* [PATCH kgl 1/4] Disable interactive OAuth flows when stdin is not a terminal
2026-12-05 6:56 [PATCH kgl 0/4] Add conditional initial-arrival delivery rules Dmitry Torokhov
@ 2026-12-05 6:56 ` Dmitry Torokhov
2026-12-05 6:56 ` [PATCH kgl 2/4] Defer Gmail OAuth loading until delivery and isolate target failures Dmitry Torokhov
` (2 subsequent siblings)
3 siblings, 0 replies; 5+ messages in thread
From: Dmitry Torokhov @ 2026-12-05 6:56 UTC (permalink / raw)
To: Kernel.org Tools; +Cc: Konstantin Ryabitsev
Target initialization previously treated any CLI invocation without
GUI mode enabled as interactive. When running unattended under systemd
timers or cron jobs where standard input is not connected to a
terminal, missing credentials or expired refresh tokens could block
indefinitely waiting for a browser OAuth callback.
Require both non-GUI mode and a terminal on standard input before
enabling interactive authentication flows for target services.
Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
---
src/korgalore/cli.py | 4 ++--
tests/test_cli_misc.py | 61 +++++++++++++++++++++++++++++++++++++++++++++++++-
2 files changed, 62 insertions(+), 3 deletions(-)
diff --git a/src/korgalore/cli.py b/src/korgalore/cli.py
index 0692ab8..68f5e2d 100644
--- a/src/korgalore/cli.py
+++ b/src/korgalore/cli.py
@@ -275,8 +275,8 @@ def get_target(ctx: click.Context, identifier: str) -> Any:
target_type = details.get('type', '')
# Instantiate based on type
- # In GUI mode, don't run interactive OAuth flows
- interactive = not ctx.obj.get('gui_mode', False)
+ # In GUI mode or non-interactive terminals, don't run interactive OAuth flows
+ interactive = not ctx.obj.get('gui_mode', False) and sys.stdin.isatty()
service: Any
if target_type == 'gmail':
service = get_gmail_target(
diff --git a/tests/test_cli_misc.py b/tests/test_cli_misc.py
index e351b0b..9c7ed0e 100644
--- a/tests/test_cli_misc.py
+++ b/tests/test_cli_misc.py
@@ -10,12 +10,14 @@ noise into somebody's debug log.
"""
import io
+from unittest.mock import patch
import click
import pytest
from korgalore import format_key_for_display
-from korgalore.cli import progress_file
+from korgalore.cli import get_target, progress_file
+from tests.digest_helpers import make_ctx
@pytest.mark.parametrize(
@@ -75,3 +77,60 @@ def test_hidden_bar_writes_nothing_to_stdout(capsys: pytest.CaptureFixture[str])
# stream is what keeps it off the user's terminal, so check it landed here.
assert isinstance(stream, io.StringIO)
assert 'Hiding' in stream.getvalue()
+
+
+def test_get_target_interactive_when_tty_and_not_gui() -> None:
+ ctx = make_ctx(
+ {
+ 'config': {'targets': {'test': {'type': 'gmail', 'credentials': 'creds.json'}}},
+ 'targets': {},
+ 'gui_mode': False,
+ }
+ )
+ with (
+ patch('sys.stdin.isatty', return_value=True),
+ patch('korgalore.cli.get_gmail_target') as mock_gmail,
+ ):
+ mock_gmail.return_value = 'target-service'
+ res = get_target(ctx, 'test')
+ assert res == 'target-service'
+ assert mock_gmail.call_args.kwargs['interactive'] is True
+ assert mock_gmail.call_args.kwargs['identifier'] == 'test'
+
+
+def test_get_target_non_interactive_when_not_tty() -> None:
+ ctx = make_ctx(
+ {
+ 'config': {'targets': {'test': {'type': 'gmail', 'credentials': 'creds.json'}}},
+ 'targets': {},
+ 'gui_mode': False,
+ }
+ )
+ with (
+ patch('sys.stdin.isatty', return_value=False),
+ patch('korgalore.cli.get_gmail_target') as mock_gmail,
+ ):
+ mock_gmail.return_value = 'target-service'
+ res = get_target(ctx, 'test')
+ assert res == 'target-service'
+ assert mock_gmail.call_args.kwargs['interactive'] is False
+ assert mock_gmail.call_args.kwargs['identifier'] == 'test'
+
+
+def test_get_target_non_interactive_when_gui_mode() -> None:
+ ctx = make_ctx(
+ {
+ 'config': {'targets': {'test': {'type': 'gmail', 'credentials': 'creds.json'}}},
+ 'targets': {},
+ 'gui_mode': True,
+ }
+ )
+ with (
+ patch('sys.stdin.isatty', return_value=True),
+ patch('korgalore.cli.get_gmail_target') as mock_gmail,
+ ):
+ mock_gmail.return_value = 'target-service'
+ res = get_target(ctx, 'test')
+ assert res == 'target-service'
+ assert mock_gmail.call_args.kwargs['interactive'] is False
+ assert mock_gmail.call_args.kwargs['identifier'] == 'test'
--
2.56.1.987.g2ec0ab4260-goog
^ permalink raw reply related [flat|nested] 5+ messages in thread* [PATCH kgl 2/4] Defer Gmail OAuth loading until delivery and isolate target failures
2026-12-05 6:56 [PATCH kgl 0/4] Add conditional initial-arrival delivery rules Dmitry Torokhov
2026-12-05 6:56 ` [PATCH kgl 1/4] Disable interactive OAuth flows when stdin is not a terminal Dmitry Torokhov
@ 2026-12-05 6:56 ` Dmitry Torokhov
2026-12-05 6:56 ` [PATCH kgl 3/4] Add initial_labels, intra-pull dedup cache, and Gmail scope upgrades Dmitry Torokhov
2026-12-05 6:56 ` [PATCH kgl 4/4] Add conditional initial-arrival delivery rules Dmitry Torokhov
3 siblings, 0 replies; 5+ messages in thread
From: Dmitry Torokhov @ 2026-12-05 6:56 UTC (permalink / raw)
To: Kernel.org Tools; +Cc: Konstantin Ryabitsev
Previously, stored OAuth tokens were loaded and validated during
configuration startup. This triggered disk access, network token
refreshes, and interactive browser prompts even on idle pulls when no
messages were pending delivery. An unhandled connection failure on one
target also aborted the entire delivery process, preventing other
healthy targets from receiving messages.
Defer token loading and refresh until deliveries actually begin,
eliminating unnecessary network and disk operations when no deliveries
are required. Consolidate target disconnect handling in a clean exit
path when pull, digest, and track operations finish.
Isolate target and digest authentication or configuration failures
during pull so healthy destinations continue processing normally while
unattempted commits are left intact instead of falsely marked failed.
Compare recorded feed state against each delivery position before
skipping unchanged feeds so subsequent pulls still resume stranded
deliveries even when no new upstream commits arrive. Expose interactive
re-authentication uniformly for the GUI, pre-validate thread-tracking
destinations before mutating state, and ensure pull, digest, yank, and
thread tracking handle lazy connection errors without unhandled
exceptions.
Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
---
src/korgalore/cli.py | 519 +++++++++++++++++++++++-----------
src/korgalore/gmail_target.py | 5 +
src/korgalore/google_creds.py | 142 +++++-----
src/korgalore/gui.py | 53 ++--
src/korgalore/imap_target.py | 5 +
src/korgalore/jmap_target.py | 13 +
src/korgalore/pi_feed.py | 42 +++
tests/test_cli_misc.py | 48 +++-
tests/test_digest_cli.py | 62 ++++
tests/test_gmail_target.py | 17 +-
tests/test_google_creds.py | 104 +++++--
tests/test_gui.py | 53 ++++
tests/test_imap_target.py | 19 ++
tests/test_jmap_target.py | 4 +
tests/test_pi_feed.py | 36 +++
tests/test_pull.py | 241 +++++++++++++++-
tests/test_tracked_thread_delivery.py | 113 +++++++-
17 files changed, 1182 insertions(+), 294 deletions(-)
diff --git a/src/korgalore/cli.py b/src/korgalore/cli.py
index 68f5e2d..1e4e3f2 100644
--- a/src/korgalore/cli.py
+++ b/src/korgalore/cli.py
@@ -17,8 +17,9 @@ from datetime import UTC, datetime
from email import policy
from email.message import EmailMessage
from email.parser import BytesParser
+from functools import wraps
from pathlib import Path
-from typing import Any, TextIO
+from typing import Any, ParamSpec, TextIO, TypeVar
import click
import click_log # type: ignore[import-untyped]
@@ -331,15 +332,6 @@ def get_target(ctx: click.Context, identifier: str) -> Any:
raise click.Abort()
ctx.obj['targets'][identifier] = service
-
- # Check if Gmail target needs authentication (in non-interactive/GUI mode)
- # Note: IMAP OAuth2 targets handle this during connect() instead, which
- # allows the 'auth' command to work properly.
- if isinstance(service, GmailTarget) and service.needs_auth:
- raise AuthenticationError(
- f"Gmail target '{identifier}' requires authentication.", target_id=identifier, target_type='gmail'
- )
-
return service
@@ -747,6 +739,8 @@ def deliver_commit(
)
feed.mark_successful_delivery(delivery_name, epoch, commit, message=raw_message, was_failing=was_failing)
return msgid
+ except (AuthenticationError, ConfigurationError):
+ raise
except Exception as e:
logger.debug('Failed to deliver commit %s from epoch %d: %s', commit, epoch, str(e))
feed.mark_failed_delivery(delivery_name, epoch, commit)
@@ -1226,21 +1220,59 @@ def start_digest_worker(ctx: click.Context) -> None:
spawn_digest_worker(ctx.obj['data_dir'], ctx.obj.get('cfgpath'))
+@contextmanager
+def record_target_failure(
+ failed_targets: dict[str, Exception],
+ target_id: str,
+ action: str,
+ *,
+ catch: tuple[type[Exception], ...] = (AuthenticationError, ConfigurationError),
+) -> Generator[None, None, None]:
+ """Catch fatal target errors, log them, and record them in ``failed_targets``."""
+ try:
+ yield
+ except catch as e:
+ logger.error("Failed %s for target '%s': %s", action, target_id, e)
+ failed_targets[target_id] = e
+
+
+def raise_first_target_failure(failed_targets: Mapping[str, Exception]) -> None:
+ """Raise the first AuthenticationError or ConfigurationError recorded in ``failed_targets``."""
+ for exc_type in (AuthenticationError, ConfigurationError):
+ err = next((e for e in failed_targets.values() if isinstance(e, exc_type)), None)
+ if err is not None:
+ raise err
+
+
def run_due_digests(
ctx: click.Context,
delivery_names: list[str],
force: bool = False,
status_callback: Callable[[str], None] | None = None,
+ failed_targets: dict[str, Exception] | None = None,
) -> dict[str, list[str]]:
"""Send the digests that are due, logging failures and moving on.
Feeds must already be locked and updated. Digests that need the digest
worker are only collected here, and the worker is started for them.
+ Args:
+ ctx: Click context containing schedules, deliveries, and config.
+ delivery_names: Digest delivery names to inspect and run if due.
+ force: Send due/unscheduled digests regardless of cadence when True.
+ status_callback: Optional progress callback invoked per digest.
+ failed_targets: Optional mapping of target identifiers to errors,
+ used both to skip digests targeting already-failed
+ destinations and to record new authentication or
+ configuration errors in pull mode.
+
Returns:
A mapping of delivery name to the Message-IDs of the digest parts
sent. Digests that sent nothing are left out.
"""
+ own_failed_targets = failed_targets is None
+ if failed_targets is None:
+ failed_targets = {}
schedules: dict[str, DigestSchedule] = ctx.obj.get('digest_schedules', {})
bozo_set = ctx.obj.get('bozofilter', set())
sent: dict[str, list[str]] = {}
@@ -1248,6 +1280,10 @@ def run_due_digests(
waiting = False
for dname in delivery_names:
feed, target, labels, subfolder = ctx.obj['deliveries'][dname]
+ target_id = target.identifier
+ if target_id in failed_targets:
+ logger.warning("Skipping digest '%s' due to earlier target '%s' failure.", dname, target_id)
+ continue
if status_callback:
status_callback(f'Checking digest {format_key_for_display(dname)}...')
schedule = schedules[dname]
@@ -1258,17 +1294,18 @@ def run_due_digests(
logger.error('Could not collect digest %s, will retry on the next run: %s', dname, e)
logger.debug('Traceback:', exc_info=True)
continue
+ parts: list[EmailMessage] = []
try:
- parts = send_digest(dname, feed, target, labels, subfolder, schedule, bozo_set, force=force)
- except AuthenticationError:
- # The GUI shows an auth button for this, so let it through
- raise
+ with record_target_failure(failed_targets, target_id, f"running digest '{dname}'"):
+ parts = send_digest(dname, feed, target, labels, subfolder, schedule, bozo_set, force=force)
except Exception as e:
logger.error('Could not send digest %s, will retry on the next run: %s', dname, e)
logger.debug('Traceback:', exc_info=True)
continue
finally:
used_targets[target.identifier] = target
+ if target_id in failed_targets:
+ continue
for part in parts:
logger.info('Sent digest %s: %s', dname, part['Subject'])
if parts:
@@ -1279,6 +1316,8 @@ def run_due_digests(
target.disconnect()
if waiting:
start_digest_worker(ctx)
+ if own_failed_targets:
+ raise_first_target_failure(failed_targets)
return sent
@@ -1708,6 +1747,34 @@ def lock_all_feeds(ctx: click.Context) -> None:
raise
+P = ParamSpec('P')
+R = TypeVar('R')
+
+
+def abort_on_target_error(func: Callable[P, R]) -> Callable[P, R]:
+ """Decorator converting target auth or configuration errors into ``click.Abort``.
+
+ Logs ``ConfigurationError`` and ``AuthenticationError`` once at command
+ level and exits cleanly with status 1 instead of printing a traceback.
+
+ Args:
+ func: Click command callback to wrap.
+
+ Returns:
+ Wrapped callback preserving the original function signature.
+ """
+
+ @wraps(func)
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
+ try:
+ return func(*args, **kwargs)
+ except (ConfigurationError, AuthenticationError) as e:
+ logger.critical('Error: %s', e)
+ raise click.Abort() from e
+
+ return wrapper
+
+
@contextmanager
def abort_if_feed_locked() -> Generator[None, None, None]:
"""Turn a busy feed into a short error message instead of a traceback."""
@@ -1725,6 +1792,26 @@ def unlock_all_feeds(ctx: click.Context) -> None:
feed.feed_unlock()
+def disconnect_all_targets(ctx: click.Context) -> None:
+ """Disconnect all cached target services in the context.
+
+ Iterates over a snapshot of instantiated targets and invokes any
+ ``disconnect()`` hook, logging failures at debug level so cleanup continues
+ across all remaining targets.
+
+ Args:
+ ctx: Click context holding cached target instances under ``targets``.
+ """
+ targets = ctx.obj.get('targets', {})
+ for target in list(targets.values()):
+ disconnect = getattr(target, 'disconnect', None)
+ if callable(disconnect):
+ try:
+ disconnect()
+ except Exception as e:
+ logger.debug('Failed to disconnect target %s: %s', target.identifier, e)
+
+
def digest_history_needs(ctx: click.Context) -> dict[str, datetime]:
"""How far back each lore feed must keep its history for its digests.
@@ -1798,8 +1885,19 @@ def update_all_feeds(
return updated_feeds, initialized_feeds
-def retry_all_failed_deliveries(ctx: click.Context) -> None:
- """Retry all previously failed deliveries across all feeds."""
+def retry_all_failed_deliveries(
+ ctx: click.Context,
+ failed_targets: dict[str, Exception] | None = None,
+) -> None:
+ """Retry all previously failed deliveries across all feeds.
+
+ Args:
+ ctx: Click context containing mapped feeds and deliveries.
+ failed_targets: Optional per-target fatal error map updated when a
+ target fails authentication or configuration.
+ """
+ if failed_targets is None:
+ failed_targets = {}
bozo_set = ctx.obj.get('bozofilter', set())
# 'deliveries' is a mapping: delivery_name -> tuple[feed, target, labels, subfolder]
@@ -1825,17 +1923,21 @@ def retry_all_failed_deliveries(ctx: click.Context) -> None:
retry_list, label='Reattempting delivery', show_pos=True, file=progress_file(ctx.obj['hide_bar'])
) as bar:
for delivery_name, target, feed, epoch, commit, labels, subfolder in bar:
- deliver_commit(
- delivery_name,
- target,
- feed,
- epoch,
- commit,
- labels,
- was_failing=True,
- bozofilter=bozo_set,
- subfolder=subfolder,
- )
+ target_id = target.identifier
+ if target_id in failed_targets:
+ continue
+ with record_target_failure(failed_targets, target_id, 'retrying delivery'):
+ deliver_commit(
+ delivery_name,
+ target,
+ feed,
+ epoch,
+ commit,
+ labels,
+ was_failing=True,
+ bozofilter=bozo_set,
+ subfolder=subfolder,
+ )
@click.group()
@@ -2076,42 +2178,29 @@ def labels(ctx: click.Context, target: str, ids: bool = False) -> None:
raise click.Abort() from e
-def perform_pull(
+def run_locked_pull(
ctx: click.Context,
no_update: bool,
force: bool,
- delivery_name: str | None,
status_callback: Callable[[str], None] | None = None,
-) -> tuple[dict[str, int], set[str]]:
- """Execute the pull logic and return changes.
+) -> tuple[dict[str, int], set[str], dict[str, Exception]]:
+ """Run feed updates, pending/new deliveries, and digests under feed locks.
+
+ Args:
+ ctx: Click context with mapped feeds, deliveries, and targets.
+ no_update: Skip updating feeds when True.
+ force: Run all non-digest deliveries even when feeds did not advance.
+ status_callback: Optional progress callback invoked by GUI syncs.
Returns:
- A tuple of (per-delivery counts dict, set of unique message-ids delivered).
- Feeds that failed to update are left in ctx.obj['failed_feeds'].
+ Tuple of (per-delivery counts dict, delivered Message-IDs set, mapping of
+ target identifiers to fatal AuthenticationError or ConfigurationError).
"""
- # Reset on every pull: the GUI calls us repeatedly with the same ctx
- ctx.obj['failed_feeds'] = []
- cfg = ctx.obj.get('config', {})
bozo_set = ctx.obj.get('bozofilter', set())
+ failed_targets: dict[str, Exception] = {}
- # Load deliveries to process
- deliveries = cfg.get('deliveries', {})
- if delivery_name:
- if delivery_name not in deliveries:
- logger.critical('Delivery "%s" not found in configuration.', delivery_name)
- raise click.Abort()
- deliveries = {delivery_name: deliveries[delivery_name]}
-
- # Collect unique feeds from all deliveries
- map_deliveries(ctx, deliveries)
-
- # Map tracked threads as ephemeral deliveries (unless specific delivery requested)
- if not delivery_name:
- map_tracked_threads(ctx)
-
- lock_all_feeds(ctx)
# Retry all previously failed deliveries, if any
- retry_all_failed_deliveries(ctx)
+ retry_all_failed_deliveries(ctx, failed_targets=failed_targets)
if no_update:
logger.debug('No-update flag set, skipping feed updates')
updated_feeds: list[str] = []
@@ -2136,27 +2225,28 @@ def perform_pull(
logger.info('Initializing delivery state: %s', dname)
feed.save_delivery_info(dname)
+ # Digests are sent on their own schedule, not message by message. They
+ # are checked on every pull, because a digest can be due even when its
+ # feed has nothing new.
+ digest_names = list(ctx.obj.get('digest_schedules', {}))
run_deliveries: list[str] = []
if not force:
logger.debug('Updated feeds: %s', ', '.join(updated_feeds))
- for feed_key in updated_feeds:
- run_deliveries.extend(feed_to_deliveries.get(feed_key, []))
+ updated_set = set(updated_feeds)
+ for dname, (feed, _, _, _) in ctx.obj['deliveries'].items():
+ if dname in digest_names:
+ continue
+ if feed.feed_key in updated_set or feed.has_pending_commits(dname):
+ run_deliveries.append(dname)
else:
# If force is specified, treat all feeds as updated
logger.debug('Force flag set, treating all feeds as updated')
- run_deliveries = list(ctx.obj['deliveries'].keys())
-
- # Digests are sent on their own schedule, not message by message. They
- # are checked on every pull, because a digest can be due even when its
- # feed has nothing new.
- digest_names = list(ctx.obj.get('digest_schedules', {}))
- run_deliveries = [dname for dname in run_deliveries if dname not in digest_names]
+ run_deliveries = [dname for dname in ctx.obj['deliveries'] if dname not in digest_names]
logger.debug('Deliveries to run: %s', ', '.join(run_deliveries))
if not run_deliveries and not digest_names:
- unlock_all_feeds(ctx)
- return {}, set()
+ return {}, set(), failed_targets
# Build a worklist of updates per target
by_target: dict[str, list[str]] = {}
@@ -2171,6 +2261,11 @@ def perform_pull(
# Process deliveries now
for target_name, delivery_names in by_target.items():
+ if target_name in failed_targets:
+ logger.warning("Skipping target '%s' due to earlier failure.", target_name)
+ continue
+
+ target_service = ctx.obj['targets'].get(target_name)
logger.debug('Processing deliveries for target: %s', target_name)
run_list: list[tuple[str, Any, LeiFeed | LoreFeed, int, str, list[str], str | None]] = []
for dname in delivery_names:
@@ -2184,6 +2279,18 @@ def perform_pull(
if not run_list:
logger.debug('No deliveries with new commits for target: %s', target_name)
continue
+
+ if target_service is not None:
+ with record_target_failure(
+ failed_targets,
+ target_name,
+ 'connecting',
+ catch=(AuthenticationError, ConfigurationError, RemoteError),
+ ):
+ target_service.connect()
+ if target_name in failed_targets:
+ continue
+
logger.debug('Delivering %d messages to target: %s', len(run_list), target_name)
with click.progressbar(
@@ -2203,17 +2310,22 @@ def perform_pull(
if consecutive_failures >= 5:
logger.error('Aborting deliveries to target "%s" due to repeated failures.', target_name)
break
- msgid = deliver_commit(
- dname,
- target,
- feed,
- epoch,
- commit,
- labels,
- was_failing=False,
- bozofilter=bozo_set,
- subfolder=subfolder,
- )
+ msgid: str | None = None
+ with record_target_failure(failed_targets, target_name, 'delivering'):
+ msgid = deliver_commit(
+ dname,
+ target,
+ feed,
+ epoch,
+ commit,
+ labels,
+ was_failing=False,
+ bozofilter=bozo_set,
+ subfolder=subfolder,
+ )
+ if target_name in failed_targets:
+ break
+
if msgid is None:
consecutive_failures += 1
continue
@@ -2228,31 +2340,69 @@ def perform_pull(
if msgid:
unique_msgids.add(msgid)
- # Disconnect target if it supports it (e.g., IMAP)
- target_service = ctx.obj['targets'].get(target_name)
- if target_service is not None and hasattr(target_service, 'disconnect'):
- target_service.disconnect()
-
if digest_names:
- try:
- sent = run_due_digests(ctx, digest_names, status_callback=status_callback)
- except AuthenticationError:
- unlock_all_feeds(ctx)
- raise
+ sent = run_due_digests(ctx, digest_names, status_callback=status_callback, failed_targets=failed_targets)
for dname, digest_msgids in sent.items():
changes[dname] = len(digest_msgids)
unique_msgids.update(digest_msgids)
- unlock_all_feeds(ctx)
+ return changes, unique_msgids, failed_targets
- # Update tracking manifest activity for any tracked threads that had deliveries
- update_tracked_thread_activity(ctx, changes)
- # Close HTTP session and clear cached targets to avoid stale session references
- close_requests_session()
- ctx.obj['targets'] = {}
+def perform_pull(
+ ctx: click.Context,
+ no_update: bool,
+ force: bool,
+ delivery_name: str | None,
+ status_callback: Callable[[str], None] | None = None,
+) -> tuple[dict[str, int], set[str]]:
+ """Execute the pull logic and return changes.
- return changes, unique_msgids
+ Returns:
+ A tuple of (per-delivery counts dict, set of unique message-ids delivered).
+ Feeds that failed to update are left in ctx.obj['failed_feeds'].
+
+ Raises:
+ AuthenticationError: If any target failed with an authentication error
+ during deliveries or digests.
+ ConfigurationError: If any target failed with a configuration error.
+ """
+ # Reset on every pull: the GUI calls us repeatedly with the same ctx
+ ctx.obj['failed_feeds'] = []
+ cfg = ctx.obj.get('config', {})
+
+ # Load deliveries to process
+ deliveries = cfg.get('deliveries', {})
+ if delivery_name:
+ if delivery_name not in deliveries:
+ logger.critical('Delivery "%s" not found in configuration.', delivery_name)
+ raise click.Abort()
+ deliveries = {delivery_name: deliveries[delivery_name]}
+
+ # Collect unique feeds from all deliveries
+ map_deliveries(ctx, deliveries)
+
+ # Map tracked threads as ephemeral deliveries (unless specific delivery requested)
+ if not delivery_name:
+ map_tracked_threads(ctx)
+
+ lock_all_feeds(ctx)
+ try:
+ changes, unique_msgids, failed_targets = run_locked_pull(
+ ctx,
+ no_update=no_update,
+ force=force,
+ status_callback=status_callback,
+ )
+ # Update tracking manifest activity for any tracked threads that had deliveries
+ update_tracked_thread_activity(ctx, changes)
+ raise_first_target_failure(failed_targets)
+ return changes, unique_msgids
+ finally:
+ disconnect_all_targets(ctx)
+ unlock_all_feeds(ctx)
+ close_requests_session()
+ ctx.obj['targets'] = {}
@main.command()
@@ -2266,6 +2416,7 @@ def perform_pull(
help='exit with status 3 if any feed failed to update (all feeds and deliveries still run)',
)
@click.argument('delivery_name', type=str, required=False)
+@abort_on_target_error
def pull(
ctx: click.Context,
max_mail: int,
@@ -2323,6 +2474,7 @@ def pull(
help='show what the next digests would send to their summarizer, without calling it or sending anything',
)
@click.argument('delivery_names', type=str, nargs=-1)
+@abort_on_target_error
def digest_cmd(
ctx: click.Context,
force: bool,
@@ -2365,6 +2517,7 @@ def digest_cmd(
try:
run_digest_worker(ctx, list(digests))
finally:
+ disconnect_all_targets(ctx)
ctx.obj['targets'] = {}
return
@@ -2382,6 +2535,7 @@ def digest_cmd(
if not sent:
logger.info('No digests were due.')
finally:
+ disconnect_all_targets(ctx)
unlock_all_feeds(ctx)
close_requests_session()
ctx.obj['targets'] = {}
@@ -2467,6 +2621,7 @@ def perform_yank(
@click.option('--labels', '-l', multiple=True, help='Labels to apply (repeatable or comma-separated)')
@click.option('--thread', '-T', is_flag=True, help='Fetch and upload the entire thread')
@click.argument('msgid_or_url', type=str, nargs=1)
+@abort_on_target_error
def yank(ctx: click.Context, target: str | None, labels: tuple[str, ...], thread: bool, msgid_or_url: str) -> None:
"""Yank a single message or entire thread to a target."""
# Get the target service
@@ -2637,6 +2792,7 @@ def track(ctx: click.Context) -> None:
@click.option('--target', '-t', default=None, help='Target for deliveries (default: first configured)')
@click.option('--labels', '-l', multiple=True, help='Labels to apply (repeatable or comma-separated)')
@click.pass_context
+@abort_on_target_error
def track_add(ctx: click.Context, msgid_or_url: str, target: str | None, labels: tuple[str, ...]) -> None:
"""Start tracking a thread by message ID or lore URL."""
config = ctx.obj.get('config', {})
@@ -2664,99 +2820,128 @@ def track_add(ctx: click.Context, msgid_or_url: str, target: str | None, labels:
logger.info('Aborted.')
return
- # Create lei search directory
- data_dir = ctx.obj.get('data_dir', get_xdg_data_dir())
- import secrets
-
- track_id = f'track-{secrets.token_hex(6)}'
- lei_path = data_dir / 'lei' / track_id
+ # Resolve target and validate connectivity/labels before creating lei search or manifest state
+ try:
+ target_service = get_target(ctx, target)
- logger.info('Creating lei search for thread: %s', msgid)
+ if labels:
+ labels_list = parse_labels(labels)
+ else:
+ labels_list = target_service.DEFAULT_LABELS
- # Create the lei search
- try:
- retcode, output = create_lei_thread_search(msgid, lei_path)
- except PublicInboxError as e:
- logger.critical('Failed to create lei search: %s', str(e))
- raise click.Abort() from e
+ try:
+ target_service.connect()
+ if labels_list and hasattr(target_service, 'translate_labels'):
+ target_service.translate_labels(labels_list)
+ except liblore.RemoteError as e:
+ logger.critical('Failed to connect to target "%s": %s', target, e)
+ raise click.Abort() from e
- if retcode != 0:
- logger.critical('Lei query failed: %s', output.decode())
- raise click.Abort()
+ # Create lei search directory
+ data_dir = ctx.obj.get('data_dir', get_xdg_data_dir())
+ import secrets
- # Populate the git repository with lei up
- logger.info('Populating lei search repository...')
- try:
- retcode, output = update_lei_search(lei_path)
- except PublicInboxError as e:
- logger.critical('Failed to update lei search: %s', str(e))
- raise click.Abort() from e
+ track_id = f'track-{secrets.token_hex(6)}'
+ lei_path = data_dir / 'lei' / track_id
- if retcode != 0:
- logger.critical('Lei update failed: %s', output.decode())
- raise click.Abort()
+ logger.info('Creating lei search for thread: %s', msgid)
- # Get the subject from the first message
- subject = '(unknown subject)'
- try:
- node = get_lore_node(ctx)
- raw_message = node.get_message_by_msgid(msgid)
- msg = parse_message(raw_message)
- subject = msg_get_subject(msg) or '(no subject)'
- except liblore.RemoteError:
- logger.warning('Could not fetch message to get subject')
+ # Create the lei search
+ try:
+ retcode, output = create_lei_thread_search(msgid, lei_path)
+ except PublicInboxError as e:
+ logger.critical('Failed to create lei search: %s', str(e))
+ raise click.Abort() from e
- # Thread archives are named after a random track id, so the subject is
- # the only thing that identifies them in a public-inbox listing.
- write_archive_description(lei_path, subject)
+ if retcode != 0:
+ logger.critical('Lei query failed: %s', output.decode())
+ raise click.Abort()
- # Get target instance for delivery and default labels
- target_service = get_target(ctx, target)
+ # Populate the git repository with lei up
+ logger.info('Populating lei search repository...')
+ try:
+ retcode, output = update_lei_search(lei_path)
+ except PublicInboxError as e:
+ logger.critical('Failed to update lei search: %s', str(e))
+ raise click.Abort() from e
- # Add to manifest with target-specific default labels if none specified
- if labels:
- labels_list = parse_labels(labels)
- else:
- labels_list = target_service.DEFAULT_LABELS
+ if retcode != 0:
+ logger.critical('Lei update failed: %s', output.decode())
+ raise click.Abort()
- thread = manifest.add_thread(
- track_id=track_id, msgid=msgid, subject=subject, target=target, labels=labels_list, lei_path=lei_path
- )
+ # Get the subject from the first message
+ subject = '(unknown subject)'
+ try:
+ node = get_lore_node(ctx)
+ raw_message = node.get_message_by_msgid(msgid)
+ msg = parse_message(raw_message)
+ subject = msg_get_subject(msg) or '(no subject)'
+ except liblore.RemoteError:
+ logger.warning('Could not fetch message to get subject')
- logger.info('Now tracking thread %s: %s', thread.track_id, subject)
- logger.info('Target: %s, Labels: %s', target, ', '.join(labels_list))
+ # Thread archives are named after a random track id, so the subject is
+ # the only thing that identifies them in a public-inbox listing.
+ write_archive_description(lei_path, subject)
- # Deliver initial messages to target
- lei_url = f'lei:{lei_path}'
- try:
- lei_feed = LeiFeed(thread.track_id, lei_url)
- except ConfigurationError as e:
- logger.warning('Could not initialize lei feed for delivery: %s', str(e))
- return
+ thread = manifest.add_thread(
+ track_id=track_id, msgid=msgid, subject=subject, target=target, labels=labels_list, lei_path=lei_path
+ )
- # Get all commits in epoch 0 (lei thread searches won't exceed a single epoch)
- commits = lei_feed.get_all_commits_in_epoch(0)
+ logger.info('Now tracking thread %s: %s', thread.track_id, subject)
+ logger.info('Target: %s, Labels: %s', target, ', '.join(labels_list))
- if not commits:
- logger.info('No messages found in thread yet.')
- return
+ # Deliver initial messages to target
+ lei_url = f'lei:{lei_path}'
+ try:
+ lei_feed = LeiFeed(thread.track_id, lei_url)
+ except ConfigurationError as e:
+ logger.warning('Could not initialize lei feed for delivery: %s', str(e))
+ return
- logger.info('Delivering %d messages to target...', len(commits))
+ # Get all commits in epoch 0 (lei thread searches won't exceed a single epoch)
+ commits = lei_feed.get_all_commits_in_epoch(0)
- bozo_set = ctx.obj.get('bozofilter', set())
- delivered = 0
- for commit in commits:
- result = deliver_commit(
- thread.track_id, target_service, lei_feed, 0, commit, labels_list, was_failing=False, bozofilter=bozo_set
- )
- if result and result not in (SKIPPED_BOZOFILTER, SKIPPED_NOOP_COMMIT):
- delivered += 1
+ if not commits:
+ logger.info('No messages found in thread yet.')
+ return
- # Initialize feed state so subsequent pulls don't re-initialize
- lei_feed.init_feed()
+ logger.info('Delivering %d messages to target...', len(commits))
- manifest.update_activity(thread.track_id, delivered)
- logger.info('Delivered %d messages.', delivered)
+ bozo_set = ctx.obj.get('bozofilter', set())
+ delivered = 0
+ for idx, commit in enumerate(commits):
+ try:
+ result = deliver_commit(
+ thread.track_id,
+ target_service,
+ lei_feed,
+ 0,
+ commit,
+ labels_list,
+ was_failing=False,
+ bozofilter=bozo_set,
+ )
+ except (AuthenticationError, ConfigurationError):
+ # Keep unattempted commits recoverable on subsequent pulls before aborting
+ for failed_commit in commits[idx:]:
+ lei_feed.mark_failed_delivery(thread.track_id, 0, failed_commit)
+ lei_feed.save_delivery_info(thread.track_id, 0, latest_commit=commits[-1])
+ lei_feed.init_feed()
+ if delivered:
+ manifest.update_activity(thread.track_id, delivered)
+ raise
+ if result and result not in (SKIPPED_BOZOFILTER, SKIPPED_NOOP_COMMIT):
+ delivered += 1
+
+ # Initialize feed state so subsequent pulls don't re-initialize
+ lei_feed.init_feed()
+
+ manifest.update_activity(thread.track_id, delivered)
+ logger.info('Delivered %d messages.', delivered)
+ finally:
+ disconnect_all_targets(ctx)
+ close_requests_session()
+ ctx.obj['targets'] = {}
@track.command('list')
diff --git a/src/korgalore/gmail_target.py b/src/korgalore/gmail_target.py
index f294f43..5a08f40 100644
--- a/src/korgalore/gmail_target.py
+++ b/src/korgalore/gmail_target.py
@@ -70,6 +70,11 @@ class GmailTarget:
# asking for one would only send the user into a flow that cannot help.
return isinstance(self.creds, OAuthFileCredentials) and self.creds.needs_auth
+ @property
+ def can_reauthenticate(self) -> bool:
+ """Return True if target credentials support interactive reauthentication."""
+ return isinstance(self.creds, OAuthFileCredentials)
+
def connect(self) -> None:
"""Establish connection to the Gmail API service.
diff --git a/src/korgalore/google_creds.py b/src/korgalore/google_creds.py
index bf32deb..eb07c1d 100644
--- a/src/korgalore/google_creds.py
+++ b/src/korgalore/google_creds.py
@@ -39,19 +39,22 @@ class OAuthFileCredentials(BaseCredentials):
) -> None:
"""Initialize file-backed OAuth credentials for a Google target.
+ Stores configuration and paths only; token loading and network
+ refresh are deferred until ``refresh()`` is called during
+ ``connect()`` so idle pulls perform no credential I/O.
+
Args:
identifier: Unique identifier for this target.
credentials_file: Path to the Google OAuth credentials JSON file.
token_file: Path to store/load the OAuth token.
scopes: OAuth scopes to request when running interactive auth.
interactive: If True, run OAuth flow interactively when needed.
- If False, record ``needs_auth`` instead (for GUI mode).
+ If False, raise ``AuthenticationError`` on
+ ``refresh()`` instead (for GUI/unattended mode).
target_type: Target type string reported in AuthenticationError.
Raises:
- ConfigurationError: If credentials file path is empty or missing.
- AuthenticationError: If token is expired/revoked and re-auth is needed,
- or if an interactive OAuth flow fails.
+ ConfigurationError: If credentials file path is empty.
"""
self._creds: OAuthCredentials | None = None
super().__init__() # type: ignore[no-untyped-call]
@@ -67,59 +70,27 @@ class OAuthFileCredentials(BaseCredentials):
self._credentials_file = Path(os.path.expandvars(credentials_file)).expanduser()
self._token_file = Path(os.path.expandvars(os.fspath(token_file))).expanduser()
- self._load_credentials()
-
- def _load_credentials(self) -> None:
- """Load or refresh OAuth credentials for API access.
+ def _load_token_file(self) -> bool:
+ """Load stored OAuth credentials from disk if not already loaded.
- Attempts to load existing credentials from ``self._token_file``. If
- not present or expired, refreshes with the stored refresh token or
- initiates the OAuth flow using ``self._credentials_file``.
-
- Raises:
- ConfigurationError: If credentials file is not found.
- AuthenticationError: If token is expired/revoked and re-auth is needed.
+ Returns:
+ True if credentials were loaded from disk during this call.
"""
+ if self._creds is not None or not self._token_file.exists():
+ return False
# The file token.json stores the user's access and refresh tokens
- if self._token_file.exists():
- try:
- self._creds = Credentials.from_authorized_user_file(str(self._token_file)) # type: ignore[no-untyped-call]
- except Exception as e:
- logger.warning('Failed to load OAuth token for %s from %s: %s', self.identifier, self._token_file, e)
- self._creds = None
-
- # If there are no (valid) credentials available, let the user log in
- if not self._creds or not self._creds.valid:
- if self._creds and self._creds.expired and self._creds.refresh_token:
- try:
- self._creds.refresh(Request()) # type: ignore[no-untyped-call]
- self._save_token()
- except RefreshError as e:
- logger.warning('OAuth token for target %s has expired or been revoked.', self.identifier)
- self._quarantine_token()
- self.needs_auth = True
- if not self._interactive:
- # In non-interactive mode, just return - caller will check needs_auth
- return
- raise AuthenticationError(
- f"OAuth token for '{self.identifier}' is invalid. Please re-authenticate.",
- target_id=self.identifier,
- target_type=self._target_type,
- ) from e
- elif not self._credentials_file.exists():
- raise ConfigurationError(
- f"Credentials file not found for target '{self.identifier}': {self._credentials_file}"
- )
- elif not self._interactive:
- # In non-interactive mode (GUI), don't run OAuth flow
- # Just mark as needing auth and return - caller will check needs_auth
- self.needs_auth = True
- return
- else:
- self.reauthenticate()
- return
-
- self.needs_auth = False
+ try:
+ self._creds = Credentials.from_authorized_user_file(str(self._token_file)) # type: ignore[no-untyped-call]
+ return True
+ except Exception as e:
+ logger.warning(
+ "Failed to load token file '%s' for target '%s': %s",
+ self._token_file,
+ self.identifier,
+ e,
+ )
+ self._creds = None
+ return False
@property
def token(self) -> str | None:
@@ -163,41 +134,60 @@ class OAuthFileCredentials(BaseCredentials):
self._token_file.rename(invalid_token_file)
def refresh(self, request: Any = None) -> None:
- """Refresh the access token using the stored refresh token.
+ """Load stored credentials or refresh the access token.
+
+ On first call with an unloaded but still valid stored token, avoids
+ an unnecessary network refresh. Subsequent calls (such as when
+ ``google-auth`` retries after a mid-session HTTP 401) always refresh.
Args:
request: Optional Google auth transport request object.
Raises:
- ConfigurationError: If credentials file is missing during
- interactive re-authentication.
- AuthenticationError: If refresh fails or no token is loaded in
- non-interactive mode.
+ ConfigurationError: If client secrets file is missing when
+ authentication is needed.
+ AuthenticationError: If refresh fails or authentication is needed
+ in non-interactive mode.
"""
- if self._creds is None:
- if self._interactive:
- self.reauthenticate()
+ just_loaded = self._load_token_file()
+ if just_loaded and self._creds and self._creds.valid:
+ self.needs_auth = False
+ return
+
+ req = request or Request()
+ # If there are no (valid) credentials available, refresh or let the user log in
+ if self._creds and self._creds.refresh_token:
+ try:
+ self._creds.refresh(req) # type: ignore[no-untyped-call]
+ self._save_token()
+ self.needs_auth = False
return
+ except RefreshError as e:
+ logger.warning('OAuth token for target %s has expired or been revoked.', self.identifier)
+ self._quarantine_token()
+ self._creds = None
+ if not self._interactive:
+ self.needs_auth = True
+ # In non-interactive mode (GUI), fail fast so the UI can prompt re-auth
+ raise AuthenticationError(
+ f"OAuth token for '{self.identifier}' is invalid. Please re-authenticate.",
+ target_id=self.identifier,
+ target_type=self._target_type,
+ ) from e
+
+ if not self._credentials_file.exists():
+ raise ConfigurationError(
+ f"Credentials file not found for target '{self.identifier}': {self._credentials_file}"
+ )
+ if not self._interactive:
self.needs_auth = True
+ # Never block unattended timers/GUI threads on a local browser server
raise AuthenticationError(
f"Target '{self.identifier}' requires authentication.",
target_id=self.identifier,
target_type=self._target_type,
)
- req = request or Request()
- try:
- self._creds.refresh(req) # type: ignore[no-untyped-call]
- except RefreshError as e:
- logger.warning('OAuth token for target %s has expired or been revoked.', self.identifier)
- self._quarantine_token()
- self.needs_auth = True
- raise AuthenticationError(
- f"Failed to refresh credentials for target '{self.identifier}': {e}",
- target_id=self.identifier,
- target_type=self._target_type,
- ) from e
- self._save_token()
- self.needs_auth = False
+ self.reauthenticate()
def reauthenticate(self) -> None:
"""Perform OAuth re-authentication flow.
diff --git a/src/korgalore/gui.py b/src/korgalore/gui.py
index 8744932..f6a4300 100644
--- a/src/korgalore/gui.py
+++ b/src/korgalore/gui.py
@@ -18,6 +18,7 @@ import liblore
from korgalore import AuthenticationError, __version__
from korgalore.bozofilter import ensure_bozofilter_exists, load_bozofilter
from korgalore.cli import (
+ get_target,
get_xdg_config_dir,
load_config,
perform_pull,
@@ -25,17 +26,27 @@ from korgalore.cli import (
refresh_subfolder_templates,
validate_config_file,
)
-from korgalore.gmail_target import GmailTarget
# Optional GTK/AppIndicator3 support, resolved at import time by gtk_compat,
# which also handles the AyatanaAppIndicator3 naming used on some systems.
# All four namespaces are None unless HAS_GTK is True.
from korgalore.gtk_compat import HAS_GTK, AppIndicator3, Gio, GLib, Gtk
-from korgalore.imap_target import ImapTarget
logger = logging.getLogger('korgalore.gui')
+def target_can_reauthenticate(target: Any) -> bool:
+ """Return True if target supports interactive browser re-authentication.
+
+ Args:
+ target: Target service instance or None.
+
+ Returns:
+ True when the target advertises interactive re-authentication support.
+ """
+ return bool(getattr(target, 'can_reauthenticate', False))
+
+
class KorgaloreApp:
"""Korgalore Taskbar Application."""
@@ -547,9 +558,19 @@ class KorgaloreApp:
except AuthenticationError as e:
logger.error('Authentication required for %s: %s', e.target_id, str(e))
- self.auth_needed_target = e.target_id
- self.update_status(f'Auth required: {e.target_id}', 'dialog-password-symbolic')
- GLib.idle_add(self._show_auth_button)
+ target = self.ctx.obj.get('targets', {}).get(e.target_id)
+ if target is None and e.target_id:
+ try:
+ target = get_target(self.ctx, e.target_id)
+ except Exception:
+ target = None
+ if target_can_reauthenticate(target):
+ self.auth_needed_target = e.target_id
+ self.update_status(f'Auth required: {e.target_id}', 'dialog-password-symbolic')
+ GLib.idle_add(self._show_auth_button)
+ else:
+ self.auth_needed_target = None
+ self.update_status(f'Auth failed: {e.target_id}', 'dialog-error-symbolic')
except liblore.OperationCancelledError:
# Raised when the nodes are cancelled mid-sync, either by quit()
# shutting them down or by the network dropping. Neither is an
@@ -601,21 +622,19 @@ class KorgaloreApp:
GLib.idle_add(lambda: self.item_auth.set_sensitive(False))
try:
- # Find the target in our context
+ # Find the target in our context, or instantiate it
targets = self.ctx.obj.get('targets', {})
target = targets.get(target_id)
-
if target is None:
- logger.error('Target %s not found in context', target_id)
- self.update_status('Error: Target not found', 'dialog-error-symbolic')
- return
-
- # Check if target supports re-authentication
- if isinstance(target, GmailTarget):
- # Run the Gmail re-authentication flow (this opens a browser)
- target.reauthenticate()
- elif isinstance(target, ImapTarget) and target.auth_type == 'oauth2':
- # Run the IMAP OAuth2 re-authentication flow (this opens a browser)
+ try:
+ target = get_target(self.ctx, target_id)
+ except Exception as e:
+ logger.error('Failed to get target %s: %s', target_id, e)
+ self.update_status('Error: Target not found', 'dialog-error-symbolic')
+ return
+
+ # Run the Gmail/IMAP OAuth2 re-authentication flow (this opens a browser)
+ if target_can_reauthenticate(target):
target.reauthenticate()
else:
logger.error('Target %s does not support re-authentication', target_id)
diff --git a/src/korgalore/imap_target.py b/src/korgalore/imap_target.py
index a7baf7a..73bc280 100644
--- a/src/korgalore/imap_target.py
+++ b/src/korgalore/imap_target.py
@@ -125,6 +125,11 @@ class ImapTarget:
return self._oauth2_authenticator.needs_auth
return False
+ @property
+ def can_reauthenticate(self) -> bool:
+ """Return True if target uses interactive OAuth2 authentication."""
+ return self.auth_type == 'oauth2'
+
def reauthenticate(self) -> None:
"""Perform OAuth2 re-authentication flow.
diff --git a/src/korgalore/jmap_target.py b/src/korgalore/jmap_target.py
index 6811766..35dc59e 100644
--- a/src/korgalore/jmap_target.py
+++ b/src/korgalore/jmap_target.py
@@ -404,3 +404,16 @@ class JmapTarget:
"""
mailboxes = self.list_mailboxes()
return [{'name': mb['name'], 'id': mb['id']} for mb in mailboxes]
+
+ def translate_labels(self, labels: list[str]) -> list[str]:
+ """Translate folder/label names to JMAP mailbox IDs.
+
+ Delegates to ``translate_folders`` for uniform target interface compatibility.
+
+ Args:
+ labels: List of mailbox/folder names to translate.
+
+ Returns:
+ List of corresponding JMAP mailbox IDs.
+ """
+ return self.translate_folders(labels)
diff --git a/src/korgalore/pi_feed.py b/src/korgalore/pi_feed.py
index b605a28..4e6c739 100644
--- a/src/korgalore/pi_feed.py
+++ b/src/korgalore/pi_feed.py
@@ -812,6 +812,48 @@ class PIFeed:
info = self._read_delivery_info(delivery_name)
return bool(info and info.get('epochs'))
+ def has_pending_commits(self, delivery_name: str) -> bool:
+ """Return whether recorded feed state is ahead of a delivery pointer.
+
+ Compares cached epoch and latest-commit metadata in ``korgalore.feed``
+ against the delivery's state file without spawning ``git`` on idle
+ pulls. When an earlier pull updated the feed repository and recorded
+ the new tip but aborted or skipped a target due to a transient error,
+ subsequent pulls with no new upstream commits still see pending work
+ and resume delivery automatically.
+
+ Args:
+ delivery_name: Delivery identifier whose state file is inspected.
+
+ Returns:
+ True if the feed has recorded epochs or commits beyond the
+ delivery's last recorded position, False otherwise.
+ """
+ info = self._read_delivery_info(delivery_name)
+ if not info:
+ return False
+ deliv_epochs = info.get('epochs')
+ if not isinstance(deliv_epochs, dict) or not deliv_epochs:
+ return False
+
+ feed_state_file = self._get_state_file_path(delivery_name=None, suffix='feed')
+ if not feed_state_file.exists():
+ return False
+ with feed_state_file.open() as gf:
+ feed_state = json.load(gf)
+ feed_epochs = feed_state.get('epochs') if isinstance(feed_state, dict) else None
+ if not isinstance(feed_epochs, dict) or not feed_epochs:
+ return False
+
+ highest_feed_epoch = max(int(e) for e in feed_epochs)
+ highest_deliv_epoch = max(int(e) for e in deliv_epochs)
+ if highest_feed_epoch != highest_deliv_epoch:
+ return highest_feed_epoch > highest_deliv_epoch
+
+ feed_latest = feed_epochs[str(highest_feed_epoch)].get('latest_commit')
+ deliv_last = deliv_epochs[str(highest_deliv_epoch)].get('last')
+ return bool(feed_latest and feed_latest != deliv_last)
+
def load_digest_sent(self, delivery_name: str) -> datetime | None:
"""Return when the last digest of a delivery was sent, or None if never."""
info = self._read_delivery_info(delivery_name)
diff --git a/tests/test_cli_misc.py b/tests/test_cli_misc.py
index 9c7ed0e..427e8c6 100644
--- a/tests/test_cli_misc.py
+++ b/tests/test_cli_misc.py
@@ -10,13 +10,16 @@ noise into somebody's debug log.
"""
import io
-from unittest.mock import patch
+from pathlib import Path
+from unittest.mock import MagicMock, patch
import click
import pytest
+from click.testing import CliRunner
from korgalore import format_key_for_display
-from korgalore.cli import get_target, progress_file
+from korgalore.cli import get_target, progress_file, pull
+from korgalore.gmail_target import GmailTarget, make_gmail_credentials
from tests.digest_helpers import make_ctx
@@ -79,6 +82,47 @@ def test_hidden_bar_writes_nothing_to_stdout(capsys: pytest.CaptureFixture[str])
assert 'Hiding' in stream.getvalue()
+def test_pull_token_command_nonexistent_executable_aborts() -> None:
+ runner = CliRunner()
+ mock_feed = MagicMock()
+ mock_feed.feed_key = 'test-feed'
+ mock_feed.get_latest_commits_for_delivery.return_value = [(0, 'deadbeef')]
+ mock_feed.is_noop_commit.return_value = False
+ mock_feed.get_message_at_commit.return_value = b'From: test@example.com\n\nBody\n'
+
+ creds = make_gmail_credentials(
+ 'test-target',
+ {'token_command': '/nonexistent/korgalore-auth-token'},
+ Path('/nonexistent/korgalore'),
+ )
+ target = GmailTarget('test-target', creds)
+
+ ctx_obj = {
+ 'config': {
+ 'targets': {'test-target': {'type': 'gmail', 'token_command': '/nonexistent/korgalore-auth-token'}},
+ 'deliveries': {'test-deliv': {'target': 'test-target', 'feeds': ['test-feed']}},
+ },
+ 'feeds': {'test-feed': mock_feed},
+ 'deliveries': {'test-deliv': (mock_feed, target, ['INBOX'], None)},
+ 'targets': {'test-target': target},
+ 'bozofilter': set(),
+ 'hide_bar': True,
+ }
+
+ with (
+ patch('korgalore.cli.map_deliveries'),
+ patch('korgalore.cli.map_tracked_threads'),
+ patch('korgalore.cli.retry_all_failed_deliveries'),
+ ):
+ res = runner.invoke(pull, ['--no-update', '--force'], obj=ctx_obj)
+ assert res.exit_code == 1
+ assert res.exception is not None
+ assert isinstance(res.exception, SystemExit)
+ mock_feed.feed_lock.assert_called_once()
+ mock_feed.feed_unlock.assert_called_once()
+ mock_feed.mark_failed_delivery.assert_not_called()
+
+
def test_get_target_interactive_when_tty_and_not_gui() -> None:
ctx = make_ctx(
{
diff --git a/tests/test_digest_cli.py b/tests/test_digest_cli.py
index c7d94f1..21942b7 100644
--- a/tests/test_digest_cli.py
+++ b/tests/test_digest_cli.py
@@ -67,6 +67,61 @@ class TestRunDueDigests:
with patch('korgalore.cli.send_digest', side_effect=error), pytest.raises(AuthenticationError):
run_due_digests(make_ctx(obj), ['gmail'])
+ @pytest.mark.parametrize(
+ 'error',
+ [
+ ConfigurationError('missing label'),
+ AuthenticationError('expired', target_id='t1'),
+ ],
+ ids=['config-error', 'auth-error'],
+ )
+ def test_config_error_goes_to_caller_without_failed_targets(self, error: Exception) -> None:
+ """Standalone callers isolate target errors across digests and raise at the end."""
+ t1 = _target('t1')
+ t2 = _target('t2')
+ obj = self._obj({'bad': t1, 'bad2': t1, 'good': t2})
+ good_digest = {'Subject': 'ok digest', 'Message-ID': '<ok@x>'}
+
+ def fake_send(dname: str, *args: Any, **kwargs: Any) -> Any:
+ if dname == 'bad':
+ raise error
+ return [good_digest]
+
+ with (
+ patch('korgalore.cli.send_digest', side_effect=fake_send) as mock_send,
+ pytest.raises(type(error)) as exc_info,
+ ):
+ run_due_digests(make_ctx(obj), ['bad', 'bad2', 'good'])
+
+ assert exc_info.value is error
+ assert [call.args[0] for call in mock_send.call_args_list] == ['bad', 'good']
+ t1.disconnect.assert_called_once()
+ t2.disconnect.assert_called_once()
+
+ @pytest.mark.parametrize(
+ 'error',
+ [
+ AuthenticationError('expired', target_id='t1'),
+ ConfigurationError('bad label'),
+ ],
+ ids=['auth-error', 'config-error'],
+ )
+ def test_errors_isolated_when_failed_targets_passed(self, error: Exception) -> None:
+ """With failed_targets, failing digests record target error and other targets still send."""
+ obj = self._obj({'bad': _target('t1'), 'good': _target('t2')})
+ failed_targets: dict[str, Exception] = {}
+
+ def fake_send(dname: str, *args: Any, **kwargs: Any) -> Any:
+ if dname == 'bad':
+ raise error
+ return [{'Subject': 'ok digest', 'Message-ID': '<ok@x>'}]
+
+ with patch('korgalore.cli.send_digest', side_effect=fake_send):
+ sent = run_due_digests(make_ctx(obj), ['bad', 'good'], force=True, failed_targets=failed_targets)
+
+ assert failed_targets == {'t1': error}
+ assert sent == {'good': ['<ok@x>']}
+
LOCAL = {'type': 'openai', 'url': 'http://localhost:11434/v1', 'model': 'qwen3:32b'}
REMOTE = {'type': 'openai', 'url': 'https://llm.example.org/v1', 'model': 'big'}
@@ -173,6 +228,7 @@ def _pull_obj() -> dict[str, Any]:
feed.STATUS_UPDATED = PIFeed.STATUS_UPDATED
feed.STATUS_INITIALIZED = PIFeed.STATUS_INITIALIZED
feed.STATUS_NOCHANGE = PIFeed.STATUS_NOCHANGE
+ feed.has_pending_commits.return_value = False
feed.get_latest_commits_for_delivery.return_value = [(0, 'abc')]
target = _target('local')
return {
@@ -305,6 +361,12 @@ class TestDigestCommand:
assert result.exit_code != 0
env['unlock'].assert_called_once()
+ def test_config_error_exits_1(self, env: dict[str, MagicMock]) -> None:
+ env['due'].side_effect = ConfigurationError('missing label')
+ result = invoke_digest(cli_obj())
+ assert result.exit_code == 1
+ env['unlock'].assert_called_once()
+
def test_no_digests_configured(self, env: dict[str, MagicMock]) -> None:
obj = cli_obj()
del obj['config']['deliveries'][DNAME]
diff --git a/tests/test_gmail_target.py b/tests/test_gmail_target.py
index 42b161f..35c37c2 100644
--- a/tests/test_gmail_target.py
+++ b/tests/test_gmail_target.py
@@ -106,6 +106,17 @@ class TestGmailTargetInit:
with pytest.raises(AuthenticationError, match='does not support interactive reauthentication'):
target.reauthenticate()
+ def test_can_reauthenticate(self, tmp_path: Path) -> None:
+ """can_reauthenticate is True for file credentials and False for token_command."""
+ creds_file = tmp_path / 'creds.json'
+ creds_file.write_text('{}')
+ file_creds = OAuthFileCredentials('file', str(creds_file), tmp_path / 'token.json', SCOPES)
+ cmd_creds = CommandCredentials('cmd', ['echo', 'tok'])
+
+ assert GmailTarget('file', file_creds).can_reauthenticate is True
+ assert GmailTarget('cmd', cmd_creds).can_reauthenticate is False
+ assert GmailTarget('base', MagicMock(spec=BaseCredentials)).can_reauthenticate is False
+
class TestGmailTargetConnect:
"""Tests for GmailTarget connect method."""
@@ -434,7 +445,11 @@ class TestMakeGmailCredentials:
mock_credentials.from_authorized_user_file.return_value = MagicMock(valid=True)
creds = make_gmail_credentials('personal', {'credentials': str(tmp_path / 'creds.json')}, tmp_path)
+ assert isinstance(creds, OAuthFileCredentials)
+ valid_before = creds.valid
+ assert not valid_before
+ creds.refresh(None)
+ assert creds.valid
mock_credentials.from_authorized_user_file.assert_called_once_with(str(default_token))
- assert isinstance(creds, OAuthFileCredentials)
assert creds._scopes == SCOPES
diff --git a/tests/test_google_creds.py b/tests/test_google_creds.py
index b1027b7..7907feb 100644
--- a/tests/test_google_creds.py
+++ b/tests/test_google_creds.py
@@ -26,7 +26,7 @@ class TestOAuthFileCredentials:
@patch('korgalore.google_creds.Credentials')
def test_loads_existing_valid_token(self, mock_credentials: MagicMock, tmp_path: Path) -> None:
- """Loads credentials from the stored token when already valid."""
+ """Token loading waits for refresh(); valid token skips network refresh."""
token = tmp_path / 'token.json'
token.write_text('{}')
mock_creds = MagicMock()
@@ -36,10 +36,15 @@ class TestOAuthFileCredentials:
provider = OAuthFileCredentials('test', str(tmp_path / 'creds.json'), token, scopes=TEST_SCOPES)
+ valid_before = provider.valid
+ assert not valid_before
+ mock_credentials.from_authorized_user_file.assert_not_called()
+
+ provider.refresh()
assert provider.valid
assert provider.token == 'access-tok'
- assert not provider.needs_auth
mock_credentials.from_authorized_user_file.assert_called_once_with(str(token))
+ mock_creds.refresh.assert_not_called()
@patch('korgalore.google_creds.Credentials')
@patch('korgalore.google_creds.Request')
@@ -56,7 +61,8 @@ class TestOAuthFileCredentials:
mock_creds.to_json.return_value = '{"token": "refreshed"}'
mock_credentials.from_authorized_user_file.return_value = mock_creds
- OAuthFileCredentials('test', str(tmp_path / 'creds.json'), token, scopes=TEST_SCOPES)
+ provider = OAuthFileCredentials('test', str(tmp_path / 'creds.json'), token, scopes=TEST_SCOPES)
+ provider.refresh()
mock_creds.refresh.assert_called_once()
assert token.read_text() == '{"token": "refreshed"}'
@@ -84,7 +90,7 @@ class TestOAuthFileCredentials:
mock_credentials.from_authorized_user_file.return_value = mock_creds
with pytest.raises(UnicodeEncodeError):
- OAuthFileCredentials('test', str(tmp_path / 'creds.json'), token, scopes=TEST_SCOPES)
+ OAuthFileCredentials('test', str(tmp_path / 'creds.json'), token, scopes=TEST_SCOPES).refresh()
assert token.read_text() == '{"token": "stale"}'
assert [p.name for p in tmp_path.iterdir()] == ['token.json']
@@ -99,18 +105,40 @@ class TestOAuthFileCredentials:
old_umask = os.umask(0)
try:
- OAuthFileCredentials('test', str(creds), token, scopes=TEST_SCOPES)
+ OAuthFileCredentials('test', str(creds), token, scopes=TEST_SCOPES).refresh()
finally:
os.umask(old_umask)
assert (token.stat().st_mode & 0o777) == 0o600
+ @patch('korgalore.google_creds.Credentials')
+ @patch('korgalore.google_creds.Request')
+ def test_second_refresh_on_loaded_valid_creds_forces_token_refresh(
+ self, mock_request: MagicMock, mock_credentials: MagicMock, tmp_path: Path
+ ) -> None:
+ """A second refresh() after mid-session 401 refreshes even if locally valid."""
+ token = tmp_path / 'token.json'
+ token.write_text('{"token": "initial"}')
+ mock_creds = MagicMock()
+ mock_creds.valid = True
+ mock_creds.refresh_token = 'refresh_token_value'
+ mock_creds.to_json.return_value = '{"token": "forced-refresh"}'
+ mock_credentials.from_authorized_user_file.return_value = mock_creds
+
+ provider = OAuthFileCredentials('test', str(tmp_path / 'creds.json'), token, scopes=TEST_SCOPES)
+ provider.refresh()
+ mock_creds.refresh.assert_not_called()
+
+ provider.refresh()
+ mock_creds.refresh.assert_called_once()
+ assert token.read_text() == '{"token": "forced-refresh"}'
+
@patch('korgalore.google_creds.Credentials')
@patch('korgalore.google_creds.Request')
def test_revoked_token_is_set_aside(
self, mock_request: MagicMock, mock_credentials: MagicMock, tmp_path: Path
) -> None:
- """A token that fails to refresh is renamed aside and needs_auth is flagged."""
+ """A revoked token is moved aside and raises AuthenticationError when non-interactive."""
token = tmp_path / 'token.json'
token.write_text('{"token": "revoked"}')
invalid = tmp_path / 'token.json.invalid'
@@ -125,35 +153,47 @@ class TestOAuthFileCredentials:
provider = OAuthFileCredentials(
'test', str(tmp_path / 'creds.json'), token, scopes=TEST_SCOPES, interactive=False
)
+ with pytest.raises(AuthenticationError, match='invalid'):
+ provider.refresh()
- assert provider.needs_auth
assert not token.exists()
assert invalid.read_text() == '{"token": "revoked"}'
+ @patch('korgalore.google_creds.InstalledAppFlow')
@patch('korgalore.google_creds.Credentials')
@patch('korgalore.google_creds.Request')
- def test_revoked_token_interactive_raises_authentication_error(
- self, mock_request: MagicMock, mock_credentials: MagicMock, tmp_path: Path
+ def test_revoked_token_interactive_reauthenticates(
+ self, mock_request: MagicMock, mock_credentials: MagicMock, mock_flow_class: MagicMock, tmp_path: Path
) -> None:
- """Interactive load raises AuthenticationError when token refresh is revoked."""
+ """Interactive refresh falls back to OAuth reauthentication when refresh is revoked."""
+ creds = tmp_path / 'creds.json'
+ creds.write_text('{}')
token = tmp_path / 'token.json'
token.write_text('{"token": "revoked"}')
- mock_creds = MagicMock()
- mock_creds.valid = False
- mock_creds.expired = True
- mock_creds.refresh_token = 'refresh_token_value'
- mock_creds.refresh.side_effect = RefreshError
- mock_credentials.from_authorized_user_file.return_value = mock_creds
+ old_creds = MagicMock()
+ old_creds.valid = False
+ old_creds.refresh_token = 'refresh_token_value'
+ old_creds.refresh.side_effect = RefreshError
+ mock_credentials.from_authorized_user_file.return_value = old_creds
+
+ fresh_creds = MagicMock()
+ fresh_creds.valid = True
+ fresh_creds.to_json.return_value = '{"token": "fresh"}'
+ mock_flow = MagicMock()
+ mock_flow.run_local_server.return_value = fresh_creds
+ mock_flow_class.from_client_secrets_file.return_value = mock_flow
- with pytest.raises(AuthenticationError, match='invalid'):
- OAuthFileCredentials('test', str(tmp_path / 'creds.json'), token, scopes=TEST_SCOPES, interactive=True)
+ provider = OAuthFileCredentials('test', str(creds), token, scopes=TEST_SCOPES, interactive=True)
+ provider.refresh()
- assert not token.exists()
+ mock_flow.run_local_server.assert_called_once_with(port=0)
+ assert provider.valid
+ assert token.read_text() == '{"token": "fresh"}'
assert token.with_name('token.json.invalid').exists()
@patch('korgalore.google_creds.InstalledAppFlow')
def test_runs_oauth_flow_and_saves_token_when_no_token(self, mock_flow_class: MagicMock, tmp_path: Path) -> None:
- """Runs the OAuth flow interactively, saves the returned credentials, and marks auth done."""
+ """Runs the OAuth flow interactively and saves the returned credentials."""
creds = tmp_path / 'creds.json'
creds.write_text('{}')
token = tmp_path / 'token.json'
@@ -165,18 +205,21 @@ class TestOAuthFileCredentials:
mock_flow_class.from_client_secrets_file.return_value = mock_flow
provider = OAuthFileCredentials('test', str(creds), token, scopes=TEST_SCOPES)
+ provider.refresh()
mock_flow_class.from_client_secrets_file.assert_called_once_with(str(creds), TEST_SCOPES)
mock_flow.run_local_server.assert_called_once_with(port=0)
assert provider.valid
- assert not provider.needs_auth
assert token.read_text() == '{"token": "fresh"}'
assert (token.stat().st_mode & 0o777) == 0o600
def test_missing_credentials_file_raises(self, tmp_path: Path) -> None:
- """Missing credentials file raises ConfigurationError."""
+ """Missing credentials file raises ConfigurationError when refresh() runs."""
+ provider = OAuthFileCredentials(
+ 'test', str(tmp_path / 'creds.json'), tmp_path / 'token.json', scopes=TEST_SCOPES
+ )
with pytest.raises(ConfigurationError) as exc_info:
- OAuthFileCredentials('test', str(tmp_path / 'creds.json'), tmp_path / 'token.json', scopes=TEST_SCOPES)
+ provider.refresh()
assert 'not found' in str(exc_info.value)
assert 'creds.json' in str(exc_info.value)
@@ -190,19 +233,25 @@ class TestOAuthFileCredentials:
mock_credentials.from_authorized_user_file.return_value = MagicMock(valid=True)
with patch.dict('os.environ', {'HOME': str(tmp_path)}):
- OAuthFileCredentials('test', '~/creds.json', '$HOME/token.json', scopes=TEST_SCOPES)
+ provider = OAuthFileCredentials('test', '~/creds.json', '$HOME/token.json', scopes=TEST_SCOPES)
+ valid_before = provider.valid
+ assert not valid_before
+ provider.refresh()
+ assert provider.valid
mock_credentials.from_authorized_user_file.assert_called_once_with(str(token))
def test_corrupt_token_file_falls_back_gracefully(self, tmp_path: Path) -> None:
- """Corrupt or truncated token.json logs warning and leaves creds unloaded instead of crashing."""
+ """Corrupt or truncated token.json logs warning and raises AuthenticationError on refresh."""
token = tmp_path / 'token.json'
token.write_text('not valid json{')
creds = tmp_path / 'creds.json'
creds.write_text('{}')
provider = OAuthFileCredentials('test', str(creds), token, scopes=TEST_SCOPES, interactive=False)
- assert provider.needs_auth
+ assert not provider.valid
+ with pytest.raises(AuthenticationError, match='requires authentication'):
+ provider.refresh()
assert not provider.valid
@@ -224,6 +273,7 @@ class TestOAuthFileCredentialsRefresh:
provider = OAuthFileCredentials(
'test', str(tmp_path / 'creds.json'), token, scopes=TEST_SCOPES, interactive=False
)
+ provider._load_token_file()
return provider, mock_creds, token
def test_refresh_saves_new_token(self, loaded: Loaded) -> None:
@@ -242,7 +292,7 @@ class TestOAuthFileCredentialsRefresh:
provider, mock_creds, token = loaded
mock_creds.refresh.side_effect = RefreshError
- with pytest.raises(AuthenticationError, match='Failed to refresh'):
+ with pytest.raises(AuthenticationError, match='invalid'):
provider.refresh(MagicMock())
assert provider.needs_auth
diff --git a/tests/test_gui.py b/tests/test_gui.py
index f47fc09..55f8472 100644
--- a/tests/test_gui.py
+++ b/tests/test_gui.py
@@ -19,6 +19,12 @@ from unittest.mock import MagicMock, patch
import pytest
import liblore
+from korgalore import AuthenticationError
+from korgalore.gmail_target import SCOPES, GmailTarget
+from korgalore.google_creds import CommandCredentials, OAuthFileCredentials
+from korgalore.gui import target_can_reauthenticate
+from korgalore.imap_target import ImapTarget
+from korgalore.jmap_target import JmapTarget
from tests.gui_helpers import make_app
if TYPE_CHECKING:
@@ -373,3 +379,50 @@ class TestQuitStillShutsDown:
node.shutdown.assert_called_once_with()
node.cancel_active.assert_not_called()
+
+
+class TestTargetCanReauthenticate:
+ """Tests for GUI interactive reauthentication capability checks."""
+
+ def test_gmail_oauth_file_vs_token_command(self, tmp_path: Path) -> None:
+ creds = tmp_path / 'creds.json'
+ creds.write_text('{}')
+ oauth_target = GmailTarget(
+ 'personal', OAuthFileCredentials('personal', str(creds), tmp_path / 'token.json', SCOPES)
+ )
+ cmd_target = GmailTarget('work', CommandCredentials('work', ['echo', 'tok']))
+
+ assert target_can_reauthenticate(oauth_target) is True
+ assert target_can_reauthenticate(cmd_target) is False
+
+ def test_imap_and_jmap_targets(self) -> None:
+ imap_oauth = ImapTarget('io', 'imap.example.com', 'u', auth_type='oauth2', client_id='cid', interactive=False)
+ imap_pw = ImapTarget('ip', 'imap.example.com', 'u', auth_type='password', password='pw')
+ jmap = JmapTarget('jmap', 'https://api.example.com/jmap/session', 'u', token='tok')
+
+ assert target_can_reauthenticate(imap_oauth) is True
+ assert target_can_reauthenticate(imap_pw) is False
+ assert target_can_reauthenticate(jmap) is False
+ assert target_can_reauthenticate(None) is False
+
+ def test_run_sync_auth_error_checks_can_reauthenticate(self) -> None:
+ cmd_target = GmailTarget('work', CommandCredentials('work', ['echo', 'tok']))
+ app = make_app(sync_interval=300)
+ statuses: list[str] = []
+
+ def _fail(*args: Any, **kwargs: Any) -> None:
+ raise AuthenticationError('bad token', target_id='work', target_type='gmail')
+
+ with (
+ patch.object(app, '_check_reload_config'),
+ patch('korgalore.gui.refresh_subfolder_templates'),
+ patch.object(app, 'update_status', side_effect=lambda text, icon=None: statuses.append(text)),
+ patch('korgalore.gui.perform_pull', side_effect=_fail),
+ patch('korgalore.gui.get_target', return_value=cmd_target),
+ patch('korgalore.gui.GLib') as mock_glib,
+ ):
+ app.run_sync()
+
+ assert app.auth_needed_target is None
+ assert statuses == ['Syncing...', 'Auth failed: work']
+ assert mock_glib.idle_add.call_count == 2 # only item_sync disable/re-enable
diff --git a/tests/test_imap_target.py b/tests/test_imap_target.py
index d280c1b..cfdab05 100644
--- a/tests/test_imap_target.py
+++ b/tests/test_imap_target.py
@@ -479,3 +479,22 @@ class TestImapTargetDeduplication:
def test_check_message_exists_no_connection(self, imap: tuple[ImapTarget, MagicMock]) -> None:
target, _ = imap
assert target._check_message_exists('<test@example.com>', 'INBOX') is False
+
+
+class TestImapTargetCapabilities:
+ """Tests for target capability properties."""
+
+ def test_can_reauthenticate_by_auth_type(self) -> None:
+ """OAuth2 targets support interactive reauthentication; password targets do not."""
+ oauth_target = ImapTarget(
+ identifier='io',
+ server=SERVER,
+ username=USER,
+ auth_type='oauth2',
+ client_id='cid',
+ interactive=False,
+ )
+ pw_target = make_target()
+
+ assert oauth_target.can_reauthenticate is True
+ assert pw_target.can_reauthenticate is False
diff --git a/tests/test_jmap_target.py b/tests/test_jmap_target.py
index 2756601..520cf94 100644
--- a/tests/test_jmap_target.py
+++ b/tests/test_jmap_target.py
@@ -289,6 +289,10 @@ class TestJmapTargetMailboxes:
def test_translate_folders(self, jmap_mailboxes: JmapTarget, folders: list[str]) -> None:
assert jmap_mailboxes.translate_folders(folders) == ['mb-1', 'mb-2', 'mb-3']
+ def test_translate_labels_delegates_to_translate_folders(self, jmap_mailboxes: JmapTarget) -> None:
+ """translate_labels() delegates to translate_folders() for uniform target interface."""
+ assert jmap_mailboxes.translate_labels(['INBOX', 'Sent']) == ['mb-1', 'mb-2']
+
def test_translate_unknown_folder_raises(self, jmap_mailboxes: JmapTarget) -> None:
with pytest.raises(ConfigurationError) as exc_info:
jmap_mailboxes.translate_folders(['nonexistent'])
diff --git a/tests/test_pi_feed.py b/tests/test_pi_feed.py
index fea7efb..111c924 100644
--- a/tests/test_pi_feed.py
+++ b/tests/test_pi_feed.py
@@ -283,6 +283,42 @@ class TestGetFailedCommits:
assert mock_feed.get_failed_commits_for_delivery('test-delivery') == [(0, 'abc123'), (1, 'def456')]
+class TestHasPendingCommits:
+ """Tests for pure-JSON has_pending_commits method."""
+
+ def test_returns_false_without_state_files_or_git(self, mock_feed: PIFeed, temp_feed_dir: Path) -> None:
+ """Missing state files return False with no file creation or git subprocesses."""
+ with patch('korgalore.pi_feed.run_git_command') as mock_git:
+ assert not mock_feed.has_pending_commits('test-delivery')
+ mock_git.assert_not_called()
+ assert not (temp_feed_dir / 'korgalore.test-delivery.info').exists()
+ assert not (temp_feed_dir / 'korgalore.feed').exists()
+
+ def test_same_commit_returns_false_even_with_failed_file(self, mock_feed: PIFeed, temp_feed_dir: Path) -> None:
+ """Matching pointer and feed commit returns False; failed retries run separately."""
+ (temp_feed_dir / 'korgalore.feed').write_text(json.dumps({'epochs': {'0': {'latest_commit': 'aaa111'}}}))
+ (temp_feed_dir / 'korgalore.test-delivery.info').write_text(json.dumps({'epochs': {'0': {'last': 'aaa111'}}}))
+ write_state(
+ temp_feed_dir / 'korgalore.test-delivery.failed',
+ [(0, 'abc123', OLD, 1)],
+ )
+ assert not mock_feed.has_pending_commits('test-delivery')
+
+ def test_lagging_commit_returns_true(self, mock_feed: PIFeed, temp_feed_dir: Path) -> None:
+ """Returns True when feed latest_commit differs from delivery last commit."""
+ (temp_feed_dir / 'korgalore.feed').write_text(json.dumps({'epochs': {'0': {'latest_commit': 'bbb222'}}}))
+ (temp_feed_dir / 'korgalore.test-delivery.info').write_text(json.dumps({'epochs': {'0': {'last': 'aaa111'}}}))
+ assert mock_feed.has_pending_commits('test-delivery')
+
+ def test_newer_feed_epoch_returns_true(self, mock_feed: PIFeed, temp_feed_dir: Path) -> None:
+ """Returns True when feed highest epoch exceeds delivery highest epoch."""
+ (temp_feed_dir / 'korgalore.feed').write_text(
+ json.dumps({'epochs': {'0': {'latest_commit': 'aaa111'}, '1': {'latest_commit': 'ccc333'}}})
+ )
+ (temp_feed_dir / 'korgalore.test-delivery.info').write_text(json.dumps({'epochs': {'0': {'last': 'aaa111'}}}))
+ assert mock_feed.has_pending_commits('test-delivery')
+
+
class TestCleanupFailedState:
"""Tests for cleanup_failed_state function."""
diff --git a/tests/test_pull.py b/tests/test_pull.py
index 4a94d40..ef11859 100644
--- a/tests/test_pull.py
+++ b/tests/test_pull.py
@@ -9,6 +9,8 @@ failures don't count.
"""
from collections.abc import Iterator
+from datetime import UTC, datetime
+from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, patch
@@ -16,7 +18,7 @@ import click
import pytest
from click.testing import CliRunner
-from korgalore import GitError, PublicInboxError, RemoteError, StateError
+from korgalore import AuthenticationError, ConfigurationError, GitError, PublicInboxError, RemoteError, StateError
from korgalore.cli import (
SKIPPED_NOOP_COMMIT,
deliver_commit,
@@ -26,8 +28,10 @@ from korgalore.cli import (
update_all_feeds,
)
from korgalore.lore_feed import LoreFeed
+from korgalore.maildir_target import MaildirTarget
from korgalore.pi_feed import PIFeed
-from tests.digest_helpers import make_ctx
+from tests.conftest import make_pi_feed
+from tests.digest_helpers import DAILY, InboxRepo, make_ctx
def _make_feed(feed_key: str, status: int = PIFeed.STATUS_UPDATED, error: Exception | None = None) -> MagicMock:
@@ -39,6 +43,7 @@ def _make_feed(feed_key: str, status: int = PIFeed.STATUS_UPDATED, error: Except
feed.update_feed.side_effect = error
else:
feed.update_feed.return_value = status
+ feed.has_pending_commits.return_value = False
feed.get_latest_commits_for_delivery.return_value = [(0, f'{feed_key}-commit')]
feed.STATUS_UPDATED = PIFeed.STATUS_UPDATED
feed.STATUS_INITIALIZED = PIFeed.STATUS_INITIALIZED
@@ -173,6 +178,238 @@ class TestPerformPull:
assert ctx.obj['failed_feeds'] == []
+ def test_target_connect_error_isolated(self, pull_env: MagicMock) -> None:
+ """Target connect failure isolates to that target; others still succeed."""
+ feed1 = _make_feed('feed1')
+ feed2 = _make_feed('feed2')
+ t1 = MagicMock()
+ t1.identifier = 'target1'
+ t2 = MagicMock()
+ t2.identifier = 'target2'
+ t2.connect.side_effect = RemoteError('network down')
+
+ obj = {
+ 'config': {'deliveries': {'d1': {}, 'd2': {}}},
+ 'feeds': {'feed1': feed1, 'feed2': feed2},
+ 'deliveries': {
+ 'd1': (feed1, t1, [], None),
+ 'd2': (feed2, t2, [], None),
+ },
+ 'targets': {'target1': t1, 'target2': t2},
+ 'bozofilter': set(),
+ 'hide_bar': True,
+ }
+ ctx = make_ctx(obj)
+ changes, _ = perform_pull(ctx, no_update=False, force=False, delivery_name=None)
+ assert changes == {'d1': 1}
+ assert 'd2' not in changes
+ feed2.mark_failed_delivery.assert_not_called()
+
+ def test_target_auth_error_raised_after_unlock(self) -> None:
+ """Fatal AuthenticationError isolates target, unlocks feeds, then raises."""
+ feed1 = _make_feed('feed1')
+ feed2 = _make_feed('feed2')
+ t1 = MagicMock()
+ t1.identifier = 'target1'
+ t2 = MagicMock()
+ t2.identifier = 'target2'
+ t2.connect.side_effect = AuthenticationError('bad token', target_id='target2', target_type='gmail')
+
+ obj = {
+ 'config': {'deliveries': {'d1': {}, 'd2': {}}},
+ 'feeds': {'feed1': feed1, 'feed2': feed2},
+ 'deliveries': {
+ 'd1': (feed1, t1, [], None),
+ 'd2': (feed2, t2, [], None),
+ },
+ 'targets': {'target1': t1, 'target2': t2},
+ 'bozofilter': set(),
+ 'hide_bar': True,
+ }
+ ctx = make_ctx(obj)
+ mock_deliver = MagicMock(side_effect=lambda dname, *args, **kwargs: f'<{dname}@example.org>')
+ with (
+ patch('korgalore.cli.map_deliveries'),
+ patch('korgalore.cli.map_tracked_threads'),
+ patch('korgalore.cli.lock_all_feeds'),
+ patch('korgalore.cli.unlock_all_feeds') as mock_unlock,
+ patch('korgalore.cli.retry_all_failed_deliveries'),
+ patch('korgalore.cli.update_tracked_thread_activity'),
+ patch('korgalore.cli.close_requests_session'),
+ patch('korgalore.cli.get_tracking_manifest'),
+ patch('korgalore.cli.deliver_commit', mock_deliver),
+ ):
+ with pytest.raises(AuthenticationError):
+ perform_pull(ctx, no_update=False, force=False, delivery_name=None)
+
+ mock_unlock.assert_called_once_with(ctx)
+ feed2.mark_failed_delivery.assert_not_called()
+
+ def test_target_auth_error_preferred_over_config_error(self) -> None:
+ """AuthenticationError wins over ConfigurationError across failed targets."""
+ feed1 = _make_feed('feed1')
+ feed2 = _make_feed('feed2')
+ t1 = MagicMock()
+ t1.identifier = 'target1'
+ t1.connect.side_effect = ConfigurationError('bad config')
+ t2 = MagicMock()
+ t2.identifier = 'target2'
+ t2.connect.side_effect = AuthenticationError('bad token', target_id='target2', target_type='gmail')
+
+ obj = {
+ 'config': {'deliveries': {'d1': {}, 'd2': {}}},
+ 'feeds': {'feed1': feed1, 'feed2': feed2},
+ 'deliveries': {
+ 'd1': (feed1, t1, [], None),
+ 'd2': (feed2, t2, [], None),
+ },
+ 'targets': {'target1': t1, 'target2': t2},
+ 'bozofilter': set(),
+ 'hide_bar': True,
+ }
+ ctx = make_ctx(obj)
+ with (
+ patch('korgalore.cli.map_deliveries'),
+ patch('korgalore.cli.map_tracked_threads'),
+ patch('korgalore.cli.lock_all_feeds'),
+ patch('korgalore.cli.unlock_all_feeds'),
+ patch('korgalore.cli.retry_all_failed_deliveries'),
+ patch('korgalore.cli.update_tracked_thread_activity'),
+ patch('korgalore.cli.close_requests_session'),
+ patch('korgalore.cli.get_tracking_manifest'),
+ ):
+ with pytest.raises(AuthenticationError):
+ perform_pull(ctx, no_update=False, force=False, delivery_name=None)
+
+ def test_two_pull_pending_commits_recovered_without_feed_update(self, tmp_path: Path) -> None:
+ """Pull 2 delivers pending commits stranded when Pull 1 connect failed."""
+ feed_dir = tmp_path / 'feed'
+ repo = InboxRepo(feed_dir)
+ when = datetime(2026, 10, 1, 8, 0, tzinfo=UTC)
+ c1 = repo.add(b'From: a@example.com\nSubject: First\nMessage-ID: <1@example.com>\n\nFirst\n', when)
+ c2 = repo.add(b'From: b@example.com\nSubject: Second\nMessage-ID: <2@example.com>\n\nSecond\n', when)
+
+ feed = make_pi_feed(feed_dir, key='test-feed')
+ feed.save_delivery_info('d1', epoch=0, latest_commit=c1)
+ feed.save_feed_state(epoch=0, latest_commit=c2)
+
+ maildir = MaildirTarget('local', str(tmp_path / 'maildir'))
+
+ def make_pull_obj() -> dict[str, Any]:
+ return {
+ 'config': {'deliveries': {'d1': {}}},
+ 'feeds': {'test-feed': feed},
+ 'deliveries': {'d1': (feed, maildir, [], None)},
+ 'targets': {'local': maildir},
+ 'bozofilter': set(),
+ 'hide_bar': True,
+ }
+
+ with (
+ patch('korgalore.cli.map_deliveries'),
+ patch('korgalore.cli.map_tracked_threads'),
+ patch('korgalore.cli.update_tracked_thread_activity'),
+ patch('korgalore.cli.close_requests_session'),
+ patch.object(feed, 'update_feed', side_effect=[PIFeed.STATUS_UPDATED, PIFeed.STATUS_NOCHANGE], create=True),
+ ):
+ # Pull 1: feed reports updated, target connect fails before delivery
+ with patch.object(maildir, 'connect', side_effect=RemoteError('temporary failure')):
+ changes1, _ = perform_pull(make_ctx(make_pull_obj()), no_update=False, force=False, delivery_name=None)
+ assert changes1 == {}
+ assert feed.has_pending_commits('d1')
+
+ # Pull 2: feed has no new upstream commits, yet pending c2 is delivered
+ changes2, msgids2 = perform_pull(
+ make_ctx(make_pull_obj()), no_update=False, force=False, delivery_name=None
+ )
+ assert changes2 == {'d1': 1}
+ assert msgids2 == {'<2@example.com>'}
+ assert not feed.has_pending_commits('d1')
+
+ def test_digest_config_error_isolated_then_aborts_pull(self) -> None:
+ """A failing digest isolates its target so healthy digests run, then pull exits 1."""
+ feed1 = _make_feed('feed1')
+ feed2 = _make_feed('feed2')
+ t1 = MagicMock()
+ t1.identifier = 'target1'
+ t2 = MagicMock()
+ t2.identifier = 'target2'
+ obj = {
+ 'config': {'deliveries': {'dig1': {}, 'dig2': {}}},
+ 'feeds': {'feed1': feed1, 'feed2': feed2},
+ 'deliveries': {
+ 'dig1': (feed1, t1, [], None),
+ 'dig2': (feed2, t2, [], None),
+ },
+ 'digest_schedules': {'dig1': DAILY, 'dig2': DAILY},
+ 'targets': {'target1': t1, 'target2': t2},
+ 'bozofilter': set(),
+ 'hide_bar': True,
+ }
+ sent_digests: list[str] = []
+
+ def fake_send_digest(dname: str, *args: Any, **kwargs: Any) -> list[dict[str, str]]:
+ if dname == 'dig1':
+ raise ConfigurationError('unknown label')
+ sent_digests.append(dname)
+ return [{'Subject': 'ok', 'Message-ID': '<d2@x>'}]
+
+ with (
+ patch('korgalore.cli.map_deliveries'),
+ patch('korgalore.cli.map_tracked_threads'),
+ patch('korgalore.cli.retry_all_failed_deliveries'),
+ patch('korgalore.cli.update_tracked_thread_activity'),
+ patch('korgalore.cli.close_requests_session'),
+ patch('korgalore.cli.get_tracking_manifest'),
+ patch('korgalore.cli.send_digest', side_effect=fake_send_digest),
+ ):
+ res = CliRunner().invoke(pull, ['--no-update'], obj=obj)
+
+ assert res.exit_code == 1
+ assert sent_digests == ['dig2']
+ feed1.feed_unlock.assert_called_once()
+ feed2.feed_unlock.assert_called_once()
+
+ def test_retry_all_failed_deliveries_without_failed_targets_skips_failed_target(self) -> None:
+ """retry_all_failed_deliveries isolates target errors even without passed failed_targets."""
+ from korgalore.cli import retry_all_failed_deliveries
+
+ feed1 = _make_feed('feed1')
+ feed1.get_failed_commits_for_delivery.return_value = [(0, 'c1'), (0, 'c2')]
+
+ feed2 = _make_feed('feed2')
+ feed2.get_failed_commits_for_delivery.return_value = [(0, 'c3')]
+
+ t1 = MagicMock()
+ t1.identifier = 'target1'
+ t2 = MagicMock()
+ t2.identifier = 'target2'
+
+ obj = {
+ 'deliveries': {
+ 'd1': (feed1, t1, [], None),
+ 'd2': (feed2, t2, [], None),
+ },
+ 'targets': {'target1': t1, 'target2': t2},
+ 'bozofilter': set(),
+ 'hide_bar': True,
+ }
+ ctx = make_ctx(obj)
+
+ delivered: list[str] = []
+
+ def fake_deliver_commit(dname: str, target: Any, *args: Any, **kwargs: Any) -> str:
+ if target.identifier == 'target1':
+ raise AuthenticationError('auth failed', target_id='target1')
+ delivered.append(dname)
+ return f'<{dname}@example.org>'
+
+ with patch('korgalore.cli.deliver_commit', side_effect=fake_deliver_commit):
+ retry_all_failed_deliveries(ctx)
+
+ # target1 failed on c1, so c2 was skipped; target2's c3 was successfully delivered
+ assert delivered == ['d2']
+
class TestPullExitStatus:
"""The exit status of the pull command itself."""
diff --git a/tests/test_tracked_thread_delivery.py b/tests/test_tracked_thread_delivery.py
index da6b460..23308c5 100644
--- a/tests/test_tracked_thread_delivery.py
+++ b/tests/test_tracked_thread_delivery.py
@@ -8,9 +8,14 @@ can unpack them without a ValueError.
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
-from unittest.mock import MagicMock, patch
+from unittest.mock import MagicMock, call, patch
-from korgalore.cli import map_tracked_threads
+import pytest
+from click.testing import CliRunner
+
+from korgalore import AuthenticationError, ConfigurationError
+from korgalore.cli import map_tracked_threads, track_add
+from korgalore.gmail_target import GmailTarget
from korgalore.tracking import TrackedThread, TrackStatus
from tests.digest_helpers import make_ctx
@@ -87,3 +92,107 @@ class TestTrackedThreadDeliveryTuple:
_, _, labels, _ = deliveries[tracked.track_id]
assert labels == ['patch-review', 'urgent']
+
+
+class TestTrackAddPreFlightAndFailureHandling:
+ """Tests for pre-flight validation and mid-loop failure handling in track_add."""
+
+ @staticmethod
+ def make_ctx_obj(tmp_path: Path) -> dict[str, Any]:
+ return {
+ 'config': {'targets': {'personal': {'type': 'gmail'}}},
+ 'targets': {},
+ 'feeds': {},
+ 'deliveries': {},
+ 'bozofilter': set(),
+ 'data_dir': tmp_path / 'data',
+ 'hide_bar': True,
+ }
+
+ @pytest.mark.parametrize(
+ ('connect_err', 'translate_err'),
+ [
+ (AuthenticationError('bad token', target_id='personal', target_type='gmail'), None),
+ (None, ConfigurationError('Label missing not found')),
+ ],
+ ids=['connect-auth-error', 'unknown-label-error'],
+ )
+ def test_preflight_failure_avoids_lei_and_manifest_pollution(
+ self,
+ tmp_path: Path,
+ connect_err: Exception | None,
+ translate_err: Exception | None,
+ ) -> None:
+ """Target connection or label failure aborts before lei search or manifest creation."""
+ target = MagicMock(spec=GmailTarget)
+ target.DEFAULT_LABELS = ['INBOX']
+ if connect_err is not None:
+ target.connect.side_effect = connect_err
+ if translate_err is not None:
+ target.translate_labels.side_effect = translate_err
+
+ manifest = MagicMock()
+ manifest.get_thread_by_msgid.return_value = None
+
+ obj = self.make_ctx_obj(tmp_path)
+ obj['targets'] = {'personal': target}
+
+ with (
+ patch('korgalore.cli.get_tracking_manifest', return_value=manifest),
+ patch('korgalore.cli.create_lei_thread_search') as mock_create,
+ patch('korgalore.cli.close_requests_session') as mock_close,
+ ):
+ res = CliRunner().invoke(
+ track_add,
+ ['--target', 'personal', '--labels', 'NonExistent', 'test@example.com'],
+ obj=obj,
+ )
+
+ assert res.exit_code == 1
+ mock_create.assert_not_called()
+ manifest.add_thread.assert_not_called()
+ mock_close.assert_called_once_with()
+ assert obj['targets'] == {}
+
+ def test_mid_loop_auth_error_records_remaining_commits_as_failed(self, tmp_path: Path) -> None:
+ """Auth failure mid-delivery marks unattempted commits failed and initializes feed state."""
+ target = MagicMock(spec=GmailTarget)
+ target.DEFAULT_LABELS = ['INBOX']
+ manifest = MagicMock()
+ manifest.get_thread_by_msgid.return_value = None
+ manifest.add_thread.return_value = _make_tracked_thread(tmp_path)
+
+ lei_feed = MagicMock()
+ lei_feed.get_all_commits_in_epoch.return_value = ['c1', 'c2', 'c3']
+
+ node = MagicMock()
+ node.get_message_by_msgid.return_value = b'Subject: Test thread\n\nBody\n'
+
+ obj = self.make_ctx_obj(tmp_path)
+ obj['targets'] = {'personal': target}
+
+ with (
+ patch('korgalore.cli.get_tracking_manifest', return_value=manifest),
+ patch('korgalore.cli.create_lei_thread_search', return_value=(0, b'')),
+ patch('korgalore.cli.update_lei_search', return_value=(0, b'')),
+ patch('korgalore.cli.get_lore_node', return_value=node),
+ patch('korgalore.cli.write_archive_description'),
+ patch('korgalore.cli.LeiFeed', return_value=lei_feed),
+ patch('korgalore.cli.close_requests_session') as mock_close,
+ patch(
+ 'korgalore.cli.deliver_commit',
+ side_effect=['<m1@example.com>', AuthenticationError('expired', target_id='personal')],
+ ),
+ ):
+ res = CliRunner().invoke(track_add, ['--target', 'personal', 'test@example.com'], obj=obj)
+
+ assert res.exit_code == 1
+ assert lei_feed.mark_failed_delivery.call_args_list == [
+ call('track-abc123', 0, 'c2'),
+ call('track-abc123', 0, 'c3'),
+ ]
+ lei_feed.save_delivery_info.assert_called_once_with('track-abc123', 0, latest_commit='c3')
+ lei_feed.init_feed.assert_called_once_with()
+ manifest.update_activity.assert_called_once_with('track-abc123', 1)
+ mock_close.assert_called_once_with()
+ assert obj['targets'] == {}
--
2.56.1.987.g2ec0ab4260-goog
^ permalink raw reply related [flat|nested] 5+ messages in thread* [PATCH kgl 3/4] Add initial_labels, intra-pull dedup cache, and Gmail scope upgrades
2026-12-05 6:56 [PATCH kgl 0/4] Add conditional initial-arrival delivery rules Dmitry Torokhov
2026-12-05 6:56 ` [PATCH kgl 1/4] Disable interactive OAuth flows when stdin is not a terminal Dmitry Torokhov
2026-12-05 6:56 ` [PATCH kgl 2/4] Defer Gmail OAuth loading until delivery and isolate target failures Dmitry Torokhov
@ 2026-12-05 6:56 ` Dmitry Torokhov
2026-12-05 6:56 ` [PATCH kgl 4/4] Add conditional initial-arrival delivery rules Dmitry Torokhov
3 siblings, 0 replies; 5+ messages in thread
From: Dmitry Torokhov @ 2026-12-05 6:56 UTC (permalink / raw)
To: Kernel.org Tools; +Cc: Konstantin Ryabitsev
Cross-posted messages imported multiple times across feeds and
deliveries reapply all configured labels on every import. For stateful
targets like Gmail and JMAP, this resurrects read or archived messages
by reapplying triage labels such as INBOX or UNREAD, while duplicate
uploads also waste network bandwidth and API quota.
Support initial labels in target import interfaces, applying them only
when a message is newly imported into the account instead of on
duplicate arrivals. Introduce an in-memory per-pull deduplication cache
for Gmail and JMAP targets that collapses duplicate uploads within a
single pull run, updating missing labels on existing messages instead of
re-uploading the entire message body (omitting UNREAD when modifying
pre-existing Gmail messages). Gmail targets without modify scope still
skip identical-label duplicates in the same pull, falling back to import
when a duplicate adds new labels.
Upgrade Gmail OAuth scopes to request modify permissions when labels
need to be updated on existing messages, handling scope verification
lazily during authentication and connection.
Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
---
src/korgalore/__init__.py | 4 +
src/korgalore/cli.py | 24 +++-
src/korgalore/dummy_target.py | 2 +
src/korgalore/gmail_target.py | 305 +++++++++++++++++++++++++++++++++++++---
src/korgalore/google_creds.py | 134 ++++++++++++++----
src/korgalore/imap_target.py | 2 +
src/korgalore/jmap_target.py | 177 ++++++++++++++++++++++-
src/korgalore/maildir_target.py | 2 +
src/korgalore/pipe_target.py | 2 +
tests/test_cli_misc.py | 95 ++++++++++++-
tests/test_gmail_target.py | 304 ++++++++++++++++++++++++++++++++++++++-
tests/test_google_creds.py | 217 +++++++++++++++++++++++++++-
tests/test_jmap_target.py | 158 +++++++++++++++++++++
tests/test_pull.py | 30 ++++
14 files changed, 1397 insertions(+), 59 deletions(-)
diff --git a/src/korgalore/__init__.py b/src/korgalore/__init__.py
index 5af2b0b..6805615 100644
--- a/src/korgalore/__init__.py
+++ b/src/korgalore/__init__.py
@@ -130,6 +130,10 @@ class AuthenticationError(KorgaloreError):
self.target_type = target_type
+class InsufficientScopesError(AuthenticationError):
+ """Raised when target credentials lack required OAuth scopes."""
+
+
def _init_git_user_agent() -> None:
"""Check git is available and set GIT_HTTP_USER_AGENT environment variable.
diff --git a/src/korgalore/cli.py b/src/korgalore/cli.py
index 1e4e3f2..1b048b5 100644
--- a/src/korgalore/cli.py
+++ b/src/korgalore/cli.py
@@ -339,20 +339,37 @@ def get_gmail_target(
identifier: str,
details: Mapping[str, Any],
interactive: bool = True,
+ requires_modify: bool = False,
) -> GmailTarget:
- """Create a Gmail target service instance."""
+ """Create a Gmail target service instance.
+
+ Args:
+ identifier: Target name from ``korgalore.toml``.
+ details: Target configuration mapping.
+ interactive: Whether interactive OAuth browser flows are permitted.
+ requires_modify: Whether ``gmail.modify`` scope is required for
+ looking up and relabeling existing messages.
+
+ Returns:
+ Configured ``GmailTarget`` instance.
+
+ Raises:
+ click.Abort: If target configuration is invalid.
+ """
try:
creds = make_gmail_credentials(
identifier=identifier,
details=details,
interactive=interactive,
config_dir=get_xdg_config_dir(),
+ requires_modify=requires_modify,
)
gt = GmailTarget(
identifier=identifier,
creds=creds,
message_date=details.get('message_date', DEFAULT_MESSAGE_DATE),
never_mark_spam=details.get('never_mark_spam', False),
+ requires_modify=requires_modify,
)
except ConfigurationError as fe:
logger.critical('Error: %s', str(fe))
@@ -729,7 +746,10 @@ def deliver_commit(
if logger.isEnabledFor(logging.DEBUG):
subject = msg_get_subject(msg) or '(no subject)'
- logger.debug(' -> %s', subject)
+ if labels:
+ logger.debug(' -> %s (labels: %s)', subject, ', '.join(labels))
+ else:
+ logger.debug(' -> %s', subject)
target.import_message(
raw_message,
labels=labels,
diff --git a/src/korgalore/dummy_target.py b/src/korgalore/dummy_target.py
index ca77e33..16b903a 100644
--- a/src/korgalore/dummy_target.py
+++ b/src/korgalore/dummy_target.py
@@ -35,6 +35,7 @@ class DummyTarget:
feed_name: str | None = None,
delivery_name: str | None = None,
subfolder: str | None = None,
+ initial_labels: list[str] | None = None,
) -> Any:
"""Discard the message.
@@ -44,6 +45,7 @@ class DummyTarget:
feed_name: Ignored.
delivery_name: Ignored.
subfolder: Ignored (no folder concept).
+ initial_labels: Ignored.
Returns:
None
diff --git a/src/korgalore/gmail_target.py b/src/korgalore/gmail_target.py
index 5a08f40..24d68fb 100644
--- a/src/korgalore/gmail_target.py
+++ b/src/korgalore/gmail_target.py
@@ -1,15 +1,20 @@
import base64
import logging
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from pathlib import Path
-from typing import Any
+from typing import Any, NoReturn
from google.auth.credentials import Credentials as BaseCredentials
from google.auth.transport.requests import Request
from googleapiclient.discovery import Resource, build # type: ignore[import-untyped]
from googleapiclient.errors import HttpError # type: ignore[import-untyped]
-from korgalore import AuthenticationError, ConfigurationError, RemoteError
+from korgalore import (
+ AuthenticationError,
+ ConfigurationError,
+ InsufficientScopesError,
+ RemoteError,
+)
from korgalore.google_creds import CommandCredentials, OAuthFileCredentials, parse_token_command
from korgalore.message import DEFAULT_MESSAGE_DATE, RawMessage, check_message_date, is_plausible_date
@@ -23,6 +28,52 @@ SCOPES = [
'https://www.googleapis.com/auth/gmail.insert',
]
+# Required when initial_labels or delivery rules are configured so we can look
+# up existing messages across the mailbox and add literal labels without re-inserting.
+MODIFY_SCOPES = [
+ 'https://www.googleapis.com/auth/gmail.labels',
+ 'https://www.googleapis.com/auth/gmail.modify',
+]
+
+
+def has_gmail_scopes(granted_scopes: Any, required_scopes: Sequence[str]) -> bool:
+ """Check if granted Gmail OAuth scopes satisfy the required scopes.
+
+ Args:
+ granted_scopes: Scope collection recorded on credentials, or a
+ non-collection value when scope metadata is unavailable.
+ required_scopes: Gmail OAuth scope URIs required by the target.
+
+ Returns:
+ True if all required scopes (or broader Gmail scope equivalents) are
+ covered, or if scope metadata is unavailable.
+ """
+ # Treat missing or non-collection scope metadata (such as tokens without
+ # explicit scope claims) as provisionally valid; API calls still enforce
+ # permissions via HTTP 403.
+ if not isinstance(granted_scopes, (list, tuple, set, frozenset)):
+ return True
+ granted = {s.rstrip('/') for s in granted_scopes if isinstance(s, str) and s}
+ if 'https://mail.google.com' in granted:
+ return True
+ modify_scope = 'https://www.googleapis.com/auth/gmail.modify'
+ insert_scope = 'https://www.googleapis.com/auth/gmail.insert'
+ labels_scope = 'https://www.googleapis.com/auth/gmail.labels'
+ readonly_scope = 'https://www.googleapis.com/auth/gmail.readonly'
+ metadata_scope = 'https://www.googleapis.com/auth/gmail.metadata'
+ for req in required_scopes:
+ norm_req = req.rstrip('/')
+ if norm_req in granted:
+ continue
+ # gmail.modify is a strict superset of gmail.insert, and modify/readonly/
+ # metadata all cover label reads needed for gmail.labels translation.
+ if norm_req == insert_scope and modify_scope in granted:
+ continue
+ if norm_req == labels_scope and granted & {modify_scope, readonly_scope, metadata_scope}:
+ continue
+ return False
+ return True
+
class GmailTarget:
"""Target class for delivering email messages to Gmail via the API."""
@@ -35,6 +86,7 @@ class GmailTarget:
creds: BaseCredentials,
message_date: str = DEFAULT_MESSAGE_DATE,
never_mark_spam: object = False,
+ requires_modify: bool = False,
) -> None:
"""Initialize a GmailTarget instance.
@@ -48,6 +100,9 @@ class GmailTarget:
never_mark_spam: True to stop Gmail from filing imported messages
under Spam. Typed as object because it comes straight from
the config file and is checked here.
+ requires_modify: Whether initial-arrival rules or ``initial_labels``
+ require ``gmail.modify`` scope to search and relabel
+ existing messages.
Raises:
ConfigurationError: If an option has the wrong value.
@@ -60,8 +115,11 @@ class GmailTarget:
if not isinstance(never_mark_spam, bool):
raise ConfigurationError(f"Gmail target '{identifier}': 'never_mark_spam' must be a boolean.")
self.never_mark_spam = never_mark_spam
+ self.requires_modify = requires_modify
self.service: Resource | None = None
self._label_map: dict[str, str] | None = None
+ # Per-pull session cache: clean_msgid -> (remote_id, applied_ids, created_in_pull)
+ self._imported_msgids: dict[str, tuple[str, set[str], bool]] = {}
@property
def needs_auth(self) -> bool:
@@ -75,6 +133,45 @@ class GmailTarget:
"""Return True if target credentials support interactive reauthentication."""
return isinstance(self.creds, OAuthFileCredentials)
+ def _handle_http_error(self, error: HttpError) -> NoReturn:
+ """Translate a Gmail API HttpError into a korgalore domain exception.
+
+ Args:
+ error: Google API HTTP error raised during a Gmail request.
+
+ Raises:
+ AuthenticationError: On HTTP 401 when credentials support interactive
+ re-authentication.
+ InsufficientScopesError: On HTTP 403 caused by missing OAuth scopes.
+ RemoteError: For all other Gmail API errors or non-reauthenticable 401s.
+ """
+ status = getattr(error.resp, 'status', None)
+ content = error.content.decode('utf-8', errors='replace') if hasattr(error, 'content') else str(error)
+ if status == 401:
+ if self.can_reauthenticate:
+ raise AuthenticationError(
+ f"Gmail authentication expired or invalid for target '{self.identifier}': {error}",
+ target_id=self.identifier,
+ target_type='gmail',
+ ) from error
+ raise RemoteError(f"Gmail authentication failed for target '{self.identifier}': {error}") from error
+ if status == 403:
+ if 'ACCESS_TOKEN_SCOPE_INSUFFICIENT' in content or 'insufficientPermissions' in content:
+ hint = 'https://www.googleapis.com/auth/gmail.modify' if self.requires_modify else 'required'
+ if self.can_reauthenticate:
+ action = f"Run 'kgl auth {self.identifier}' to re-authenticate."
+ else:
+ action = (
+ f"Update 'token_command' for target '{self.identifier}' to issue a token with {hint} scope."
+ )
+ raise InsufficientScopesError(
+ f"Gmail target '{self.identifier}' lacks {hint} OAuth scope. {action}",
+ target_id=self.identifier,
+ target_type='gmail',
+ ) from error
+ raise RemoteError(f'An error occurred: {error}') from error
+ raise RemoteError(f'An error occurred: {error}') from error
+
def connect(self) -> None:
"""Establish connection to the Gmail API service.
@@ -84,6 +181,8 @@ class GmailTarget:
ConfigurationError: If credentials file is missing or token_command
cannot be executed.
AuthenticationError: If OAuth token refresh or authentication fails.
+ InsufficientScopesError: If the loaded or refreshed token lacks
+ required OAuth scopes.
RemoteError: If token_command fails, times out, or returns an
invalid token.
"""
@@ -94,13 +193,26 @@ class GmailTarget:
self.creds.refresh(Request()) # type: ignore[no-untyped-call]
logger.debug('Connecting to Gmail service for %s', self.identifier)
- self.service = build('gmail', 'v1', credentials=self.creds, cache_discovery=False)
- try:
- self._label_map = {label['name']: label['id'] for label in self.list_labels()}
- except Exception:
- self.service = None
- self._label_map = None
- raise
+ for attempt in range(2):
+ self.service = build('gmail', 'v1', credentials=self.creds, cache_discovery=False)
+ try:
+ self._label_map = {label['name']: label['id'] for label in self.list_labels()}
+ if self.requires_modify:
+ # Probe messages.list so tokens lacking metadata/modify claims fail upfront.
+ self._find_existing_message('korgalore-scope-probe')
+ return
+ except InsufficientScopesError:
+ self.service = None
+ self._label_map = None
+ if attempt == 0 and isinstance(self.creds, OAuthFileCredentials) and self.creds.interactive:
+ logger.info("Target '%s' lacks required scopes; re-authenticating...", self.identifier)
+ self.reauthenticate()
+ continue
+ raise
+ except Exception:
+ self.service = None
+ self._label_map = None
+ raise
def _api(self) -> Any:
"""Return the connected Gmail API service, connecting first if needed.
@@ -124,7 +236,7 @@ class GmailTarget:
return labels
except HttpError as error:
- raise RemoteError(f'An error occurred: {error}') from error
+ self._handle_http_error(error)
def translate_labels(self, labels: list[str]) -> list[str]:
"""Translate label names to Gmail label IDs.
@@ -150,6 +262,45 @@ class GmailTarget:
translated.append(label_id)
return translated
+ def _label_names(self, label_ids: Sequence[str]) -> list[str]:
+ """Map label IDs back to human-readable label names using the loaded label map."""
+ if not label_ids:
+ return []
+ id_to_name = {lid: name for name, lid in self._label_map.items()} if self._label_map else {}
+ return [id_to_name.get(lid, lid) for lid in label_ids]
+
+ def _find_existing_message(self, message_id: str) -> str | None:
+ """Find an existing Gmail message matching an RFC 822 Message-ID.
+
+ Args:
+ message_id: Raw or angle-bracketed Message-ID header value.
+
+ Returns:
+ Gmail message ID if a matching message exists anywhere in the
+ account (including Spam and Trash), or None otherwise.
+
+ Raises:
+ AuthenticationError: If Gmail authentication is invalid.
+ InsufficientScopesError: If the token lacks ``gmail.modify`` scope.
+ RemoteError: If the Gmail search request fails.
+ """
+ clean_msgid = message_id.strip('<>').strip()
+ escaped = clean_msgid.replace('\\', '\\\\').replace('"', '\\"')
+ query = f'rfc822msgid:"{escaped}"'
+ try:
+ # Include Spam and Trash so previously trashed or archived messages
+ # are still found and never re-imported with initial labels.
+ results = (
+ self._api().users().messages().list(userId='me', q=query, maxResults=1, includeSpamTrash=True).execute()
+ )
+ messages = results.get('messages', [])
+ if messages:
+ msg_id = messages[0].get('id')
+ return str(msg_id) if msg_id is not None else None
+ return None
+ except HttpError as error:
+ self._handle_http_error(error)
+
def import_message(
self,
raw_message: bytes,
@@ -157,32 +308,135 @@ class GmailTarget:
feed_name: str | None = None,
delivery_name: str | None = None,
subfolder: str | None = None,
+ initial_labels: list[str] | None = None,
) -> Any:
"""Import a raw email message into Gmail.
Args:
raw_message: The raw email message as bytes.
- labels: List of label names to apply to the message.
+ labels: List of literal label names to apply to the message.
feed_name: Optional feed name for trace header.
delivery_name: Optional delivery name for trace header.
subfolder: Ignored for Gmail (use labels for folder assignment).
+ initial_labels: Optional label names applied only on initial arrival.
Returns:
- The Gmail API response object for the imported message.
+ The Gmail API response object for the imported or modified message.
Raises:
+ ConfigurationError: If any requested label does not exist in Gmail.
+ AuthenticationError: If Gmail authentication is invalid.
+ InsufficientScopesError: If the token lacks required OAuth scopes.
RemoteError: If the Gmail API call fails.
"""
+ literal_ids = list(dict.fromkeys(self.translate_labels(labels))) if labels else []
+ literal_id_set = set(literal_ids)
+ initial_ids = list(dict.fromkeys(self.translate_labels(initial_labels))) if initial_labels else []
+ effective_initial_ids = [lid for lid in initial_ids if lid not in literal_id_set]
+
+ msg = RawMessage(raw_message)
+ clean_msgid = msg.message_id.strip('<>').strip() or None if msg.message_id else None
+
try:
- msg = RawMessage(raw_message)
+ # Check intra-pull session dedup cache
+ if clean_msgid and clean_msgid in self._imported_msgids:
+ remote_id, applied_ids, created_in_pull = self._imported_msgids[clean_msgid]
+ if created_in_pull:
+ # Message was freshly inserted in this pull, so all literal and
+ # initial labels from later cross-posts still apply (including UNREAD).
+ target_ids = literal_ids + effective_initial_ids
+ else:
+ # Pre-existing message: omit UNREAD so already-read mail stays read.
+ target_ids = [lid for lid in literal_ids if lid != 'UNREAD']
+ missing_ids = [lid for lid in target_ids if lid not in applied_ids]
+ if not missing_ids:
+ logger.debug('Skipping duplicate Gmail import for %s in same pull', clean_msgid)
+ return {'id': remote_id, 'skipped': True}
+
+ if self.requires_modify:
+ missing_names = self._label_names(missing_ids)
+ logger.debug(
+ 'Adding Gmail labels %s to duplicate message %s (%s)',
+ missing_names,
+ clean_msgid,
+ remote_id,
+ )
+ try:
+ res = (
+ self._api()
+ .users()
+ .messages()
+ .modify(userId='me', id=remote_id, body={'addLabelIds': missing_ids})
+ .execute()
+ )
+ applied_ids.update(missing_ids)
+ return res
+ except HttpError as error:
+ if getattr(error.resp, 'status', None) == 404:
+ logger.debug(
+ 'Existing Gmail message %s vanished before modify; falling back to import',
+ remote_id,
+ )
+ self._imported_msgids.pop(clean_msgid, None)
+ else:
+ self._handle_http_error(error)
+ # If not requires_modify or modify hit 404, fall through to import
+
+ # Check pre-existing message in Gmail mailbox when initial_labels need protection
+ if effective_initial_ids and clean_msgid and self.requires_modify:
+ existing_id = self._find_existing_message(clean_msgid)
+ if existing_id is not None:
+ # Avoid re-marking pre-existing (possibly already read) messages as UNREAD.
+ modify_label_ids = [lid for lid in literal_ids if lid != 'UNREAD']
+ if not modify_label_ids:
+ logger.debug('Skipping Gmail import: message %s already exists as %s', clean_msgid, existing_id)
+ self._imported_msgids[clean_msgid] = (existing_id, set(), False)
+ return {'id': existing_id, 'skipped': True}
+ modify_names = self._label_names(modify_label_ids)
+ logger.debug(
+ 'Adding Gmail labels %s to existing message %s (%s)',
+ modify_names,
+ clean_msgid,
+ existing_id,
+ )
+ try:
+ res = (
+ self._api()
+ .users()
+ .messages()
+ .modify(
+ userId='me',
+ id=existing_id,
+ body={'addLabelIds': modify_label_ids},
+ )
+ .execute()
+ )
+ self._imported_msgids[clean_msgid] = (existing_id, set(modify_label_ids), False)
+ return res
+ except HttpError as error:
+ if getattr(error.resp, 'status', None) == 404:
+ logger.debug(
+ 'Existing Gmail message %s vanished before modify; falling back to import',
+ existing_id,
+ )
+ else:
+ self._handle_http_error(error)
+
+ # Upload the message
encoded_message = base64.urlsafe_b64encode(msg.as_bytes(feed_name, delivery_name)).decode()
message_body: dict[str, Any] = {'raw': encoded_message}
- if labels:
- label_ids = self.translate_labels(labels)
- message_body['labelIds'] = label_ids
+ combined_ids = literal_ids + effective_initial_ids
+ if combined_ids:
+ message_body['labelIds'] = combined_ids
+
+ combined_names = self._label_names(combined_ids)
+ logger.debug(
+ 'Importing message %s to Gmail with labels: %s',
+ clean_msgid or '(no-msgid)',
+ combined_names,
+ )
- # Upload the message
result = (
self._api()
.users()
@@ -195,11 +449,17 @@ class GmailTarget:
)
.execute()
)
+ remote_id = result.get('id')
+ if clean_msgid and remote_id:
+ existing_entry = self._imported_msgids.get(clean_msgid)
+ prior_applied = existing_entry[1] if existing_entry else set()
+ prior_created = existing_entry[2] if existing_entry else True
+ self._imported_msgids[clean_msgid] = (str(remote_id), prior_applied | set(combined_ids), prior_created)
return result
except HttpError as error:
- raise RemoteError(f'An error occurred: {error}') from error
+ self._handle_http_error(error)
def _internal_date_source(self, msg: RawMessage) -> str:
"""Choose how Gmail dates the message.
@@ -238,6 +498,7 @@ class GmailTarget:
self.creds.reauthenticate()
self.service = None
self._label_map = None
+ self._imported_msgids.clear()
def make_gmail_credentials(
@@ -245,6 +506,7 @@ def make_gmail_credentials(
details: Mapping[str, Any],
config_dir: Path,
interactive: bool = True,
+ requires_modify: bool = False,
) -> BaseCredentials:
"""Create credentials for a Gmail target from configuration.
@@ -253,6 +515,8 @@ def make_gmail_credentials(
details: Target configuration mapping from ``korgalore.toml``.
config_dir: Configuration directory that holds the default token file.
interactive: Whether interactive OAuth browser flows are permitted.
+ requires_modify: Whether OAuth file credentials must include
+ ``gmail.modify`` scope.
Returns:
Configured credentials instance compatible with ``GmailTarget``.
@@ -290,7 +554,8 @@ def make_gmail_credentials(
identifier=identifier,
credentials_file=creds_raw,
token_file=token_file,
- scopes=SCOPES,
+ scopes=MODIFY_SCOPES if requires_modify else SCOPES,
interactive=interactive,
target_type='gmail',
+ scope_checker=has_gmail_scopes,
)
diff --git a/src/korgalore/google_creds.py b/src/korgalore/google_creds.py
index eb07c1d..c8cc527 100644
--- a/src/korgalore/google_creds.py
+++ b/src/korgalore/google_creds.py
@@ -3,7 +3,7 @@
import logging
import os
import subprocess
-from collections.abc import Sequence
+from collections.abc import Callable, Sequence
from pathlib import Path
from typing import Any
@@ -14,10 +14,44 @@ from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow # type: ignore[import-untyped]
-from korgalore import AuthenticationError, ConfigurationError, RemoteError, atomic_write, split_command
+from korgalore import (
+ AuthenticationError,
+ ConfigurationError,
+ InsufficientScopesError,
+ RemoteError,
+ atomic_write,
+ split_command,
+)
logger = logging.getLogger('korgalore')
+
+def effective_creds_scopes(creds: Any) -> Any:
+ """Return concrete granted scopes, falling back to configured scopes.
+
+ Args:
+ creds: Google credentials instance loaded from disk or OAuth flow.
+
+ Returns:
+ Granted scope collection if present as a concrete sequence or set,
+ otherwise the credential's configured ``scopes`` attribute or ``None``.
+ """
+ # Prefer granted_scopes only when it is a concrete collection so tokens
+ # without explicit granted_scopes still fall back to .scopes.
+ granted = getattr(creds, 'granted_scopes', None)
+ if isinstance(granted, (list, tuple, set, frozenset)):
+ return granted
+ return getattr(creds, 'scopes', None)
+
+
+def default_scope_checker(granted_scopes: Any, required_scopes: Sequence[str]) -> bool:
+ """Check whether concrete granted scopes cover every required scope."""
+ if not isinstance(granted_scopes, (list, tuple, set, frozenset)):
+ return True
+ granted = {s.rstrip('/') for s in granted_scopes if isinstance(s, str) and s}
+ return all(req.rstrip('/') in granted for req in required_scopes)
+
+
# InstalledAppFlow.run_local_server() returns either flavour depending on what
# the client_secrets file describes. Both expose the valid/expired/refresh_token
# attributes and the to_json() and refresh() methods used below, so the code
@@ -36,6 +70,7 @@ class OAuthFileCredentials(BaseCredentials):
scopes: Sequence[str],
interactive: bool = True,
target_type: str = 'gmail',
+ scope_checker: Callable[[Any, Sequence[str]], bool] | None = None,
) -> None:
"""Initialize file-backed OAuth credentials for a Google target.
@@ -52,6 +87,8 @@ class OAuthFileCredentials(BaseCredentials):
If False, raise ``AuthenticationError`` on
``refresh()`` instead (for GUI/unattended mode).
target_type: Target type string reported in AuthenticationError.
+ scope_checker: Optional callable validating granted scopes against
+ required scopes.
Raises:
ConfigurationError: If credentials file path is empty.
@@ -63,6 +100,7 @@ class OAuthFileCredentials(BaseCredentials):
self._scopes = list(scopes)
self._target_type = target_type
self.needs_auth = False
+ self._scope_checker = scope_checker or default_scope_checker
if not credentials_file:
raise ConfigurationError(f"No credentials file specified for target '{identifier}'.")
@@ -114,11 +152,30 @@ class OAuthFileCredentials(BaseCredentials):
if self._creds:
self._creds.expiry = value
+ def _has_required_scopes(self, creds: Any) -> bool:
+ """Return True if credentials satisfy all required scopes."""
+ return self._scope_checker(effective_creds_scopes(creds), self._scopes)
+
@property
def valid(self) -> bool:
- """Whether loaded OAuth2 credentials are present and currently valid."""
+ """Whether loaded OAuth2 credentials are valid and satisfy required scopes."""
+ if self._creds and not self._has_required_scopes(self._creds):
+ return False
return bool(self._creds and self._creds.valid)
+ @property
+ def interactive(self) -> bool:
+ """Whether this credential provider may prompt interactively."""
+ return self._interactive
+
+ def _missing_scopes_error(self) -> InsufficientScopesError:
+ """Build an InsufficientScopesError with remediation instructions."""
+ return InsufficientScopesError(
+ f"OAuth token for '{self.identifier}' lacks required scopes. Run 'kgl auth {self.identifier}'.",
+ target_id=self.identifier,
+ target_type=self._target_type,
+ )
+
def _save_token(self) -> None:
"""Persist current OAuth credentials to the configured token file."""
if self._creds is None:
@@ -148,32 +205,49 @@ class OAuthFileCredentials(BaseCredentials):
authentication is needed.
AuthenticationError: If refresh fails or authentication is needed
in non-interactive mode.
+ InsufficientScopesError: If the loaded or refreshed token lacks
+ required OAuth scopes.
"""
just_loaded = self._load_token_file()
- if just_loaded and self._creds and self._creds.valid:
- self.needs_auth = False
- return
-
- req = request or Request()
- # If there are no (valid) credentials available, refresh or let the user log in
- if self._creds and self._creds.refresh_token:
- try:
- self._creds.refresh(req) # type: ignore[no-untyped-call]
- self._save_token()
+ if self._creds and not self._has_required_scopes(self._creds):
+ if not self._interactive:
+ self.needs_auth = True
+ raise self._missing_scopes_error()
+ logger.info("OAuth token for '%s' lacks required scopes; re-authenticating...", self.identifier)
+ else:
+ if just_loaded and self._creds and self._creds.valid:
self.needs_auth = False
return
- except RefreshError as e:
- logger.warning('OAuth token for target %s has expired or been revoked.', self.identifier)
- self._quarantine_token()
- self._creds = None
- if not self._interactive:
- self.needs_auth = True
- # In non-interactive mode (GUI), fail fast so the UI can prompt re-auth
- raise AuthenticationError(
- f"OAuth token for '{self.identifier}' is invalid. Please re-authenticate.",
- target_id=self.identifier,
- target_type=self._target_type,
- ) from e
+
+ req = request or Request()
+ # If there are no (valid) credentials available, refresh or let the user log in
+ if self._creds and self._creds.refresh_token:
+ try:
+ self._creds.refresh(req) # type: ignore[no-untyped-call]
+ if not self._has_required_scopes(self._creds):
+ if not self._interactive:
+ self.needs_auth = True
+ raise self._missing_scopes_error()
+ logger.info(
+ "OAuth token for '%s' lacks required scopes; re-authenticating...",
+ self.identifier,
+ )
+ else:
+ self._save_token()
+ self.needs_auth = False
+ return
+ except RefreshError as e:
+ logger.warning('OAuth token for target %s has expired or been revoked.', self.identifier)
+ self._quarantine_token()
+ self._creds = None
+ if not self._interactive:
+ self.needs_auth = True
+ # In non-interactive mode (GUI), fail fast so the UI can prompt re-auth
+ raise AuthenticationError(
+ f"OAuth token for '{self.identifier}' is invalid. Please re-authenticate.",
+ target_id=self.identifier,
+ target_type=self._target_type,
+ ) from e
if not self._credentials_file.exists():
raise ConfigurationError(
@@ -198,6 +272,8 @@ class OAuthFileCredentials(BaseCredentials):
Raises:
ConfigurationError: If credentials file is not found.
AuthenticationError: If the local OAuth authorization flow fails.
+ InsufficientScopesError: If the user completes OAuth consent without
+ granting all required scopes.
"""
if not self._credentials_file.exists():
raise ConfigurationError(
@@ -206,7 +282,7 @@ class OAuthFileCredentials(BaseCredentials):
logger.critical('Log in to account for %s', self.identifier)
try:
flow = InstalledAppFlow.from_client_secrets_file(str(self._credentials_file), self._scopes)
- self._creds = flow.run_local_server(port=0)
+ new_creds = flow.run_local_server(port=0)
except Exception as e:
self.needs_auth = True
raise AuthenticationError(
@@ -214,6 +290,12 @@ class OAuthFileCredentials(BaseCredentials):
target_id=self.identifier,
target_type=self._target_type,
) from e
+ # Validate scopes on the fresh credentials before updating self._creds or
+ # saving token.json so partial consent never overwrites a working token.
+ if not self._has_required_scopes(new_creds):
+ self.needs_auth = True
+ raise self._missing_scopes_error()
+ self._creds = new_creds
self._save_token()
self.needs_auth = False
diff --git a/src/korgalore/imap_target.py b/src/korgalore/imap_target.py
index 73bc280..824495a 100644
--- a/src/korgalore/imap_target.py
+++ b/src/korgalore/imap_target.py
@@ -258,6 +258,7 @@ class ImapTarget:
feed_name: str | None = None,
delivery_name: str | None = None,
subfolder: str | None = None,
+ initial_labels: list[str] | None = None,
) -> Any:
"""Import raw email message to IMAP server.
@@ -267,6 +268,7 @@ class ImapTarget:
feed_name: Optional feed name for trace header
delivery_name: Optional delivery name for trace header
subfolder: Optional subfolder path relative to target's folder
+ initial_labels: Ignored for IMAP (single folder only)
Returns:
IMAP response from APPEND command
diff --git a/src/korgalore/jmap_target.py b/src/korgalore/jmap_target.py
index 35dc59e..5d30d65 100644
--- a/src/korgalore/jmap_target.py
+++ b/src/korgalore/jmap_target.py
@@ -76,6 +76,69 @@ class JmapTarget:
# Mailbox cache
self._mailbox_map: dict[str, str] | None = None # name -> id
+ # Per-pull session cache: clean_msgid -> (email_id, applied_mailbox_ids, created_in_pull)
+ self._imported_msgids: dict[str, tuple[str, set[str], bool]] = {}
+
+ def _add_mailboxes(self, email_id: str, mailbox_ids: list[str]) -> bool:
+ """Add mailbox IDs to an existing email via JMAP Email/set.
+
+ Args:
+ email_id: Existing JMAP email ID to update.
+ mailbox_ids: Mailbox IDs to attach to the email.
+
+ Returns:
+ True if the update succeeded (or nothing needed updating), or False if
+ the server reported ``notFound`` so the caller can fall back to import.
+
+ Raises:
+ RemoteError: If the HTTP request fails or JMAP returns another error.
+ """
+ if not mailbox_ids or not self.api_url:
+ return True
+ update_patch = {f'mailboxIds/{mb_id}': True for mb_id in mailbox_ids}
+ request_body = {
+ 'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:mail'],
+ 'methodCalls': [
+ [
+ 'Email/set',
+ {
+ 'accountId': self.account_id,
+ 'update': {
+ email_id: update_patch,
+ },
+ },
+ 'call-set',
+ ]
+ ],
+ }
+ try:
+ response = self._get_session().post(
+ self.api_url,
+ json=request_body,
+ headers={'Authorization': f'Bearer {self.token}'},
+ timeout=self.timeout,
+ )
+ response.raise_for_status()
+ result = response.json()
+ except requests.RequestException as e:
+ raise RemoteError(f'Failed to update mailboxes for email {email_id}: {e}') from e
+
+ for method_response in result.get('methodResponses', []):
+ method_name, method_result, _ = method_response
+ if method_name == 'error':
+ raise RemoteError(f'JMAP Email/set failed: {method_result}')
+ if method_name == 'Email/set':
+ not_updated = method_result.get('notUpdated') or {}
+ if email_id in not_updated:
+ err = not_updated[email_id]
+ if isinstance(err, dict) and err.get('type') == 'notFound':
+ logger.debug('Existing JMAP message %s vanished before Email/set update', email_id)
+ return False
+ raise RemoteError(f'JMAP Email/set failed: {not_updated}')
+ if not_updated:
+ raise RemoteError(f'JMAP Email/set failed: {not_updated}')
+ return True
+
def _get_session(self) -> requests.Session:
"""Get requests session, using provided one or falling back to requests module."""
if self._reqsession is not None:
@@ -296,6 +359,63 @@ class JmapTarget:
logger.debug('Failed to check for existing message: %s', e)
return False
+ def _find_existing_message(self, message_id: str) -> str | None:
+ """Find any existing email in the JMAP account matching Message-ID.
+
+ Expects angle-bracketed Message-IDs so RFC 8621 header substring matching
+ is bounded and does not match substrings of unrelated Message-IDs. Unlike
+ ``_check_message_exists``, query errors fail closed by raising
+ ``RemoteError`` instead of returning None and risking duplicate imports
+ with initial labels into INBOX.
+
+ Args:
+ message_id: Angle-bracketed RFC 5322 Message-ID header value.
+
+ Returns:
+ JMAP email ID if found in any mailbox, or None if absent.
+
+ Raises:
+ RemoteError: If the HTTP request fails or JMAP returns an error.
+ """
+ assert self.api_url is not None, 'Must call connect() first'
+ request_body = {
+ 'using': ['urn:ietf:params:jmap:core', 'urn:ietf:params:jmap:mail'],
+ 'methodCalls': [
+ [
+ 'Email/query',
+ {
+ 'accountId': self.account_id,
+ 'filter': {'header': ['Message-ID', message_id]},
+ 'limit': 1,
+ },
+ 'call-0',
+ ]
+ ],
+ }
+ try:
+ response = self._get_session().post(
+ self.api_url,
+ json=request_body,
+ headers={'Authorization': f'Bearer {self.token}'},
+ timeout=self.timeout,
+ )
+ response.raise_for_status()
+ result = response.json()
+ except requests.RequestException as e:
+ raise RemoteError(f'Failed to query JMAP message {message_id}: {e}') from e
+
+ for method_response in result.get('methodResponses', []):
+ method_name, method_result, _ = method_response
+ if method_name == 'error':
+ raise RemoteError(f'JMAP Email/query failed: {method_result}')
+ if method_name == 'Email/query':
+ ids = method_result.get('ids', [])
+ if ids:
+ return str(ids[0])
+ return None
+
+ raise RemoteError(f'Unexpected JMAP Email/query response: {result}')
+
def import_message(
self,
raw_message: bytes,
@@ -303,6 +423,7 @@ class JmapTarget:
feed_name: str | None = None,
delivery_name: str | None = None,
subfolder: str | None = None,
+ initial_labels: list[str] | None = None,
) -> Any:
"""Import raw email message to JMAP server.
@@ -312,6 +433,7 @@ class JmapTarget:
feed_name: Optional feed name for trace header
delivery_name: Optional delivery name for trace header
subfolder: Ignored for JMAP (use labels for multiple folders)
+ initial_labels: Optional initial folder names applied only on initial arrival
Returns:
JMAP import result dict
@@ -326,17 +448,52 @@ class JmapTarget:
else:
# Default to INBOX if no folders specified
mailbox_ids_list = self.translate_folders(['inbox'])
-
- # Step 2: Check if message already exists in target mailbox(es)
+ literal_mb_set = set(mailbox_ids_list)
+
+ effective_initial_mb_ids: list[str] = []
+ if initial_labels:
+ raw_initial_mb_ids = self.translate_folders(initial_labels)
+ effective_initial_mb_ids = [
+ mb_id for mb_id in dict.fromkeys(raw_initial_mb_ids) if mb_id not in literal_mb_set
+ ]
+
+ clean_msgid = msg.message_id.strip('<>').strip() or None if msg.message_id else None
+
+ # Step 2: Check intra-pull cache
+ if clean_msgid and clean_msgid in self._imported_msgids:
+ existing_id, applied_mb_ids, created_in_pull = self._imported_msgids[clean_msgid]
+ target_mb_ids = mailbox_ids_list + (effective_initial_mb_ids if created_in_pull else [])
+ missing_mb_ids = [mb_id for mb_id in target_mb_ids if mb_id not in applied_mb_ids]
+ if not missing_mb_ids:
+ logger.debug('Skipping duplicate JMAP import for %s in same pull', clean_msgid)
+ return {'id': existing_id, 'skipped': True}
+
+ if self._add_mailboxes(existing_id, missing_mb_ids):
+ applied_mb_ids.update(missing_mb_ids)
+ return {'id': existing_id, 'modified': True}
+ logger.debug('Existing JMAP message %s vanished before update; falling back to import', existing_id)
+ self._imported_msgids.pop(clean_msgid, None)
+
+ # Step 3: Check if message already exists in target mailbox(es)
if msg.message_id and self._check_message_exists(msg.message_id, mailbox_ids_list):
logger.debug('Skipping import: message %s already in target mailbox', msg.message_id)
return {'id': '(duplicate)', 'skipped': True}
- # Step 3: Upload blob
+ # Step 3b: Check if message already exists anywhere in the JMAP account
+ if effective_initial_mb_ids and clean_msgid:
+ found_id = self._find_existing_message(f'<{clean_msgid}>')
+ if found_id is not None:
+ if self._add_mailboxes(found_id, mailbox_ids_list):
+ self._imported_msgids[clean_msgid] = (found_id, set(mailbox_ids_list), False)
+ return {'id': found_id, 'modified': True}
+ logger.debug('Existing JMAP message %s vanished before update; falling back to import', found_id)
+
+ # Step 4: Upload blob
blob_id = self._upload_blob(msg.as_bytes(feed_name, delivery_name))
+ all_mb_ids = mailbox_ids_list + effective_initial_mb_ids
# Build mailboxIds dict (id -> true)
- mailbox_ids = {mb_id: True for mb_id in mailbox_ids_list}
+ mailbox_ids = {mb_id: True for mb_id in all_mb_ids}
email: dict[str, Any] = {
'blobId': blob_id,
@@ -378,7 +535,10 @@ class JmapTarget:
# Check for successful creation first
created = method_result.get('created', {})
if 'msg1' in created:
- logger.debug('Imported message: %s', created['msg1']['id'])
+ msg_id = str(created['msg1']['id'])
+ logger.debug('Imported message: %s', msg_id)
+ if clean_msgid:
+ self._imported_msgids[clean_msgid] = (msg_id, set(all_mb_ids), True)
return created['msg1']
# If not created, check if there were errors (notCreated will be non-empty)
@@ -388,6 +548,13 @@ class JmapTarget:
if 'msg1' in not_created and not_created['msg1'].get('type') == 'alreadyExists':
existing_id = not_created['msg1'].get('existingId', '(unknown)')
logger.debug('Message already exists with id: %s', existing_id)
+ if (
+ existing_id
+ and existing_id != '(unknown)'
+ and self._add_mailboxes(existing_id, mailbox_ids_list)
+ and clean_msgid
+ ):
+ self._imported_msgids[clean_msgid] = (existing_id, set(mailbox_ids_list), False)
return {'id': existing_id}
# Any other error is a real failure
raise RemoteError(f'JMAP Email/import failed: {not_created}')
diff --git a/src/korgalore/maildir_target.py b/src/korgalore/maildir_target.py
index 3c12978..56be4ce 100644
--- a/src/korgalore/maildir_target.py
+++ b/src/korgalore/maildir_target.py
@@ -85,6 +85,7 @@ class MaildirTarget:
feed_name: str | None = None,
delivery_name: str | None = None,
subfolder: str | None = None,
+ initial_labels: list[str] | None = None,
) -> Any:
"""Import message to maildir.
@@ -94,6 +95,7 @@ class MaildirTarget:
feed_name: Optional feed name for trace header
delivery_name: Optional delivery name for trace header
subfolder: Optional subfolder path relative to base maildir
+ initial_labels: Ignored for maildir (single folder per target)
Returns:
Message key from maildir
diff --git a/src/korgalore/pipe_target.py b/src/korgalore/pipe_target.py
index bb026de..d688d7d 100644
--- a/src/korgalore/pipe_target.py
+++ b/src/korgalore/pipe_target.py
@@ -63,6 +63,7 @@ class PipeTarget:
feed_name: str | None = None,
delivery_name: str | None = None,
subfolder: str | None = None,
+ initial_labels: list[str] | None = None,
) -> Any:
"""Pipe message to the configured command.
@@ -72,6 +73,7 @@ class PipeTarget:
feed_name: Optional feed name for trace header
delivery_name: Optional delivery name for trace header
subfolder: Ignored for pipe target (no folder concept)
+ initial_labels: Ignored for pipe target
Returns:
Return code from the command
diff --git a/tests/test_cli_misc.py b/tests/test_cli_misc.py
index 427e8c6..becc858 100644
--- a/tests/test_cli_misc.py
+++ b/tests/test_cli_misc.py
@@ -16,10 +16,12 @@ from unittest.mock import MagicMock, patch
import click
import pytest
from click.testing import CliRunner
+from googleapiclient.errors import HttpError # type: ignore[import-untyped]
-from korgalore import format_key_for_display
-from korgalore.cli import get_target, progress_file, pull
-from korgalore.gmail_target import GmailTarget, make_gmail_credentials
+from korgalore import InsufficientScopesError, format_key_for_display
+from korgalore.cli import auth, get_target, progress_file, pull
+from korgalore.gmail_target import MODIFY_SCOPES, GmailTarget, make_gmail_credentials
+from korgalore.google_creds import OAuthFileCredentials
from tests.digest_helpers import make_ctx
@@ -178,3 +180,90 @@ def test_get_target_non_interactive_when_gui_mode() -> None:
assert res == 'target-service'
assert mock_gmail.call_args.kwargs['interactive'] is False
assert mock_gmail.call_args.kwargs['identifier'] == 'test'
+
+
+def test_auth_connects_target_successfully() -> None:
+ runner = CliRunner()
+ ctx_obj = {
+ 'config': {'targets': {'test': {'type': 'gmail', 'credentials': 'creds.json'}}},
+ 'targets': {},
+ }
+ with patch('korgalore.cli.get_target') as mock_gt:
+ target = MagicMock()
+ mock_gt.return_value = target
+ res = runner.invoke(auth, ['test'], obj=ctx_obj)
+ assert res.exit_code == 0
+ target.connect.assert_called_once()
+
+
+def test_auth_aborts_when_connect_raises_insufficient_scopes() -> None:
+ runner = CliRunner()
+ ctx_obj = {
+ 'config': {'targets': {'test': {'type': 'gmail', 'credentials': 'creds.json'}}},
+ 'targets': {},
+ }
+ with patch('korgalore.cli.get_target') as mock_gt:
+ target = MagicMock()
+ target.connect.side_effect = InsufficientScopesError('need modify', target_id='test', target_type='gmail')
+ mock_gt.return_value = target
+ res = runner.invoke(auth, ['test'], obj=ctx_obj)
+ assert res.exit_code == 1
+ target.connect.assert_called_once()
+
+
+def gmail_http_403_scope_error() -> HttpError:
+ resp = MagicMock()
+ resp.status = 403
+ return HttpError(resp, b'{"error": {"message": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"}}')
+
+
+def test_auth_gmail_scope_probe_403_reauthenticates(tmp_path: Path) -> None:
+ runner = CliRunner()
+ creds_path = tmp_path / 'creds.json'
+ creds_path.write_text('{}')
+ provider = OAuthFileCredentials('test', str(creds_path), str(tmp_path / 'token.json'), scopes=MODIFY_SCOPES)
+ provider._creds = MagicMock(valid=True, scopes=None, granted_scopes=None)
+ gt = GmailTarget('test', creds=provider, requires_modify=True)
+
+ probe_service = MagicMock()
+ probe_service.users().labels().list().execute.return_value = {'labels': []}
+ probe_service.users().messages().list().execute.side_effect = [
+ gmail_http_403_scope_error(),
+ {'messages': []},
+ ]
+ ctx_obj = {
+ 'config': {'targets': {'test': {'type': 'gmail', 'credentials': str(creds_path)}}},
+ 'targets': {},
+ }
+
+ with (
+ patch('korgalore.cli.get_target', return_value=gt),
+ patch('korgalore.gmail_target.build', return_value=probe_service),
+ patch.object(provider, 'reauthenticate') as mock_reauth,
+ ):
+ mock_reauth.side_effect = lambda: setattr(
+ provider, '_creds', MagicMock(valid=True, scopes=None, granted_scopes=None)
+ )
+ res = runner.invoke(auth, ['test'], obj=ctx_obj)
+ assert res.exit_code == 0
+ mock_reauth.assert_called_once()
+ assert probe_service.users().messages().list().execute.call_count == 2
+
+
+def test_auth_gmail_token_command_scope_probe_403_aborts() -> None:
+ runner = CliRunner()
+ ctx_obj = {
+ 'config': {'targets': {'test': {'type': 'gmail', 'token_command': 'get-token'}}},
+ 'targets': {},
+ }
+ probe_service = MagicMock()
+ probe_service.users().labels().list().execute.return_value = {'labels': []}
+ probe_service.users().messages().list().execute.side_effect = gmail_http_403_scope_error()
+ gt = GmailTarget('test', creds=MagicMock(valid=True), requires_modify=True)
+
+ with (
+ patch('korgalore.cli.get_target', return_value=gt),
+ patch('korgalore.gmail_target.build', return_value=probe_service),
+ ):
+ res = runner.invoke(auth, ['test'], obj=ctx_obj)
+ assert res.exit_code == 1
diff --git a/tests/test_gmail_target.py b/tests/test_gmail_target.py
index 35c37c2..1e28054 100644
--- a/tests/test_gmail_target.py
+++ b/tests/test_gmail_target.py
@@ -1,6 +1,7 @@
"""Tests for GmailTarget message delivery."""
import base64
+import logging
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock, patch
@@ -9,8 +10,8 @@ import pytest
from google.auth.credentials import Credentials as BaseCredentials
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 import AuthenticationError, ConfigurationError, InsufficientScopesError, RemoteError
+from korgalore.gmail_target import MODIFY_SCOPES, SCOPES, GmailTarget, has_gmail_scopes, make_gmail_credentials
from korgalore.google_creds import CommandCredentials, OAuthFileCredentials
@@ -453,3 +454,302 @@ class TestMakeGmailCredentials:
mock_credentials.from_authorized_user_file.assert_called_once_with(str(default_token))
assert creds._scopes == SCOPES
+
+ def test_requires_modify_uses_modify_scopes_and_gmail_checker(self, tmp_path: Path) -> None:
+ """requires_modify=True selects MODIFY_SCOPES and Gmail scope equivalence checker."""
+ creds = make_gmail_credentials(
+ 'work',
+ {'credentials': str(tmp_path / 'creds.json'), 'token': str(tmp_path / 'token.json')},
+ UNUSED_CONFIG_DIR,
+ requires_modify=True,
+ )
+
+ assert isinstance(creds, OAuthFileCredentials)
+ assert creds._scopes == MODIFY_SCOPES
+ assert creds._scope_checker is has_gmail_scopes
+
+ def test_has_gmail_scopes_hierarchy(self) -> None:
+ """Higher-privilege Gmail scopes satisfy lower-privilege required scopes."""
+ assert has_gmail_scopes(['https://mail.google.com/'], MODIFY_SCOPES)
+ assert has_gmail_scopes(['https://www.googleapis.com/auth/gmail.modify'], SCOPES)
+ assert has_gmail_scopes(
+ ['https://www.googleapis.com/auth/gmail.readonly', 'https://www.googleapis.com/auth/gmail.insert'],
+ SCOPES,
+ )
+ assert has_gmail_scopes(
+ ['https://www.googleapis.com/auth/gmail.metadata', 'https://www.googleapis.com/auth/gmail.insert'],
+ SCOPES,
+ )
+ assert not has_gmail_scopes(['https://www.googleapis.com/auth/gmail.labels'], SCOPES)
+ assert not has_gmail_scopes(SCOPES, MODIFY_SCOPES)
+
+
+class TestGmailTargetDedupAndScopes:
+ """Tests for intra-pull dedup cache and scope handling."""
+
+ def test_intra_pull_dedup_skips_duplicate(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+ """Subsequent deliveries of same message in same pull with same labels make 0 RPCs."""
+ target, service = gmail_labels
+ service.users().messages().import_().execute.return_value = {'id': 'msg-1'}
+ raw = b'Message-ID: <test@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+ res1 = target.import_message(raw, ['INBOX'])
+ assert res1 == {'id': 'msg-1'}
+ assert service.users().messages().import_().execute.call_count == 1
+
+ # Second delivery of same message with same label in same pull
+ res2 = target.import_message(raw, ['INBOX'])
+ assert res2 == {'id': 'msg-1', 'skipped': True}
+ assert service.users().messages().import_().execute.call_count == 1
+ service.users().messages().modify.assert_not_called()
+
+ def test_intra_pull_dedup_adds_missing_labels(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+ """Subsequent delivery with new label modifies the message."""
+ target, service = gmail_labels
+ target.requires_modify = True
+ service.users().messages().import_.return_value.execute.return_value = {'id': 'msg-1'}
+ service.users().messages().modify.return_value.execute.return_value = {'id': 'msg-1', 'modified': True}
+ raw = b'Message-ID: <test@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+ target.import_message(raw, ['INBOX'])
+ res2 = target.import_message(raw, ['INBOX', 'MyLabel'])
+
+ assert res2 == {'id': 'msg-1', 'modified': True}
+ service.users().messages().modify.assert_called_once_with(
+ userId='me', id='msg-1', body={'addLabelIds': ['Label_123']}
+ )
+
+ def test_pre_existing_message_omits_unread_and_skips_initial(
+ self, gmail_labels: tuple[GmailTarget, MagicMock]
+ ) -> None:
+ """Pre-existing message found via list: skips initial_labels and omits UNREAD."""
+ target, service = gmail_labels
+ target.requires_modify = True
+ service.users().messages().list.return_value.execute.return_value = {'messages': [{'id': 'existing-msg'}]}
+ service.users().messages().modify.return_value.execute.return_value = {'id': 'existing-msg'}
+ raw = b'Message-ID: <pre@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+ res = target.import_message(raw, ['MyLabel', 'UNREAD'], initial_labels=['INBOX'])
+
+ assert res == {'id': 'existing-msg'}
+ service.users().messages().import_.assert_not_called()
+ # Initial label INBOX was skipped, UNREAD was omitted, only MyLabel was added
+ service.users().messages().modify.assert_called_once_with(
+ userId='me', id='existing-msg', body={'addLabelIds': ['Label_123']}
+ )
+
+ def test_http_403_scope_error_translation(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+ """HTTP 403 with ACCESS_TOKEN_SCOPE_INSUFFICIENT translates to InsufficientScopesError."""
+ target, service = gmail_labels
+ service.users().messages().import_().execute.side_effect = http_error(
+ 403, b'{"error": {"message": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"}}'
+ )
+
+ with pytest.raises(InsufficientScopesError):
+ target.import_message(b'Test', ['INBOX'])
+
+ def test_http_401_auth_error_translation(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+ """HTTP 401 translates to AuthenticationError when can_reauthenticate is True."""
+ target, service = gmail_labels
+ target.creds = MagicMock(spec=OAuthFileCredentials)
+ service.users().messages().import_().execute.side_effect = http_error(401, b'Unauthorized')
+
+ with pytest.raises(AuthenticationError):
+ target.import_message(b'Test', ['INBOX'])
+
+ def test_pre_existing_empty_modify_labels_caches_empty_applied_set(
+ self, gmail_labels: tuple[GmailTarget, MagicMock]
+ ) -> None:
+ """Skipping pre-existing message with no non-UNREAD labels leaves UNREAD uncached."""
+ target, service = gmail_labels
+ target.requires_modify = True
+ service.users().messages().list.return_value.execute.return_value = {'messages': [{'id': 'existing-msg'}]}
+ service.users().messages().modify.return_value.execute.return_value = {'id': 'existing-msg'}
+ raw = b'Message-ID: <pre2@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+ res1 = target.import_message(raw, ['UNREAD'], initial_labels=['INBOX'])
+ assert res1 == {'id': 'existing-msg', 'skipped': True}
+ assert target._imported_msgids['pre2@example.com'] == ('existing-msg', set(), False)
+ service.users().messages().modify.assert_not_called()
+
+ res2 = target.import_message(raw, ['MyLabel', 'UNREAD'])
+ assert res2 == {'id': 'existing-msg'}
+ service.users().messages().modify.assert_called_once_with(
+ userId='me', id='existing-msg', body={'addLabelIds': ['Label_123']}
+ )
+
+ def test_intra_pull_non_modify_fallthrough_preserves_prior_applied_labels(
+ self, gmail_labels: tuple[GmailTarget, MagicMock]
+ ) -> None:
+ """Falling through to import_ without modify unions prior applied labels in cache."""
+ target, service = gmail_labels
+ target.requires_modify = False
+ service.users().messages().import_.return_value.execute.return_value = {'id': 'msg-1'}
+ raw = b'Message-ID: <cross@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+ target.import_message(raw, ['INBOX', 'MyLabel'])
+ target.import_message(raw, ['UNREAD'])
+ res3 = target.import_message(raw, ['INBOX'])
+
+ assert res3 == {'id': 'msg-1', 'skipped': True}
+ assert service.users().messages().import_.call_count == 2
+ assert target._imported_msgids['cross@example.com'] == ('msg-1', {'INBOX', 'Label_123', 'UNREAD'}, True)
+
+ def test_reauthenticate_clears_dedup_cache(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+ """GmailTarget.reauthenticate() clears _imported_msgids."""
+ target, service = gmail_labels
+ target.creds = MagicMock(spec=OAuthFileCredentials)
+ service.users().messages().import_().execute.return_value = {'id': 'msg-1'}
+ target.import_message(b'Message-ID: <reauth@example.com>\r\n\r\nBody', ['INBOX'])
+ assert target._imported_msgids
+
+ target.reauthenticate()
+ assert target._imported_msgids == {}
+
+ def test_connect_probes_messages_list_only_when_requires_modify(
+ self, gmail_labels: tuple[GmailTarget, MagicMock]
+ ) -> None:
+ """connect() probes messages().list() only when requires_modify is True."""
+ target, service = gmail_labels
+ with patch('korgalore.gmail_target.build', return_value=service):
+ target.service = None
+ target.connect()
+ service.users().labels().list.assert_called_once_with(userId='me')
+ service.users().messages().list.assert_not_called()
+
+ target.service = None
+ target._label_map = None
+ target.requires_modify = True
+ target.connect()
+ service.users().messages().list.assert_called_once()
+
+ def test_http_403_scope_error_action_by_credential_type(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+ """HTTP 403 insufficient scope message tailors remediation to credential type."""
+ target, service = gmail_labels
+ target.requires_modify = True
+ service.users().messages().list().execute.side_effect = http_error(
+ 403, b'{"error": {"message": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"}}'
+ )
+
+ with patch('korgalore.gmail_target.build', return_value=service):
+ target.creds = MagicMock(spec=OAuthFileCredentials)
+ target.creds.interactive = False
+ target.service = None
+ with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+ target.connect()
+ assert target.service is None
+
+ target.creds = MagicMock(spec=OAuthFileCredentials)
+ target.creds.interactive = True
+ target.service = None
+ with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+ target.connect()
+ assert target.service is None
+ target.creds.reauthenticate.assert_called_once()
+
+ target.creds = CommandCredentials('test', ['echo', 'tok'])
+ target.service = None
+ with pytest.raises(InsufficientScopesError, match='token_command'):
+ target.connect()
+ assert target.service is None
+
+ def test_connect_scope_probe_403_interactive_reauth_retries_and_succeeds(
+ self, gmail_labels: tuple[GmailTarget, MagicMock]
+ ) -> None:
+ """connect() catches InsufficientScopesError, reauthenticates, and retries once."""
+ target, _ = gmail_labels
+ target.requires_modify = True
+ creds = MagicMock(spec=OAuthFileCredentials)
+ creds.interactive = True
+ creds.valid = True
+ target.creds = creds
+ target.service = None
+
+ service1 = MagicMock()
+ service1.users().labels().list().execute.return_value = {'labels': []}
+ service1.users().messages().list().execute.side_effect = http_error(
+ 403, b'{"error": {"message": "ACCESS_TOKEN_SCOPE_INSUFFICIENT"}}'
+ )
+
+ service2: Any = MagicMock()
+ service2.users().labels().list().execute.return_value = {'labels': [{'id': 'INBOX', 'name': 'INBOX'}]}
+ service2.users().messages().list().execute.return_value = {'messages': []}
+
+ with patch('korgalore.gmail_target.build', side_effect=[service1, service2]):
+ target.connect()
+
+ creds.reauthenticate.assert_called_once()
+ assert target.service is service2
+ assert target._label_map == {'INBOX': 'INBOX'}
+
+ def test_label_names_mapping(self, gmail_labels: tuple[GmailTarget, MagicMock]) -> None:
+ """_label_names maps label IDs back to human-readable names."""
+ target, _ = gmail_labels
+ assert target._label_names(['INBOX', 'Label_123', 'UNKNOWN']) == ['INBOX', 'MyLabel', 'UNKNOWN']
+ assert target._label_names([]) == []
+
+ def test_import_and_modify_debug_logging(
+ self,
+ gmail_labels: tuple[GmailTarget, MagicMock],
+ caplog: pytest.LogCaptureFixture,
+ ) -> None:
+ """import_message logs human-readable label names for imports and modifications."""
+ target, service = gmail_labels
+ target.requires_modify = True
+ service.users().messages().import_().execute.return_value = {'id': 'msg-1'}
+ service.users().messages().modify().execute.return_value = {'id': 'msg-1'}
+
+ raw = b'Message-ID: <test-log@example.com>\r\nSubject: Hi\r\n\r\nBody'
+
+ with caplog.at_level(logging.DEBUG, logger='korgalore'):
+ # Path 1: Initial import (message not in Gmail yet)
+ service.users().messages().list().execute.return_value = {'messages': []}
+ target.import_message(raw, ['INBOX'], initial_labels=['MyLabel'])
+ assert "Importing message test-log@example.com to Gmail with labels: ['INBOX', 'MyLabel']" in caplog.text
+
+ caplog.clear()
+ # Path 2: Same-pull duplicate with new label
+ target.import_message(raw, ['UNREAD'])
+ assert "Adding Gmail labels ['UNREAD'] to duplicate message test-log@example.com (msg-1)" in caplog.text
+
+ caplog.clear()
+ # Path 3: Pre-existing message
+ service.users().messages().list().execute.return_value = {'messages': [{'id': 'msg-pre'}]}
+ service.users().messages().modify().execute.return_value = {'id': 'msg-pre'}
+ raw_pre = b'Message-ID: <pre-exist@example.com>\r\nSubject: Old\r\n\r\nBody'
+ target.import_message(raw_pre, ['MyLabel'], initial_labels=['INBOX'])
+ assert "Adding Gmail labels ['MyLabel'] to existing message pre-exist@example.com (msg-pre)" in caplog.text
+
+ def test_requires_modify_with_never_mark_spam_and_404_fallback(self) -> None:
+ """import_message forwards internalDateSource/neverMarkSpam on 404 fallback, not on modify."""
+ target, _ = make_target(message_date='import', never_mark_spam=True, requires_modify=True)
+ service = MagicMock()
+ target.service = service
+ target._label_map = {'INBOX': 'INBOX', 'MyLabel': 'Label_123'}
+ messages = service.users.return_value.messages.return_value
+
+ raw_existing = b'Message-ID: <existing@example.com>\r\nSubject: Hi\r\n\r\nBody'
+ messages.list.return_value.execute.return_value = {'messages': [{'id': 'msg-existing'}]}
+ messages.modify.return_value.execute.return_value = {'id': 'msg-existing'}
+
+ res_existing = target.import_message(raw_existing, ['MyLabel'], initial_labels=['INBOX'])
+
+ assert res_existing == {'id': 'msg-existing'}
+ messages.modify.assert_called_once_with(userId='me', id='msg-existing', body={'addLabelIds': ['Label_123']})
+ messages.import_.assert_not_called()
+
+ # Pre-existing message vanishes before modify() -> falls back to import_()
+ raw_vanished = b'Message-ID: <vanished@example.com>\r\nSubject: Gone\r\n\r\nBody'
+ messages.list.return_value.execute.return_value = {'messages': [{'id': 'msg-gone'}]}
+ messages.modify.return_value.execute.side_effect = http_error(404, b'Not Found')
+ messages.import_.return_value.execute.return_value = {'id': 'msg-reimported'}
+
+ res = target.import_message(raw_vanished, ['MyLabel'], initial_labels=['INBOX'])
+
+ assert res == {'id': 'msg-reimported'}
+ messages.modify.assert_called_with(userId='me', id='msg-gone', body={'addLabelIds': ['Label_123']})
+ assert messages.modify.call_count == 2
+ import_kwargs = messages.import_.call_args[1]
+ assert import_kwargs['internalDateSource'] == 'receivedTime'
+ assert import_kwargs['neverMarkSpam'] is True
+ assert import_body(service)['labelIds'] == ['Label_123', 'INBOX']
diff --git a/tests/test_google_creds.py b/tests/test_google_creds.py
index 7907feb..4d3c8ae 100644
--- a/tests/test_google_creds.py
+++ b/tests/test_google_creds.py
@@ -2,16 +2,18 @@
import os
import subprocess
+from collections.abc import Sequence
from pathlib import Path
from unittest.mock import MagicMock, patch
import pytest
from google.auth.exceptions import RefreshError
-from korgalore import AuthenticationError, ConfigurationError, RemoteError
+from korgalore import AuthenticationError, ConfigurationError, InsufficientScopesError, RemoteError
from korgalore.google_creds import (
CommandCredentials,
OAuthFileCredentials,
+ default_scope_checker,
parse_token_command,
run_token_command,
)
@@ -254,6 +256,219 @@ class TestOAuthFileCredentials:
provider.refresh()
assert not provider.valid
+ def test_stored_token_insufficient_scopes_raises(self, tmp_path: Path) -> None:
+ """Non-interactive OAuthFileCredentials raises InsufficientScopesError when scopes missing."""
+ token = tmp_path / 'token.json'
+ token.write_text('{}')
+ mock_creds = MagicMock()
+ mock_creds.valid = True
+ mock_creds.scopes = ['https://example.invalid/scope.a']
+
+ with patch('korgalore.google_creds.Credentials') as mock_c:
+ mock_c.from_authorized_user_file.return_value = mock_creds
+ provider = OAuthFileCredentials(
+ 'test',
+ str(tmp_path / 'creds.json'),
+ token,
+ scopes=TEST_SCOPES,
+ interactive=False,
+ )
+ with pytest.raises(InsufficientScopesError):
+ provider.refresh()
+
+ def test_default_scope_checker_and_custom_checker(self, tmp_path: Path) -> None:
+ """Default checker validates normalized subsets and custom checkers override it."""
+ assert default_scope_checker(
+ ['https://example.invalid/scope.a/', 'https://example.invalid/scope.b'], TEST_SCOPES
+ )
+ assert default_scope_checker(None, TEST_SCOPES)
+ assert not default_scope_checker(['https://example.invalid/scope.a'], TEST_SCOPES)
+
+ token = tmp_path / 'token.json'
+ token.write_text('{}')
+ mock_creds = MagicMock()
+ mock_creds.valid = True
+ mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+ called: list[tuple[object, list[str]]] = []
+
+ def custom_checker(granted: object, required: Sequence[str]) -> bool:
+ called.append((granted, list(required)))
+ return True
+
+ with patch('korgalore.google_creds.Credentials') as mock_c:
+ mock_c.from_authorized_user_file.return_value = mock_creds
+ provider = OAuthFileCredentials(
+ 'test',
+ str(tmp_path / 'creds.json'),
+ token,
+ scopes=TEST_SCOPES,
+ interactive=False,
+ scope_checker=custom_checker,
+ )
+ provider.refresh()
+ assert provider.valid
+
+ assert called == [
+ (['https://example.invalid/scope.a'], TEST_SCOPES),
+ (['https://example.invalid/scope.a'], TEST_SCOPES),
+ ]
+
+ def test_oauth_file_credentials_interactive_property(self, tmp_path: Path) -> None:
+ """interactive property exposes configured interactivity."""
+ p_yes = OAuthFileCredentials(
+ 'test', str(tmp_path / 'c.json'), str(tmp_path / 't.json'), scopes=TEST_SCOPES, interactive=True
+ )
+ assert p_yes.interactive is True
+ p_no = OAuthFileCredentials(
+ 'test', str(tmp_path / 'c.json'), str(tmp_path / 't.json'), scopes=TEST_SCOPES, interactive=False
+ )
+ assert p_no.interactive is False
+
+ def test_refresh_interactive_lacks_scopes_reauthenticates(self, tmp_path: Path) -> None:
+ """Interactive refresh calls reauthenticate when loaded token lacks scopes."""
+ creds_file = tmp_path / 'creds.json'
+ creds_file.write_text('{}')
+ token = tmp_path / 'token.json'
+ token.write_text('{}')
+ mock_creds = MagicMock()
+ mock_creds.valid = True
+ mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+
+ with (
+ patch('korgalore.google_creds.Credentials') as mock_c,
+ patch.object(OAuthFileCredentials, 'reauthenticate') as mock_reauth,
+ ):
+ mock_c.from_authorized_user_file.return_value = mock_creds
+ provider = OAuthFileCredentials(
+ 'test',
+ str(creds_file),
+ token,
+ scopes=TEST_SCOPES,
+ interactive=True,
+ )
+ provider.refresh()
+ mock_reauth.assert_called_once()
+
+ def test_refresh_non_interactive_lacks_scopes_raises(self, tmp_path: Path) -> None:
+ """Non-interactive refresh raises InsufficientScopesError when loaded token lacks scopes."""
+ creds_file = tmp_path / 'creds.json'
+ creds_file.write_text('{}')
+ token = tmp_path / 'token.json'
+ token.write_text('{}')
+ mock_creds = MagicMock()
+ mock_creds.valid = True
+ mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+
+ with (
+ patch('korgalore.google_creds.Credentials') as mock_c,
+ patch.object(OAuthFileCredentials, 'reauthenticate') as mock_reauth,
+ ):
+ mock_c.from_authorized_user_file.return_value = mock_creds
+ provider = OAuthFileCredentials(
+ 'test',
+ str(creds_file),
+ token,
+ scopes=TEST_SCOPES,
+ interactive=False,
+ )
+ with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+ provider.refresh()
+ mock_reauth.assert_not_called()
+ assert provider.needs_auth
+
+ def test_refresh_partial_granted_scopes_raises_when_non_interactive(self, tmp_path: Path) -> None:
+ """Partial granted_scopes after token refresh raises when non-interactive."""
+ creds_file = tmp_path / 'creds.json'
+ creds_file.write_text('{}')
+ token = tmp_path / 'token.json'
+ token.write_text('{"original": true}')
+ mock_creds = MagicMock()
+ mock_creds.valid = False
+ mock_creds.refresh_token = 'rtok'
+ mock_creds.scopes = TEST_SCOPES
+ mock_creds.granted_scopes = TEST_SCOPES
+
+ def partial_refresh(req: object) -> None:
+ mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+
+ mock_creds.refresh.side_effect = partial_refresh
+
+ with patch('korgalore.google_creds.Credentials') as mock_c:
+ mock_c.from_authorized_user_file.return_value = mock_creds
+ provider = OAuthFileCredentials(
+ 'test',
+ str(creds_file),
+ token,
+ scopes=TEST_SCOPES,
+ interactive=False,
+ )
+ with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+ provider.refresh()
+ assert provider.needs_auth
+ assert token.read_text() == '{"original": true}'
+
+ def test_refresh_partial_granted_scopes_reauthenticates_when_interactive(self, tmp_path: Path) -> None:
+ """Partial granted_scopes after token refresh reauthenticates when interactive."""
+ creds_file = tmp_path / 'creds.json'
+ creds_file.write_text('{}')
+ token = tmp_path / 'token.json'
+ token.write_text('{"original": true}')
+ mock_creds = MagicMock()
+ mock_creds.valid = False
+ mock_creds.refresh_token = 'rtok'
+ mock_creds.scopes = TEST_SCOPES
+ mock_creds.granted_scopes = TEST_SCOPES
+
+ def partial_refresh(req: object) -> None:
+ mock_creds.granted_scopes = ['https://example.invalid/scope.a']
+
+ mock_creds.refresh.side_effect = partial_refresh
+
+ with (
+ patch('korgalore.google_creds.Credentials') as mock_c,
+ patch.object(OAuthFileCredentials, 'reauthenticate') as mock_reauth,
+ ):
+ mock_c.from_authorized_user_file.return_value = mock_creds
+ provider = OAuthFileCredentials(
+ 'test',
+ str(creds_file),
+ token,
+ scopes=TEST_SCOPES,
+ interactive=True,
+ )
+ provider.refresh()
+ mock_reauth.assert_called_once()
+ assert token.read_text() == '{"original": true}'
+
+ def test_reauthenticate_partial_consent_raises_without_saving(self, tmp_path: Path) -> None:
+ """Partial browser consent raises InsufficientScopesError before saving token."""
+ creds_file = tmp_path / 'creds.json'
+ creds_file.write_text('{}')
+ token = tmp_path / 'token.json'
+ token.write_text('{"old": true}')
+
+ partial_creds = MagicMock()
+ partial_creds.granted_scopes = ['https://example.invalid/scope.a']
+ mock_flow = MagicMock()
+ mock_flow.run_local_server.return_value = partial_creds
+
+ with patch(
+ 'korgalore.google_creds.InstalledAppFlow.from_client_secrets_file', return_value=mock_flow
+ ) as mock_fc:
+ provider = OAuthFileCredentials(
+ 'test',
+ str(creds_file),
+ token,
+ scopes=TEST_SCOPES,
+ interactive=True,
+ )
+ with pytest.raises(InsufficientScopesError, match='kgl auth test'):
+ provider.reauthenticate()
+ mock_fc.assert_called_once_with(str(creds_file), TEST_SCOPES)
+ assert provider.needs_auth
+ assert provider._creds is None
+ assert token.read_text() == '{"old": true}'
+
class TestOAuthFileCredentialsRefresh:
"""Tests for refresh(), which runs long after the constructor.
diff --git a/tests/test_jmap_target.py b/tests/test_jmap_target.py
index 520cf94..3bdfe69 100644
--- a/tests/test_jmap_target.py
+++ b/tests/test_jmap_target.py
@@ -392,9 +392,15 @@ class TestJmapTargetImportMessage:
mock_post.side_effect = [
upload_response(),
import_response({'notCreated': {'msg1': {'type': 'alreadyExists', 'existingId': 'existing-789'}}}),
+ json_response({'methodResponses': []}),
]
assert jmap_mailboxes.import_message(b'Test', ['inbox']) == {'id': 'existing-789'}
+ assert mock_post.call_count == 3
+ # Third call should be Email/set adding the mailbox
+ set_call = mock_post.call_args_list[2][1]['json']
+ assert set_call['methodCalls'][0][0] == 'Email/set'
+ assert set_call['methodCalls'][0][1]['update']['existing-789'] == {'mailboxIds/mb-1': True}
@pytest.mark.parametrize(
('import_result', 'message'),
@@ -495,3 +501,155 @@ class TestJmapTargetDeduplication:
assert result == {'id': 'new-email-id'}
assert mock_post.call_count == 2 # upload + import only
+
+
+class TestJmapIntraPullDedup:
+ """Tests for JmapTarget per-pull session cache."""
+
+ def test_intra_pull_dedup_skips_duplicate(self, jmap_mailboxes: JmapTarget, mock_post: MagicMock) -> None:
+ """Second delivery of same Message-ID in same pull with same folder makes 0 HTTP calls."""
+ mock_post.side_effect = [query_response([]), upload_response(), created('email-1')]
+ raw = b'From: a@b.com\r\nMessage-ID: <test@example.com>\r\n\r\nBody'
+
+ res1 = jmap_mailboxes.import_message(raw, ['inbox'])
+ assert res1 == {'id': 'email-1'}
+ assert mock_post.call_count == 3
+
+ # Second delivery of same message with same folder
+ res2 = jmap_mailboxes.import_message(raw, ['inbox'])
+ assert res2 == {'id': 'email-1', 'skipped': True}
+ assert mock_post.call_count == 3 # No additional HTTP calls
+
+ def test_intra_pull_dedup_adds_missing_mailbox(self, jmap_mailboxes: JmapTarget, mock_post: MagicMock) -> None:
+ """Second delivery of same Message-ID in same pull with new folder calls Email/set."""
+ mock_post.side_effect = [
+ query_response([]),
+ upload_response(),
+ created('email-1'),
+ json_response({'methodResponses': []}),
+ ]
+ raw = b'From: a@b.com\r\nMessage-ID: <test@example.com>\r\n\r\nBody'
+
+ jmap_mailboxes.import_message(raw, ['inbox'])
+ res2 = jmap_mailboxes.import_message(raw, ['inbox', 'archive'])
+
+ assert res2 == {'id': 'email-1', 'modified': True}
+ assert mock_post.call_count == 4
+ # Fourth call is Email/set adding mb-3 (archive)
+ set_call = mock_post.call_args_list[3][1]['json']
+ assert set_call['methodCalls'][0][0] == 'Email/set'
+ assert set_call['methodCalls'][0][1]['update']['email-1'] == {'mailboxIds/mb-3': True}
+
+ def test_cross_pull_preexisting_archived_message_skips_initial_labels(
+ self, jmap_mailboxes: JmapTarget, mock_post: MagicMock
+ ) -> None:
+ """Archived account-wide message gets only literal folders, skipping initial_labels and upload."""
+ mock_post.side_effect = [
+ query_response([]), # _check_message_exists in mb-3 (archive): not there
+ query_response(['existing-archived']), # _find_existing_message account-wide: found
+ json_response({'methodResponses': [['Email/set', {'updated': {'existing-archived': None}}, 'call-set']]}),
+ ]
+ raw = b'From: a@b.com\r\nMessage-ID: <arch@example.com>\r\n\r\nBody'
+
+ res1 = jmap_mailboxes.import_message(raw, ['archive'], initial_labels=['inbox'])
+ assert res1 == {'id': 'existing-archived', 'modified': True}
+ assert mock_post.call_count == 3
+ query_call = mock_post.call_args_list[1][1]['json']['methodCalls'][0][1]
+ assert query_call['filter'] == {'header': ['Message-ID', '<arch@example.com>']}
+ set_call = mock_post.call_args_list[2][1]['json']['methodCalls'][0][1]
+ assert set_call['update'] == {'existing-archived': {'mailboxIds/mb-3': True}}
+
+ # Same message delivered again in same pull with ['archive'] makes 0 HTTP calls
+ res2 = jmap_mailboxes.import_message(raw, ['archive'], initial_labels=['inbox'])
+ assert res2 == {'id': 'existing-archived', 'skipped': True}
+ assert mock_post.call_count == 3
+
+ def test_cross_pull_preexisting_not_found_falls_back_to_import(
+ self, jmap_mailboxes: JmapTarget, mock_post: MagicMock
+ ) -> None:
+ """If account-wide Email/set returns notFound, import_message falls back to upload+import."""
+ mock_post.side_effect = [
+ query_response([]),
+ query_response(['vanished-id']),
+ json_response(
+ {
+ 'methodResponses': [
+ ['Email/set', {'notUpdated': {'vanished-id': {'type': 'notFound'}}}, 'call-set'],
+ ]
+ }
+ ),
+ upload_response('blob-fallback'),
+ created('new-id'),
+ ]
+ raw = b'From: a@b.com\r\nMessage-ID: <vanish@example.com>\r\n\r\nBody'
+
+ res = jmap_mailboxes.import_message(raw, ['archive'], initial_labels=['inbox'])
+ assert res == {'id': 'new-id'}
+ assert mock_post.call_count == 5
+ import_call = mock_post.call_args_list[4][1]['json']['methodCalls'][0][1]
+ assert import_call['emails']['msg1']['mailboxIds'] == {'mb-3': True, 'mb-1': True}
+
+ def test_intra_pull_add_mailboxes_not_found_falls_back_to_import(
+ self, jmap_mailboxes: JmapTarget, mock_post: MagicMock
+ ) -> None:
+ """If cached intra-pull Email/set returns notFound, cache is dropped and upload+import runs."""
+ mock_post.side_effect = [
+ query_response([]),
+ upload_response('blob-1'),
+ created('email-1'),
+ json_response(
+ {'methodResponses': [['Email/set', {'notUpdated': {'email-1': {'type': 'notFound'}}}, 'call-set']]}
+ ),
+ query_response([]),
+ upload_response('blob-2'),
+ created('email-2'),
+ ]
+ raw = b'From: a@b.com\r\nMessage-ID: <gone@example.com>\r\n\r\nBody'
+
+ jmap_mailboxes.import_message(raw, ['inbox'])
+ res2 = jmap_mailboxes.import_message(raw, ['archive'])
+ assert res2 == {'id': 'email-2'}
+ assert jmap_mailboxes._imported_msgids['gone@example.com'][0] == 'email-2'
+
+ @pytest.mark.parametrize(
+ 'response_or_exc',
+ [
+ requests.RequestException('boom'),
+ json_response({'methodResponses': [['error', {'type': 'serverFail'}, 'call-set']]}),
+ json_response(
+ {'methodResponses': [['Email/set', {'notUpdated': {'e1': {'type': 'forbidden'}}}, 'call-set']]}
+ ),
+ ],
+ ids=['http-error', 'jmap-error', 'not-updated'],
+ )
+ def test_add_mailboxes_errors_raise_remote_error(
+ self, jmap_mailboxes: JmapTarget, mock_post: MagicMock, response_or_exc: Any
+ ) -> None:
+ """_add_mailboxes raises RemoteError on transport, JMAP error, or non-notFound failures."""
+ if isinstance(response_or_exc, Exception):
+ mock_post.side_effect = response_or_exc
+ else:
+ mock_post.return_value = response_or_exc
+
+ with pytest.raises(RemoteError):
+ jmap_mailboxes._add_mailboxes('e1', ['mb-1'])
+
+ @pytest.mark.parametrize(
+ 'response_or_exc',
+ [
+ requests.RequestException('boom'),
+ json_response({'methodResponses': [['error', {'type': 'serverFail'}, 'call-0']]}),
+ ],
+ ids=['http-error', 'jmap-error'],
+ )
+ def test_find_existing_message_errors_raise_remote_error(
+ self, jmap_mailboxes: JmapTarget, mock_post: MagicMock, response_or_exc: Any
+ ) -> None:
+ """_find_existing_message fails closed with RemoteError on HTTP or JMAP error."""
+ if isinstance(response_or_exc, Exception):
+ mock_post.side_effect = response_or_exc
+ else:
+ mock_post.return_value = response_or_exc
+
+ with pytest.raises(RemoteError):
+ jmap_mailboxes._find_existing_message('<msg@example.com>')
diff --git a/tests/test_pull.py b/tests/test_pull.py
index ef11859..910eb1e 100644
--- a/tests/test_pull.py
+++ b/tests/test_pull.py
@@ -8,6 +8,7 @@ exits with status 3 at the end when any feed failed to update. Delivery
failures don't count.
"""
+import logging
from collections.abc import Iterator
from datetime import UTC, datetime
from pathlib import Path
@@ -625,3 +626,32 @@ class TestRetryNoopDoesNotRewindPointer:
assert result == SKIPPED_NOOP_COMMIT
feed.mark_successful_delivery.assert_called_once_with('test-delivery', 0, 'abc123', was_failing=True)
+
+
+class TestDeliverCommitDebugLogging:
+ """Tests for deliver_commit DEBUG level logging."""
+
+ def test_deliver_commit_logs_labels(self, caplog: pytest.LogCaptureFixture) -> None:
+ """deliver_commit logs subject and labels when DEBUG is enabled."""
+ feed = MagicMock()
+ feed.is_noop_commit.return_value = False
+ feed.get_message_at_commit.return_value = b'Subject: Test Subject\nMessage-ID: <m1@example.com>\n\nBody'
+ target = MagicMock()
+
+ with caplog.at_level(logging.DEBUG, logger='korgalore'):
+ deliver_commit('test-delivery', target, feed, 0, 'abc123', ['inbox', 'review'])
+
+ assert ' -> Test Subject (labels: inbox, review)' in caplog.text
+
+ def test_deliver_commit_logs_without_labels_when_empty(self, caplog: pytest.LogCaptureFixture) -> None:
+ """deliver_commit logs only subject when no labels are specified."""
+ feed = MagicMock()
+ feed.is_noop_commit.return_value = False
+ feed.get_message_at_commit.return_value = b'Subject: Test Subject\nMessage-ID: <m1@example.com>\n\nBody'
+ target = MagicMock()
+
+ with caplog.at_level(logging.DEBUG, logger='korgalore'):
+ deliver_commit('test-delivery', target, feed, 0, 'abc123', [])
+
+ assert ' -> Test Subject' in caplog.text
+ assert 'labels:' not in caplog.text
--
2.56.1.987.g2ec0ab4260-goog
^ permalink raw reply related [flat|nested] 5+ messages in thread* [PATCH kgl 4/4] Add conditional initial-arrival delivery rules
2026-12-05 6:56 [PATCH kgl 0/4] Add conditional initial-arrival delivery rules Dmitry Torokhov
` (2 preceding siblings ...)
2026-12-05 6:56 ` [PATCH kgl 3/4] Add initial_labels, intra-pull dedup cache, and Gmail scope upgrades Dmitry Torokhov
@ 2026-12-05 6:56 ` Dmitry Torokhov
3 siblings, 0 replies; 5+ messages in thread
From: Dmitry Torokhov @ 2026-12-05 6:56 UTC (permalink / raw)
To: Kernel.org Tools; +Cc: Konstantin Ryabitsev
Applying labels such as INBOX unconditionally causes delayed list
mirrors or cross-posted copies to bring already archived threads back
into the inbox on stateful targets.
Add rule parsing and evaluation for target and delivery configurations,
matching message headers against address, subject, and arbitrary header
criteria. When rules match, pass their labels as initial labels so that
stateful targets like Gmail and JMAP apply them only when a message
newly arrives in the mailbox.
Restrict delivery rules to Gmail and JMAP destinations, rejecting rules
on other target types or on digest deliveries at configuration time.
Reject empty parsed label lists and % strftime templates during
thread-tracking --labels validation, and automatically require modify
permissions on Gmail targets when rules are active.
Signed-off-by: Dmitry Torokhov <dmitry.torokhov@gmail.com>
---
docs/configuration.rst | 82 ++++++++-
korgalore-example.toml | 5 +
man/korgalore.toml.5 | 31 +++-
src/korgalore/cli.py | 144 +++++++++++++++-
src/korgalore/rules.py | 312 ++++++++++++++++++++++++++++++++++
tests/test_cli_deliveries.py | 173 ++++++++++++++++++-
tests/test_gui.py | 37 ++++
tests/test_pull.py | 119 +++++++++++++
tests/test_rules.py | 222 ++++++++++++++++++++++++
tests/test_tracked_thread_delivery.py | 49 ++++++
10 files changed, 1163 insertions(+), 11 deletions(-)
diff --git a/docs/configuration.rst b/docs/configuration.rst
index 74946a9..7fd086d 100644
--- a/docs/configuration.rst
+++ b/docs/configuration.rst
@@ -437,11 +437,15 @@ Gmail Target Parameters
``token``. It is split like a shell command line, and ``$VARS`` and a
leading ``~`` are expanded, but no shell runs it. 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``).
+ and ``https://www.googleapis.com/auth/gmail.insert``, plus
+ ``https://www.googleapis.com/auth/gmail.modify`` when
+ `Conditional Delivery Rules`_ are configured).
* ``message_date``: (Optional) ``'date'``, ``'received'`` or ``'import'``
(default: ``'date'``). See `Message Dates`_
* ``never_mark_spam``: (Optional) Set to ``true`` to stop Gmail from putting
imported messages in Spam (default: ``false``).
+* ``rules``: (Optional) Conditional initial-arrival rules
+ (``[[targets.<name>.rules]]``). See `Conditional Delivery Rules`_
Maildir Target Parameters
~~~~~~~~~~~~~~~~~~~~~~~~~~
@@ -515,6 +519,8 @@ JMAP Target Parameters
* ``timeout``: (Optional) Request timeout in seconds (default: ``60``)
* ``message_date``: (Optional) ``'date'``, ``'received'`` or ``'import'``
(default: ``'date'``). See `Message Dates`_
+* ``rules``: (Optional) Conditional initial-arrival rules
+ (``[[targets.<name>.rules]]``). See `Conditional Delivery Rules`_
.. important::
Either ``token`` or ``token_file`` must be provided.
@@ -760,6 +766,80 @@ Example with date-based archiving (Maildir only):
target = 'archive'
subfolder = '%Y/%m' # Results in ~/Mail/Archive/2026/01
+Conditional Delivery Rules
+~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Targets and message-mode deliveries can define ``[[targets.<name>.rules]]``
+and ``[[deliveries.<name>.rules]]`` tables to attach extra labels (such as
+``'INBOX'``) **only on initial arrival** of a message:
+
+.. code-block:: toml
+
+ [[targets.personal.rules]]
+ recipient = ['alice@example.com', '@example-team.org']
+ not_from = 'noreply@bots.example.org'
+ labels = ['INBOX']
+
+ [deliveries.lkml]
+ feed = 'lkml'
+ target = 'personal'
+ labels = ['Lists/LKML', 'UNREAD']
+
+ [[deliveries.lkml.rules]]
+ subject = '\[PATCH'
+ not_subject = '\[RFC'
+ header = { List-Id = '<linux-kernel\.vger\.kernel\.org>' }
+ labels = ['Inbox/Patches']
+
+On stateful targets (Gmail and JMAP), rule labels are applied only when the
+message's ``Message-ID`` is not already present in the mailbox. If a delayed
+copy or cross-posted mirror arrives later, korgalore adds only any missing
+literal ``labels`` and does not re-apply rule labels, so messages you already
+archived or read stay archived. Using rules with a Gmail target requires the
+``gmail.modify`` OAuth scope (run ``kgl auth <target>`` to upgrade, or ensure
+tokens returned by ``token_command`` include ``gmail.modify``). Rules are
+supported on Gmail and JMAP targets; defining rules on IMAP, Maildir, pipe, or
+dummy targets raises a configuration error. Rules are not supported on digest
+deliveries or ``kgl yank``.
+
+For Gmail triage, two common patterns work well:
+
+* **Unread feed folders** (recommended for tracking mailing lists): keep
+ ``labels = ['Lists/<name>', 'UNREAD']`` on the delivery and use rule
+ ``labels = ['INBOX']`` so all matching mail promotes to your inbox while other
+ list messages stay unread in their list folders.
+* **Quiet read feed folders**: keep ``labels = ['Lists/<name>']`` without
+ ``'UNREAD'`` on the delivery and set ``labels = ['INBOX', 'UNREAD']`` in the
+ rule so only rule-matching messages arrive unread in your inbox.
+
+Keep ``'UNREAD'`` consistent across cross-posted feeds targeting the same Gmail
+account. Korgalore preserves ``'UNREAD'`` across feeds within a single
+``kgl pull`` run, and never re-adds ``'UNREAD'`` when updating labels on an
+existing message; however, across separate pulls, Gmail's duplicate import
+clears ``'UNREAD'`` if another feed omits ``'UNREAD'`` and imports first.
+
+Rule fields within a rule combine with logical ``AND`` (a rule with only
+``labels`` and no matchers matches every message), while items in a list matcher
+combine with ``OR``. If multiple rules match, their ``labels`` are combined in
+order.
+
+Rule keys:
+
+* ``labels`` (required): Non-empty list of labels/folders to apply on initial
+ arrival (``%`` strftime patterns are not allowed)
+* ``recipient``, ``to``, ``cc``, ``from``: Case-insensitive exact email address
+ (``user@example.com``) or ``@domain`` domain suffix matched against parsed
+ addresses in ``To``/``Cc``/``Resent-To``/``Resent-Cc`` (for ``recipient``),
+ ``To``/``Resent-To`` (for ``to``), ``Cc``/``Resent-Cc`` (for ``cc``), or
+ ``From`` (for ``from``)
+* ``not_recipient``, ``not_from``: Negative versions of ``recipient`` and
+ ``from``; the rule matches only if none of the corresponding addresses match
+* ``subject``, ``not_subject``: Case-insensitive regular expression (string or
+ non-empty list of strings) matched against the decoded ``Subject`` header
+* ``header``: Table mapping header names to a case-insensitive regular
+ expression or non-empty list of regular expressions, matched against all
+ instances of each named header
+
Digest Deliveries
~~~~~~~~~~~~~~~~~
diff --git a/korgalore-example.toml b/korgalore-example.toml
index b639217..bd03410 100644
--- a/korgalore-example.toml
+++ b/korgalore-example.toml
@@ -8,6 +8,11 @@ credentials = '/path/to/personal-credentials.json'
# Prevent Gmail from marking imported messages as spam (default: false):
# never_mark_spam = true
+# Optional: conditional initial-arrival rules (applied only if Message-ID is not yet in mailbox)
+# [[targets.personal.rules]]
+# recipient = ['user@example.com', '@example.com']
+# labels = ['INBOX']
+
[targets.work]
type = 'gmail'
credentials = '/path/to/work-credentials.json'
diff --git a/man/korgalore.toml.5 b/man/korgalore.toml.5
index 3f3236e..1b7df9e 100644
--- a/man/korgalore.toml.5
+++ b/man/korgalore.toml.5
@@ -43,7 +43,9 @@ stdout. Mutually exclusive with both \fBcredentials\fR and \fBtoken\fR.
It is split like a shell command line, and \fI$VARS\fR and a leading
\fI~\fR are expanded, but no shell runs it. 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).
+\fIhttps://www.googleapis.com/auth/gmail.insert\fR, plus
+\fIhttps://www.googleapis.com/auth/gmail.modify\fR when \fBrules\fR are
+configured).
.TP
.B message_date
(Optional) The date that Gmail keeps for each message. \fI'date'\fR and
@@ -55,6 +57,10 @@ Default: \fI'date'\fR.
.B never_mark_spam
(Optional) Set to \fItrue\fR to stop Gmail from putting imported messages
in Spam. Default: \fIfalse\fR.
+.TP
+.B rules
+(Optional) Conditional initial-arrival rules (\fB[[targets.<name>.rules]]\fR).
+See \fBrules\fR under \fB[deliveries.<name>]\fR.
.RE
.PP
.B Maildir Targets
@@ -144,6 +150,10 @@ must be provided.
.B message_date
(Optional) The date that the server keeps for each message. See
\fBMESSAGE DATES\fR. Default: \fI'date'\fR.
+.TP
+.B rules
+(Optional) Conditional initial-arrival rules (\fB[[targets.<name>.rules]]\fR).
+See \fBrules\fR under \fB[deliveries.<name>]\fR.
.RE
.PP
.B Pipe Targets
@@ -199,6 +209,25 @@ and refreshed before each GUI sync.
Ignored for Gmail, JMAP, and pipe targets.
.RE
.TP
+.B rules
+(Optional, target or message delivery) An array of rule tables
+(\fB[[targets.<name>.rules]]\fR or \fB[[deliveries.<name>.rules]]\fR)
+whose \fBlabels\fR are applied only on initial arrival of a Message-ID
+in stateful targets (Gmail and JMAP), preventing delayed copies or
+cross-posts from resurfacing already archived messages. Requires
+\fBgmail.modify\fR on Gmail targets (including tokens issued by
+\fBtoken_command\fR) and is not supported with
+\fImode = 'digest'\fR. Supported Gmail setups include unread feed folders
+(\fIlabels = ['Lists/Name', 'UNREAD']\fR with rule \fIlabels = ['INBOX']\fR)
+or quiet feed folders (\fIlabels = ['Lists/Name']\fR with rule
+\fIlabels = ['INBOX', 'UNREAD']\fR); keep \fIUNREAD\fR consistent across
+cross-posted feeds targeting the same Gmail account. Supported matchers
+(combined with AND across fields, OR within list values) are
+\fBrecipient\fR, \fBto\fR, \fBcc\fR, \fBfrom\fR, \fBnot_recipient\fR,
+\fBnot_from\fR (case-insensitive exact address or \fI@domain\fR),
+\fBsubject\fR, \fBnot_subject\fR (case-insensitive regex),
+and \fBheader\fR (table mapping header name to regex or list of regexes).
+.TP
.B mode
(Optional) \fImessage\fR (the default) delivers every message.
\fIdigest\fR sends one summary email per period instead, listing the
diff --git a/src/korgalore/cli.py b/src/korgalore/cli.py
index 1b048b5..a94e777 100644
--- a/src/korgalore/cli.py
+++ b/src/korgalore/cli.py
@@ -71,6 +71,7 @@ from korgalore.maintainers import (
)
from korgalore.message import DEFAULT_MESSAGE_DATE
from korgalore.pipe_target import PipeTarget
+from korgalore.rules import DeliveryRule, evaluate_rules, parse_rules
from korgalore.summarizer import (
Summarizer,
SummaryCache,
@@ -260,6 +261,85 @@ def resolve_target_name(target: str | None, targets: dict[str, Any]) -> str:
return default
+def gmail_target_requires_modify(config: Mapping[str, Any], identifier: str) -> bool:
+ """Return whether a Gmail target requires the ``gmail.modify`` OAuth scope.
+
+ Targets configured with ``rules`` (either on the target itself or on any
+ message-mode delivery pointing at it) need ``gmail.modify`` so they can search
+ the account for pre-existing copies and add literal labels without
+ re-applying ``initial_labels``.
+
+ Args:
+ config: Parsed korgalore configuration mapping.
+ identifier: Target name to inspect.
+
+ Returns:
+ True if the target or any non-digest delivery targeting it defines rules.
+ """
+ target_cfg = config.get('targets', {}).get(identifier)
+ if isinstance(target_cfg, Mapping) and target_cfg.get('rules'):
+ return True
+ deliveries = config.get('deliveries', {})
+ if isinstance(deliveries, Mapping):
+ for details in deliveries.values():
+ if not isinstance(details, Mapping):
+ continue
+ if details.get('target') != identifier:
+ continue
+ if details.get('mode', 'message') == 'digest':
+ continue
+ if details.get('rules'):
+ return True
+ return False
+
+
+def parse_target_rules(targets_cfg: Mapping[str, Any]) -> dict[str, list[DeliveryRule]]:
+ """Validate and parse ``[[targets.<name>.rules]]`` entries for all targets.
+
+ Args:
+ targets_cfg: The ``[targets]`` configuration mapping.
+
+ Returns:
+ Mapping of target name to compiled ``DeliveryRule`` instances.
+
+ Raises:
+ ConfigurationError: If rules are configured on an unsupported target type
+ or fail schema/pattern validation.
+ """
+ target_rules: dict[str, list[DeliveryRule]] = {}
+ for target_id, target_cfg in targets_cfg.items():
+ if not isinstance(target_cfg, Mapping):
+ continue
+ rules_cfg = target_cfg.get('rules')
+ if rules_cfg:
+ target_type = target_cfg.get('type')
+ if target_type not in ('gmail', 'jmap'):
+ raise ConfigurationError(
+ f"Target '{target_id}': rules are only supported on 'gmail' and 'jmap' targets "
+ f'(got {target_type!r})'
+ )
+ target_rules[target_id] = parse_rules(rules_cfg, context=f"target '{target_id}'")
+ return target_rules
+
+
+def get_rules_for_delivery(ctx: click.Context, delivery_name: str, target_id: str) -> list[DeliveryRule]:
+ """Return combined target and delivery rules for a delivery.
+
+ Args:
+ ctx: Click command context holding parsed rule mappings in ``ctx.obj``.
+ delivery_name: Delivery or tracked-thread name.
+ target_id: Identifier of the destination target.
+
+ Returns:
+ Combined list of target-level and delivery-level ``DeliveryRule`` objects.
+ """
+ target_rules = ctx.obj.get('target_rules', {}).get(target_id, ())
+ delivery_rules = ctx.obj.get('delivery_rules', {}).get(delivery_name, ())
+ if not target_rules and not delivery_rules:
+ return []
+ return [*target_rules, *delivery_rules]
+
+
def get_target(ctx: click.Context, identifier: str) -> Any:
"""Get or create a target service instance by identifier."""
if identifier in ctx.obj['targets']:
@@ -284,6 +364,7 @@ def get_target(ctx: click.Context, identifier: str) -> Any:
identifier=identifier,
details=details,
interactive=interactive,
+ requires_modify=gmail_target_requires_modify(config, identifier),
)
elif target_type == 'maildir':
service = get_maildir_target(
@@ -701,6 +782,7 @@ def deliver_commit(
was_failing: bool = False,
bozofilter: set[str] | None = None,
subfolder: str | None = None,
+ rules: Sequence[DeliveryRule] | None = None,
) -> str | None:
"""Deliver a single message to the target.
@@ -714,6 +796,7 @@ def deliver_commit(
was_failing: True if this is a retry of a previously failed delivery.
bozofilter: Optional set of addresses to skip (from bozofilter).
subfolder: Optional subfolder for IMAP/Maildir targets.
+ rules: Optional delivery and target rules to evaluate for initial arrival.
Returns:
The Message-ID of the delivered message on success, None on failure or skip.
@@ -744,10 +827,15 @@ def deliver_commit(
)
return SKIPPED_BOZOFILTER
+ initial_labels: list[str] | None = None
+ if rules:
+ initial_labels = evaluate_rules(rules, msg) or None
+
+ all_labels: list[str] = list(dict.fromkeys([*labels, *(initial_labels or [])]))
if logger.isEnabledFor(logging.DEBUG):
subject = msg_get_subject(msg) or '(no subject)'
- if labels:
- logger.debug(' -> %s (labels: %s)', subject, ', '.join(labels))
+ if all_labels:
+ logger.debug(' -> %s (labels: %s)', subject, ', '.join(all_labels))
else:
logger.debug(' -> %s', subject)
target.import_message(
@@ -756,6 +844,7 @@ def deliver_commit(
feed_name=format_key_for_display(feed.feed_key),
delivery_name=delivery_name,
subfolder=subfolder,
+ initial_labels=initial_labels,
)
feed.mark_successful_delivery(delivery_name, epoch, commit, message=raw_message, was_failing=was_failing)
return msgid
@@ -1640,10 +1729,19 @@ def map_deliveries(ctx: click.Context, deliveries: dict[str, Any]) -> None:
summarizers: dict[str, Summarizer] = {}
summarizer_cfg: dict[str, Any] = ctx.obj.get('config', {}).get('summarizers', {})
logger.debug('Mapping deliveries to their feeds and targets')
+
+ # Parse and validate target rules
+ targets_cfg = ctx.obj.get('config', {}).get('targets', {})
+ target_rules = parse_target_rules(targets_cfg)
+ delivery_rules: dict[str, list[DeliveryRule]] = {}
+
# Pre-map deliveries to their feeds and targets for later use.
for delivery_name, details in deliveries.items():
mode = details.get('mode', 'message')
+ rules_cfg = details.get('rules')
if mode == 'digest':
+ if rules_cfg:
+ raise ConfigurationError(f"Delivery '{delivery_name}': rules are not supported on digest deliveries")
schedules[delivery_name] = DigestSchedule.from_config(delivery_name, details)
elif mode == 'message':
digest_keys = [key for key in DIGEST_KEYS if key in details]
@@ -1653,6 +1751,22 @@ def map_deliveries(ctx: click.Context, deliveries: dict[str, Any]) -> None:
)
else:
raise ConfigurationError(f"Delivery '{delivery_name}': mode must be 'message' or 'digest' (got {mode!r})")
+
+ # Map target
+ target_name = details.get('target', '')
+ if not target_name:
+ logger.critical('No target specified for delivery: %s', delivery_name)
+ raise ConfigurationError(f'No target specified for delivery: {delivery_name}')
+
+ if rules_cfg:
+ target_type = targets_cfg.get(target_name, {}).get('type')
+ if target_type not in ('gmail', 'jmap'):
+ raise ConfigurationError(
+ f"Delivery '{delivery_name}': rules are only supported on deliveries to 'gmail' and 'jmap' "
+ f"targets (target '{target_name}' is type {target_type!r})"
+ )
+ delivery_rules[delivery_name] = parse_rules(rules_cfg, context=f"delivery '{delivery_name}'")
+
# Map feed
feed = get_feed_for_delivery(details, ctx)
sname = schedules[delivery_name].summarizer if delivery_name in schedules else None
@@ -1671,11 +1785,7 @@ def map_deliveries(ctx: click.Context, deliveries: dict[str, Any]) -> None:
'and lei feeds can hold private mail. Set allow_private_feeds = true in '
f'[summarizers.{sname}] if that is fine.'
)
- # Map target
- target_name = details.get('target', '')
- if not target_name:
- logger.critical('No target specified for delivery: %s', delivery_name)
- raise ConfigurationError(f'No target specified for delivery: {delivery_name}')
+
target = get_target(ctx, target_name)
# Extract and validate subfolder
subfolder = details.get('subfolder')
@@ -1720,6 +1830,8 @@ def map_deliveries(ctx: click.Context, deliveries: dict[str, Any]) -> None:
ctx.obj['subfolder_templates'] = templates
ctx.obj['digest_schedules'] = schedules
ctx.obj['summarizers'] = summarizers
+ ctx.obj['target_rules'] = target_rules
+ ctx.obj['delivery_rules'] = delivery_rules
if schedules:
ctx.obj['digest_worker'] = get_digest_worker_mode(ctx.obj.get('config', {}))
@@ -1946,6 +2058,7 @@ def retry_all_failed_deliveries(
target_id = target.identifier
if target_id in failed_targets:
continue
+ rules = get_rules_for_delivery(ctx, delivery_name, target_id)
with record_target_failure(failed_targets, target_id, 'retrying delivery'):
deliver_commit(
delivery_name,
@@ -1957,6 +2070,7 @@ def retry_all_failed_deliveries(
was_failing=True,
bozofilter=bozo_set,
subfolder=subfolder,
+ rules=rules,
)
@@ -2330,6 +2444,7 @@ def run_locked_pull(
if consecutive_failures >= 5:
logger.error('Aborting deliveries to target "%s" due to repeated failures.', target_name)
break
+ rules = get_rules_for_delivery(ctx, dname, target_name)
msgid: str | None = None
with record_target_failure(failed_targets, target_name, 'delivering'):
msgid = deliver_commit(
@@ -2342,6 +2457,7 @@ def run_locked_pull(
was_failing=False,
bozofilter=bozo_set,
subfolder=subfolder,
+ rules=rules,
)
if target_name in failed_targets:
break
@@ -2766,6 +2882,8 @@ def map_tracked_threads(ctx: click.Context) -> list[str]:
feeds = ctx.obj.get('feeds', {})
deliveries = ctx.obj.get('deliveries', {})
+ if 'target_rules' not in ctx.obj:
+ ctx.obj['target_rules'] = parse_target_rules(ctx.obj.get('config', {}).get('targets', {}))
mapped: list[str] = []
for tracked in active:
@@ -2840,12 +2958,20 @@ def track_add(ctx: click.Context, msgid_or_url: str, target: str | None, labels:
logger.info('Aborted.')
return
- # Resolve target and validate connectivity/labels before creating lei search or manifest state
+ # Resolve target and validate rules, connectivity, and labels before creating lei search or manifest state
try:
+ ctx.obj['target_rules'] = parse_target_rules(targets)
target_service = get_target(ctx, target)
if labels:
labels_list = parse_labels(labels)
+ if not labels_list:
+ logger.critical('No valid labels specified in --labels.')
+ raise click.Abort()
+ for label in labels_list:
+ if '%' in label:
+ logger.critical('strftime templates in labels are not supported (got %s)', label)
+ raise click.Abort()
else:
labels_list = target_service.DEFAULT_LABELS
@@ -2928,6 +3054,7 @@ def track_add(ctx: click.Context, msgid_or_url: str, target: str | None, labels:
logger.info('Delivering %d messages to target...', len(commits))
bozo_set = ctx.obj.get('bozofilter', set())
+ rules = get_rules_for_delivery(ctx, thread.track_id, target)
delivered = 0
for idx, commit in enumerate(commits):
try:
@@ -2940,6 +3067,7 @@ def track_add(ctx: click.Context, msgid_or_url: str, target: str | None, labels:
labels_list,
was_failing=False,
bozofilter=bozo_set,
+ rules=rules,
)
except (AuthenticationError, ConfigurationError):
# Keep unattempted commits recoverable on subsequent pulls before aborting
diff --git a/src/korgalore/rules.py b/src/korgalore/rules.py
new file mode 100644
index 0000000..a55a632
--- /dev/null
+++ b/src/korgalore/rules.py
@@ -0,0 +1,312 @@
+"""Conditional initial-arrival delivery rules matching message headers.
+
+Rules attach labels (such as ``INBOX`` or ``UNREAD``) to messages only when they
+first arrive in a stateful target (``gmail`` or ``jmap``), avoiding resurrecting
+already read, archived, or trashed threads when delayed list copies or
+cross-posts arrive later.
+
+Evaluation semantics:
+ * All configured criteria within a single rule are combined with logical AND.
+ * Multiple values within a single criterion (such as a list of patterns) are
+ combined with logical OR.
+ * Multiple matching rules contribute their labels in declaration order,
+ deduplicated into the final ``initial_labels`` list passed to the target.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Mapping, Sequence
+from dataclasses import dataclass
+from email.message import EmailMessage
+from email.utils import getaddresses
+from typing import Any
+
+from liblore.utils import clean_header
+
+from korgalore import ConfigurationError
+
+ALLOWED_RULE_KEYS = frozenset(
+ {
+ 'labels',
+ 'recipient',
+ 'to',
+ 'cc',
+ 'from',
+ 'not_recipient',
+ 'not_from',
+ 'subject',
+ 'not_subject',
+ 'header',
+ }
+)
+
+RECIPIENT_HEADERS = ('To', 'Cc', 'Resent-To', 'Resent-Cc')
+TO_HEADERS = ('To', 'Resent-To')
+CC_HEADERS = ('Cc', 'Resent-Cc')
+FROM_HEADERS = ('From',)
+
+ADDRESS_CHECKS = (
+ ('recipient', RECIPIENT_HEADERS, True),
+ ('to', TO_HEADERS, True),
+ ('cc', CC_HEADERS, True),
+ ('from_addrs', FROM_HEADERS, True),
+ ('not_recipient', RECIPIENT_HEADERS, False),
+ ('not_from', FROM_HEADERS, False),
+)
+
+
+def bad_rule(desc: str, why: str, field: str | None = None) -> ConfigurationError:
+ """Format a ConfigurationError for invalid rule configurations."""
+ if field:
+ return ConfigurationError(f"{desc}: {why} in '{field}'")
+ return ConfigurationError(f'{desc}: {why}')
+
+
+def extract_addresses(msg: EmailMessage, header_names: tuple[str, ...]) -> list[str]:
+ """Extract lowercase email addresses from the given message headers.
+
+ Args:
+ msg: Parsed email message to inspect.
+ header_names: Header field names to gather values from.
+
+ Returns:
+ Normalized lowercase ``local@domain`` addresses extracted from all
+ matching header instances.
+ """
+ values: list[str] = []
+ for name in header_names:
+ for raw_val in msg.get_all(name, ()):
+ # Unfold raw header values directly rather than passing through
+ # clean_header(), because RFC 2047 decoded display names containing
+ # unescaped quotes or angle brackets can mislead getaddresses().
+ unfolded = re.sub(r'\s*[\r\n]+\s*', ' ', str(raw_val)).strip()
+ if unfolded:
+ values.append(unfolded)
+ if not values:
+ return []
+ addrs: list[str] = []
+ for _, addr in getaddresses(values):
+ cleaned = addr.strip().lower()
+ if cleaned:
+ addrs.append(cleaned)
+ return addrs
+
+
+def address_matches(addr: str, pattern: str) -> bool:
+ """Return whether a normalized lowercase address matches an exact or @domain pattern."""
+ if pattern.startswith('@'):
+ local, sep, domain = addr.rpartition('@')
+ return bool(local and sep and domain == pattern[1:])
+ return addr == pattern
+
+
+def parse_string_or_list(value: Any, field: str, desc: str) -> list[str]:
+ """Validate and normalize a matcher value as a string or non-empty list of strings."""
+ if isinstance(value, str):
+ raw_items = [value]
+ elif isinstance(value, list):
+ if not value:
+ raise bad_rule(desc, f"'{field}' must not be empty")
+ raw_items = value
+ else:
+ raise bad_rule(desc, f"'{field}' must be a string or list of strings")
+
+ result: list[str] = []
+ for item in raw_items:
+ if not isinstance(item, str):
+ raise bad_rule(desc, f"'{field}' entries must be strings")
+ result.append(item)
+ return result
+
+
+def parse_address_patterns(value: Any, field: str, desc: str) -> tuple[str, ...]:
+ """Validate email or @domain address patterns."""
+ raw_items = parse_string_or_list(value, field, desc)
+ patterns: list[str] = []
+ for item in raw_items:
+ normalized = item.strip().lower()
+ if not normalized or any(ch.isspace() for ch in normalized):
+ raise bad_rule(desc, f'invalid address pattern {item!r}', field)
+ if normalized.startswith('@'):
+ domain = normalized[1:]
+ if not domain or '@' in domain:
+ raise bad_rule(desc, f'invalid domain pattern {item!r}', field)
+ else:
+ local, sep, domain = normalized.partition('@')
+ if not local or not sep or not domain or '@' in domain:
+ raise bad_rule(desc, f'invalid email pattern {item!r}', field)
+ patterns.append(normalized)
+ return tuple(patterns)
+
+
+def parse_regex_patterns(value: Any, field: str, desc: str) -> tuple[re.Pattern[str], ...]:
+ """Validate and compile case-insensitive regex patterns."""
+ raw_items = parse_string_or_list(value, field, desc)
+ compiled: list[re.Pattern[str]] = []
+ for item in raw_items:
+ try:
+ compiled.append(re.compile(item, re.IGNORECASE))
+ except re.error as e:
+ raise ConfigurationError(f"{desc}: invalid regex {item!r} in '{field}': {e}") from e
+ return tuple(compiled)
+
+
+def parse_rule_labels(value: Any, desc: str) -> tuple[str, ...]:
+ """Validate rule output labels."""
+ if not isinstance(value, list) or not value:
+ raise bad_rule(desc, "'labels' must be a non-empty list of non-empty strings")
+ labels: list[str] = []
+ for item in value:
+ if not isinstance(item, str) or not item.strip():
+ raise bad_rule(desc, "'labels' entries must be non-empty strings")
+ if '%' in item:
+ raise bad_rule(desc, f"'labels' must not contain strftime templates (found '{item}')")
+ labels.append(item.strip())
+ return tuple(labels)
+
+
+def parse_header_matchers(value: Any, desc: str) -> tuple[tuple[str, tuple[re.Pattern[str], ...]], ...]:
+ """Validate the [header] table mapping header names to regex patterns."""
+ if not isinstance(value, Mapping) or not value:
+ raise bad_rule(desc, "'header' must be a non-empty table mapping header names to patterns")
+ matchers: list[tuple[str, tuple[re.Pattern[str], ...]]] = []
+ for hdr_name, hdr_pats in value.items():
+ if not isinstance(hdr_name, str) or not hdr_name.strip():
+ raise bad_rule(desc, "'header' keys must be non-empty strings")
+ compiled = parse_regex_patterns(hdr_pats, f'header.{hdr_name}', desc)
+ matchers.append((hdr_name, compiled))
+ return tuple(matchers)
+
+
+@dataclass(frozen=True, slots=True)
+class DeliveryRule:
+ """Compiled rule producing ``initial_labels`` when all matchers match a message.
+
+ Attributes:
+ labels: Ordered label/folder names emitted when the rule matches.
+ recipient: Positive address/domain patterns matched against ``To``, ``Cc``,
+ ``Resent-To``, and ``Resent-Cc``.
+ to: Positive address/domain patterns matched against ``To`` and ``Resent-To``.
+ cc: Positive address/domain patterns matched against ``Cc`` and ``Resent-Cc``.
+ from_addrs: Positive address/domain patterns matched against ``From``.
+ not_recipient: Negative address/domain patterns that veto a match when
+ present in any recipient header.
+ not_from: Negative address/domain patterns that veto a match on ``From``.
+ subject: Positive case-insensitive regexes tested against decoded subjects.
+ not_subject: Negative case-insensitive regexes tested against decoded subjects.
+ header: Sequence of ``(header_name, patterns)`` pairs that must each match
+ at least one decoded header value.
+ """
+
+ labels: tuple[str, ...]
+ recipient: tuple[str, ...] = ()
+ to: tuple[str, ...] = ()
+ cc: tuple[str, ...] = ()
+ from_addrs: tuple[str, ...] = ()
+ not_recipient: tuple[str, ...] = ()
+ not_from: tuple[str, ...] = ()
+ subject: tuple[re.Pattern[str], ...] = ()
+ not_subject: tuple[re.Pattern[str], ...] = ()
+ header: tuple[tuple[str, tuple[re.Pattern[str], ...]], ...] = ()
+
+ def matches(self, msg: EmailMessage) -> bool:
+ """Evaluate whether all configured criteria satisfy the given message.
+
+ Args:
+ msg: Parsed email message to test.
+
+ Returns:
+ True if every configured matcher succeeds, or False on the first
+ mismatch.
+ """
+ for attr, headers, positive in ADDRESS_CHECKS:
+ patterns = getattr(self, attr)
+ if patterns:
+ addrs = extract_addresses(msg, headers)
+ if any(address_matches(a, p) for a in addrs for p in patterns) != positive:
+ return False
+
+ if self.subject or self.not_subject:
+ subjects = [clean_header(raw) for raw in msg.get_all('Subject', ())]
+ if self.subject and not any(pat.search(s) for s in subjects for pat in self.subject):
+ return False
+ if self.not_subject and any(pat.search(s) for s in subjects for pat in self.not_subject):
+ return False
+
+ for hdr_name, pats in self.header:
+ values = [clean_header(raw) for raw in msg.get_all(hdr_name, ())]
+ if not any(pat.search(val) for val in values for pat in pats):
+ return False
+
+ return True
+
+
+def parse_rules(rules_cfg: Any, context: str) -> list[DeliveryRule]:
+ """Parse and validate a list of rule tables from configuration.
+
+ Args:
+ rules_cfg: Raw ``rules`` configuration value from TOML, or None.
+ context: Human-readable target or delivery label for error reporting.
+
+ Returns:
+ List of compiled ``DeliveryRule`` objects in configuration order.
+
+ Raises:
+ ConfigurationError: If ``rules_cfg`` is not a list of tables or any rule
+ contains unknown keys, invalid patterns, or bad labels.
+ """
+ if rules_cfg is None:
+ return []
+ if not isinstance(rules_cfg, list):
+ raise ConfigurationError(f"Invalid 'rules' for {context}: must be a list of tables")
+
+ parsed: list[DeliveryRule] = []
+ for idx, entry in enumerate(rules_cfg, start=1):
+ rule_desc = f'Rule #{idx} for {context}'
+ if not isinstance(entry, Mapping):
+ raise bad_rule(rule_desc, 'must be a table')
+ unknown = sorted(set(entry.keys()) - ALLOWED_RULE_KEYS)
+ if unknown:
+ raise bad_rule(rule_desc, f'unknown keys: {", ".join(unknown)}')
+ if 'labels' not in entry:
+ raise bad_rule(rule_desc, "missing required 'labels' key")
+
+ kwargs: dict[str, Any] = {'labels': parse_rule_labels(entry['labels'], rule_desc)}
+ for key in ('recipient', 'to', 'cc'):
+ if key in entry:
+ kwargs[key] = parse_address_patterns(entry[key], key, rule_desc)
+ if 'from' in entry:
+ kwargs['from_addrs'] = parse_address_patterns(entry['from'], 'from', rule_desc)
+ for key in ('not_recipient', 'not_from'):
+ if key in entry:
+ kwargs[key] = parse_address_patterns(entry[key], key, rule_desc)
+ for key in ('subject', 'not_subject'):
+ if key in entry:
+ kwargs[key] = parse_regex_patterns(entry[key], key, rule_desc)
+ if 'header' in entry:
+ kwargs['header'] = parse_header_matchers(entry['header'], rule_desc)
+
+ parsed.append(DeliveryRule(**kwargs))
+ return parsed
+
+
+def evaluate_rules(rules: Sequence[DeliveryRule], msg: EmailMessage) -> list[str]:
+ """Evaluate compiled rules against a message and collect matching labels.
+
+ Args:
+ rules: Compiled rules to evaluate in order.
+ msg: Parsed email message being delivered.
+
+ Returns:
+ Ordered, deduplicated list of initial labels from all matching rules.
+ """
+ matched: list[str] = []
+ seen: set[str] = set()
+ for rule in rules:
+ if rule.matches(msg):
+ for label in rule.labels:
+ if label not in seen:
+ seen.add(label)
+ matched.append(label)
+ return matched
diff --git a/tests/test_cli_deliveries.py b/tests/test_cli_deliveries.py
index ccda983..a7c6419 100644
--- a/tests/test_cli_deliveries.py
+++ b/tests/test_cli_deliveries.py
@@ -8,9 +8,11 @@ from unittest.mock import MagicMock, patch
import click
import pytest
+from click.testing import CliRunner
from korgalore import ConfigurationError
-from korgalore.cli import map_deliveries, refresh_subfolder_templates
+from korgalore.cli import get_target, map_deliveries, refresh_subfolder_templates, track_add
+from korgalore.gmail_target import GmailTarget
from korgalore.imap_target import ImapTarget
from korgalore.maildir_target import MaildirTarget
from tests.digest_helpers import make_ctx
@@ -135,3 +137,172 @@ class TestMapDeliveriesRejections:
for message in messages:
assert message in str(exc_info.value)
+
+ def test_digest_with_rules_rejected(self, tmp_path: Path) -> None:
+ with pytest.raises(ConfigurationError, match='rules are not supported on digest deliveries'):
+ run_map(tmp_path, mode='digest', rules=[{'labels': ['INBOX']}])
+
+ @pytest.mark.parametrize('target_type', ['maildir', 'imap'])
+ def test_delivery_rules_targeting_unsupported_target_rejected(self, tmp_path: Path, target_type: str) -> None:
+ with pytest.raises(ConfigurationError, match="rules are only supported on deliveries to 'gmail' and 'jmap'"):
+ run_map(tmp_path, target=target_type, rules=[{'labels': ['INBOX']}])
+
+
+class TestRuleMapping:
+ """Tests for target and delivery rules parsed during map_deliveries."""
+
+ def test_maps_target_and_delivery_rules(self) -> None:
+ target_obj = MagicMock()
+ ctx = make_ctx(
+ {
+ 'config': {
+ 'targets': {
+ 'my-gmail': {
+ 'type': 'gmail',
+ 'credentials': 'creds.json',
+ 'rules': [{'recipient': 'me@example.com', 'labels': ['INBOX']}],
+ }
+ },
+ 'feeds': {},
+ },
+ 'targets': {'my-gmail': target_obj},
+ 'feeds': {},
+ 'deliveries': {},
+ }
+ )
+ deliveries = {
+ 'lkml': {
+ 'feed': 'https://lore.kernel.org/lkml',
+ 'target': 'my-gmail',
+ 'labels': ['Lists/LKML'],
+ 'rules': [{'subject': 'PATCH', 'labels': ['Patches']}],
+ }
+ }
+ with (
+ patch('korgalore.cli.get_feed_for_delivery', return_value=MagicMock(feed_key='lkml')),
+ patch('korgalore.cli.get_target', return_value=target_obj) as mock_gt,
+ ):
+ map_deliveries(ctx, deliveries)
+ mock_gt.assert_called_once_with(ctx, 'my-gmail')
+
+ assert len(ctx.obj['deliveries']['lkml']) == 4
+ assert len(ctx.obj['target_rules']['my-gmail']) == 1
+ assert len(ctx.obj['delivery_rules']['lkml']) == 1
+
+ def test_unsupported_target_type_with_rules_rejected(self) -> None:
+ ctx = make_ctx(
+ {
+ 'config': {
+ 'targets': {
+ 'local': {
+ 'type': 'maildir',
+ 'path': '/tmp/mail',
+ 'rules': [{'labels': ['INBOX']}],
+ }
+ },
+ 'feeds': {},
+ },
+ 'targets': {},
+ 'feeds': {},
+ 'deliveries': {},
+ }
+ )
+ deliveries = {'lkml': {'feed': 'https://lore.kernel.org/lkml', 'target': 'local'}}
+ with (
+ patch('korgalore.cli.get_feed_for_delivery', return_value=MagicMock(feed_key='lkml')),
+ pytest.raises(ConfigurationError, match="rules are only supported on 'gmail' and 'jmap' targets"),
+ ):
+ map_deliveries(ctx, deliveries)
+
+ def test_invalid_target_rule_rejected(self) -> None:
+ ctx = make_ctx(
+ {
+ 'config': {
+ 'targets': {
+ 'my-gmail': {
+ 'type': 'gmail',
+ 'credentials': 'creds.json',
+ 'rules': [{'subject': '[', 'labels': ['INBOX']}],
+ }
+ },
+ 'feeds': {},
+ },
+ 'targets': {},
+ 'feeds': {},
+ 'deliveries': {},
+ }
+ )
+ deliveries = {'lkml': {'feed': 'https://lore.kernel.org/lkml', 'target': 'my-gmail'}}
+ with (
+ patch('korgalore.cli.get_feed_for_delivery', return_value=MagicMock(feed_key='lkml')),
+ pytest.raises(ConfigurationError, match='invalid regex'),
+ ):
+ map_deliveries(ctx, deliveries)
+
+ def test_get_target_computes_requires_modify_without_deliveries(self, tmp_path: Path) -> None:
+ ctx = make_ctx(
+ {
+ 'config': {
+ 'targets': {
+ 'my-gmail': {
+ 'type': 'gmail',
+ 'credentials': 'creds.json',
+ 'rules': [{'recipient': 'me@example.com', 'labels': ['INBOX']}],
+ }
+ },
+ 'deliveries': {},
+ },
+ 'targets': {},
+ }
+ )
+ with patch('korgalore.cli.get_xdg_config_dir', return_value=tmp_path):
+ target = get_target(ctx, 'my-gmail')
+ assert isinstance(target, GmailTarget)
+ assert target.requires_modify is True
+
+ def test_track_add_validates_target_rules_and_labels_before_lei_search(self, tmp_path: Path) -> None:
+ runner = CliRunner()
+ bad_rules_obj = {
+ 'config': {
+ 'targets': {
+ 'my-gmail': {
+ 'type': 'gmail',
+ 'credentials': 'creds.json',
+ 'rules': [{'subject': '[', 'labels': ['INBOX']}],
+ }
+ }
+ },
+ 'targets': {},
+ 'data_dir': tmp_path,
+ }
+ with (
+ patch('korgalore.cli.get_xdg_config_dir', return_value=tmp_path),
+ patch('korgalore.cli.create_lei_thread_search') as mock_lei,
+ ):
+ res = runner.invoke(track_add, ['https://lore.kernel.org/r/msg@example.com'], obj=bad_rules_obj)
+ assert res.exit_code == 1
+ mock_lei.assert_not_called()
+
+ bad_labels_obj = {
+ 'config': {
+ 'targets': {
+ 'my-gmail': {
+ 'type': 'gmail',
+ 'credentials': 'creds.json',
+ }
+ }
+ },
+ 'targets': {},
+ 'data_dir': tmp_path,
+ }
+ with (
+ patch('korgalore.cli.get_xdg_config_dir', return_value=tmp_path),
+ patch('korgalore.cli.create_lei_thread_search') as mock_lei,
+ ):
+ res = runner.invoke(
+ track_add,
+ ['https://lore.kernel.org/r/msg@example.com', '-l', 'Archive/%Y'],
+ obj=bad_labels_obj,
+ )
+ assert res.exit_code == 1
+ mock_lei.assert_not_called()
diff --git a/tests/test_gui.py b/tests/test_gui.py
index 55f8472..2a917fd 100644
--- a/tests/test_gui.py
+++ b/tests/test_gui.py
@@ -25,6 +25,7 @@ from korgalore.google_creds import CommandCredentials, OAuthFileCredentials
from korgalore.gui import target_can_reauthenticate
from korgalore.imap_target import ImapTarget
from korgalore.jmap_target import JmapTarget
+from tests.digest_helpers import make_ctx
from tests.gui_helpers import make_app
if TYPE_CHECKING:
@@ -426,3 +427,39 @@ class TestTargetCanReauthenticate:
assert app.auth_needed_target is None
assert statuses == ['Syncing...', 'Auth failed: work']
assert mock_glib.idle_add.call_count == 2 # only item_sync disable/re-enable
+
+ def test_run_authenticate_uses_modify_scope_for_target_rules_without_deliveries(self, tmp_path: Path) -> None:
+ """_run_authenticate() constructs GmailTarget with requires_modify when only target rules exist."""
+ ctx = make_ctx(
+ {
+ 'config': {
+ 'targets': {
+ 'work': {
+ 'type': 'gmail',
+ 'credentials': str(tmp_path / 'creds.json'),
+ 'rules': [{'recipient': 'me@example.com', 'labels': ['INBOX']}],
+ }
+ },
+ 'deliveries': {},
+ },
+ 'targets': {},
+ 'gui_mode': True,
+ }
+ )
+ app = make_app(sync_interval=300)
+ app.ctx = ctx
+ app.auth_needed_target = 'work'
+ app.item_auth = MagicMock()
+
+ with (
+ patch('korgalore.cli.get_xdg_config_dir', return_value=tmp_path),
+ patch('korgalore.gmail_target.GmailTarget.reauthenticate') as mock_reauth,
+ patch.object(app, 'update_status'),
+ patch('korgalore.gui.GLib'),
+ ):
+ app._run_authenticate()
+
+ mock_reauth.assert_called_once()
+ target = ctx.obj['targets']['work']
+ assert isinstance(target, GmailTarget)
+ assert target.requires_modify is True
diff --git a/tests/test_pull.py b/tests/test_pull.py
index 910eb1e..328a2b9 100644
--- a/tests/test_pull.py
+++ b/tests/test_pull.py
@@ -643,6 +643,23 @@ class TestDeliverCommitDebugLogging:
assert ' -> Test Subject (labels: inbox, review)' in caplog.text
+ def test_deliver_commit_logs_initial_labels_from_rules(self, caplog: pytest.LogCaptureFixture) -> None:
+ """deliver_commit logs deduplicated combination of literal and initial labels."""
+ from korgalore.rules import parse_rules
+
+ feed = MagicMock()
+ feed.is_noop_commit.return_value = False
+ feed.get_message_at_commit.return_value = (
+ b'To: me@kernel.org\nSubject: Test Subject\nMessage-ID: <m1@example.com>\n\nBody'
+ )
+ target = MagicMock()
+ rules = parse_rules([{'recipient': 'me@kernel.org', 'labels': ['inbox', 'urgent']}], 'test')
+
+ with caplog.at_level(logging.DEBUG, logger='korgalore'):
+ deliver_commit('test-delivery', target, feed, 0, 'abc123', ['inbox', 'review'], rules=rules)
+
+ assert ' -> Test Subject (labels: inbox, review, urgent)' in caplog.text
+
def test_deliver_commit_logs_without_labels_when_empty(self, caplog: pytest.LogCaptureFixture) -> None:
"""deliver_commit logs only subject when no labels are specified."""
feed = MagicMock()
@@ -655,3 +672,105 @@ class TestDeliverCommitDebugLogging:
assert ' -> Test Subject' in caplog.text
assert 'labels:' not in caplog.text
+
+
+class TestDeliveryRulesExecution:
+ """Tests for evaluating rules and passing initial_labels during deliver_commit and pull."""
+
+ def test_deliver_commit_passes_initial_labels_when_rule_matches(self) -> None:
+ from korgalore.rules import parse_rules
+
+ feed = MagicMock()
+ feed.feed_key = 'lkml'
+ feed.is_noop_commit.return_value = False
+ feed.get_message_at_commit.return_value = (
+ b'From: alice@example.com\r\nTo: bob@kernel.org\r\nMessage-ID: <m1@example.org>\r\n\r\nBody'
+ )
+ target = MagicMock()
+ rules = parse_rules([{'recipient': 'bob@kernel.org', 'labels': ['INBOX']}], "delivery 'd'")
+
+ deliver_commit('d', target, feed, 0, 'commit1', ['Lists/LKML'], rules=rules)
+
+ assert target.import_message.call_args.kwargs['initial_labels'] == ['INBOX']
+
+ def test_deliver_commit_passes_none_when_rule_does_not_match(self) -> None:
+ from korgalore.rules import parse_rules
+
+ feed = MagicMock()
+ feed.feed_key = 'lkml'
+ feed.is_noop_commit.return_value = False
+ feed.get_message_at_commit.return_value = (
+ b'From: alice@example.com\r\nTo: list@vger.kernel.org\r\nMessage-ID: <m2@example.org>\r\n\r\nBody'
+ )
+ target = MagicMock()
+ rules = parse_rules([{'recipient': 'bob@kernel.org', 'labels': ['INBOX']}], "delivery 'd'")
+
+ deliver_commit('d', target, feed, 0, 'commit2', ['Lists/LKML'], rules=rules)
+
+ assert target.import_message.call_args.kwargs['initial_labels'] is None
+
+ def test_perform_pull_and_retry_combine_target_and_delivery_rules(self) -> None:
+ from korgalore.cli import retry_all_failed_deliveries
+ from korgalore.rules import parse_rules
+
+ feed = _make_feed('lkml')
+ feed.is_noop_commit.return_value = False
+ feed.get_message_at_commit.return_value = (
+ b'From: dev@example.org\r\n'
+ b'To: me@kernel.org\r\n'
+ b'Subject: [PATCH] Fix bug\r\n'
+ b'Message-ID: <patch@example.org>\r\n\r\nBody'
+ )
+ feed.get_failed_commits_for_delivery.return_value = []
+ feed.get_latest_commits_for_delivery.return_value = [(0, 'c1')]
+
+ tracked_feed = _make_feed('track-abc')
+ tracked_feed.is_noop_commit.return_value = False
+ tracked_feed.get_message_at_commit.return_value = (
+ b'From: dev@example.org\r\nTo: me@kernel.org\r\nMessage-ID: <reply@example.org>\r\n\r\nBody'
+ )
+ tracked_feed.get_failed_commits_for_delivery.return_value = [(0, 'retry-1')]
+ tracked_feed.get_latest_commits_for_delivery.return_value = [(0, 'c2')]
+
+ target = MagicMock()
+ target.identifier = 'personal'
+ target_rules = parse_rules([{'recipient': 'me@kernel.org', 'labels': ['INBOX']}], "target 'personal'")
+ delivery_rules = parse_rules([{'subject': 'PATCH', 'labels': ['Patches']}], "delivery 'd-lkml'")
+
+ ctx = make_ctx(
+ {
+ 'config': {'deliveries': {'d-lkml': {}, 'track-abc': {}}},
+ 'feeds': {'lkml': feed, 'track-abc': tracked_feed},
+ 'deliveries': {
+ 'd-lkml': (feed, target, ['Lists/LKML'], None),
+ 'track-abc': (tracked_feed, target, ['Tracked'], None),
+ },
+ 'target_rules': {'personal': target_rules},
+ 'delivery_rules': {'d-lkml': delivery_rules},
+ 'targets': {'personal': target},
+ 'bozofilter': set(),
+ 'hide_bar': True,
+ }
+ )
+
+ retry_all_failed_deliveries(ctx)
+ assert target.import_message.call_args.kwargs['initial_labels'] == ['INBOX']
+
+ target.import_message.reset_mock()
+ tracked_feed.get_failed_commits_for_delivery.return_value = []
+ with (
+ patch('korgalore.cli.map_deliveries'),
+ patch('korgalore.cli.map_tracked_threads'),
+ patch('korgalore.cli.lock_all_feeds'),
+ patch('korgalore.cli.unlock_all_feeds'),
+ patch('korgalore.cli.retry_all_failed_deliveries'),
+ patch('korgalore.cli.update_tracked_thread_activity'),
+ patch('korgalore.cli.close_requests_session'),
+ patch('korgalore.cli.get_tracking_manifest'),
+ ):
+ perform_pull(ctx, no_update=True, force=True, delivery_name=None)
+
+ calls = target.import_message.call_args_list
+ assert [c.kwargs['delivery_name'] for c in calls] == ['d-lkml', 'track-abc']
+ assert calls[0].kwargs['initial_labels'] == ['INBOX', 'Patches']
+ assert calls[1].kwargs['initial_labels'] == ['INBOX']
diff --git a/tests/test_rules.py b/tests/test_rules.py
new file mode 100644
index 0000000..e15981a
--- /dev/null
+++ b/tests/test_rules.py
@@ -0,0 +1,222 @@
+"""Tests for conditional initial-arrival delivery rules."""
+
+from typing import Any
+
+import pytest
+from liblore.utils import parse_message
+
+from korgalore import ConfigurationError
+from korgalore.rules import evaluate_rules, parse_rules
+
+
+def make_msg(raw: bytes) -> Any:
+ return parse_message(raw)
+
+
+class TestRuleValidation:
+ """Strict schema validation in parse_rules()."""
+
+ def test_none_returns_empty(self) -> None:
+ assert parse_rules(None, "delivery 'd'") == []
+
+ def test_zero_matchers_rule_allowed(self) -> None:
+ rules = parse_rules([{'labels': ['INBOX']}], "delivery 'd'")
+ assert len(rules) == 1
+ assert rules[0].labels == ('INBOX',)
+ assert rules[0].matches(make_msg(b'From: anyone@example.com\r\n\r\nBody'))
+
+ @pytest.mark.parametrize(
+ ('bad_rules', 'match'),
+ [
+ ('not-a-list', 'must be a list'),
+ ([123], 'must be a table'),
+ ([{'recipient': 'a@b.com'}], "missing required 'labels'"),
+ ([{'labels': []}], 'non-empty list'),
+ ([{'labels': 'INBOX'}], 'non-empty list'),
+ ([{'labels': [123]}], 'non-empty strings'),
+ ([{'labels': [' ']}], 'non-empty strings'),
+ ([{'labels': ['Archive/%Y']}], 'strftime templates'),
+ ([{'labels': ['INBOX'], 'first_only': True}], 'unknown keys: first_only'),
+ ([{'labels': ['INBOX'], 'unknown': 'val'}], 'unknown keys: unknown'),
+ ([{'labels': ['INBOX'], 'recipient': 42}], 'string or list of strings'),
+ ([{'labels': ['INBOX'], 'recipient': []}], 'must not be empty'),
+ ([{'labels': ['INBOX'], 'recipient': [123]}], 'entries must be strings'),
+ ([{'labels': ['INBOX'], 'from': 'notanemail'}], 'invalid email pattern'),
+ ([{'labels': ['INBOX'], 'from': '@'}], 'invalid domain pattern'),
+ ([{'labels': ['INBOX'], 'from': 'a@b@c.com'}], 'invalid email pattern'),
+ ([{'labels': ['INBOX'], 'to': 'has space@example.com'}], 'invalid address pattern'),
+ ([{'labels': ['INBOX'], 'subject': '['}], 'invalid regex'),
+ ([{'labels': ['INBOX'], 'not_subject': ['ok', '(']}], 'invalid regex'),
+ ([{'labels': ['INBOX'], 'subject': []}], 'must not be empty'),
+ ([{'labels': ['INBOX'], 'header': 'List-Id'}], 'non-empty table'),
+ ([{'labels': ['INBOX'], 'header': {}}], 'non-empty table'),
+ ([{'labels': ['INBOX'], 'header': {' ': 'foo'}}], 'keys must be non-empty strings'),
+ ([{'labels': ['INBOX'], 'header': {'List-Id': []}}], 'must not be empty'),
+ ([{'labels': ['INBOX'], 'header': {'List-Id': '[unclosed'}}], 'invalid regex'),
+ ],
+ ids=[
+ 'rules-not-list',
+ 'entry-not-table',
+ 'missing-labels',
+ 'empty-labels',
+ 'labels-string',
+ 'label-int',
+ 'label-whitespace',
+ 'label-strftime',
+ 'first-only-rejected',
+ 'unknown-key',
+ 'recipient-int',
+ 'recipient-empty-list',
+ 'recipient-list-int',
+ 'invalid-email-no-at',
+ 'invalid-domain-bare-at',
+ 'invalid-email-two-ats',
+ 'invalid-addr-whitespace',
+ 'invalid-subject-regex',
+ 'invalid-not-subject-regex',
+ 'empty-subject-list',
+ 'header-string',
+ 'header-empty-dict',
+ 'header-blank-key',
+ 'header-empty-patterns',
+ 'header-invalid-regex',
+ ],
+ )
+ def test_invalid_configs_rejected(self, bad_rules: Any, match: str) -> None:
+ with pytest.raises(ConfigurationError, match=match):
+ parse_rules(bad_rules, "delivery 'd'")
+
+
+class TestAddressMatching:
+ """Address matchers: recipient, to, cc, from, not_recipient, not_from."""
+
+ def test_recipient_checks_to_cc_and_resent_headers(self) -> None:
+ msg = make_msg(
+ b'From: Sender <sender@example.org>\r\n'
+ b'To: Alice <Alice@Example.com>\r\n'
+ b'Cc: Bob <bob@kernel.org>\r\n'
+ b'Resent-To: charlie@test.net\r\n'
+ b'Resent-Cc: dave@other.net\r\n\r\nBody'
+ )
+ assert evaluate_rules(parse_rules([{'recipient': 'alice@example.com', 'labels': ['A']}], 'test'), msg) == ['A']
+ assert evaluate_rules(parse_rules([{'recipient': 'bob@kernel.org', 'labels': ['B']}], 'test'), msg) == ['B']
+ assert evaluate_rules(parse_rules([{'recipient': 'charlie@test.net', 'labels': ['C']}], 'test'), msg) == ['C']
+ assert evaluate_rules(parse_rules([{'recipient': 'dave@other.net', 'labels': ['D']}], 'test'), msg) == ['D']
+
+ def test_to_and_cc_do_not_cross_match(self) -> None:
+ msg = make_msg(b'From: a@example.com\r\nTo: to-user@example.com\r\nCc: cc-user@example.com\r\n\r\nBody')
+ to_rule = parse_rules([{'to': 'cc-user@example.com', 'labels': ['X']}], 'test')
+ cc_rule = parse_rules([{'cc': 'to-user@example.com', 'labels': ['Y']}], 'test')
+ assert evaluate_rules(to_rule, msg) == []
+ assert evaluate_rules(cc_rule, msg) == []
+
+ to_ok = parse_rules([{'to': 'to-user@example.com', 'labels': ['X']}], 'test')
+ cc_ok = parse_rules([{'cc': 'cc-user@example.com', 'labels': ['Y']}], 'test')
+ assert evaluate_rules(to_ok, msg) == ['X']
+ assert evaluate_rules(cc_ok, msg) == ['Y']
+
+ def test_domain_suffix_does_not_falsely_match_superstring_domain(self) -> None:
+ rule = parse_rules([{'recipient': '@domain.com', 'labels': ['INBOX']}], 'test')
+ exact = make_msg(b'To: user@DOMAIN.COM\r\n\r\nBody')
+ lookalike = make_msg(b'To: user@notdomain.com\r\n\r\nBody')
+ subdomain = make_msg(b'To: user@sub.domain.com\r\n\r\nBody')
+
+ assert evaluate_rules(rule, exact) == ['INBOX']
+ assert evaluate_rules(rule, lookalike) == []
+ assert evaluate_rules(rule, subdomain) == []
+
+ def test_folded_and_encoded_display_name_addresses(self) -> None:
+ raw = (
+ b'From: =?utf-8?q?Doe,_John?= <john@example.com>\r\n'
+ b'To: linux-input@vger.kernel.org,\r\n'
+ b' "Maintainer, Jane" <JANE@KERNEL.ORG>\r\n\r\nBody'
+ )
+ msg = make_msg(raw)
+ rule = parse_rules([{'from': 'john@example.com', 'to': 'jane@kernel.org', 'labels': ['INBOX']}], 'test')
+ assert evaluate_rules(rule, msg) == ['INBOX']
+
+ def test_rfc2047_quoted_display_name_with_embedded_addr_does_not_spoof(self) -> None:
+ raw = b'To: =?utf-8?q?Quoted_=22Name=22_=3Cbob=40kernel.org=3E=2C_ci?= <real@example.com>\r\n\r\nBody'
+ msg = make_msg(raw)
+ spoofed = parse_rules([{'recipient': 'bob@kernel.org', 'labels': ['INBOX']}], 'test')
+ real = parse_rules([{'recipient': 'real@example.com', 'labels': ['INBOX']}], 'test')
+
+ assert evaluate_rules(spoofed, msg) == []
+ assert evaluate_rules(real, msg) == ['INBOX']
+
+ def test_negative_address_matchers(self) -> None:
+ rules = parse_rules(
+ [
+ {
+ 'recipient': '@example.com',
+ 'not_recipient': ['bot@example.com', '@noreply.com'],
+ 'not_from': '@bots.org',
+ 'labels': ['INBOX'],
+ }
+ ],
+ 'test',
+ )
+ ok = make_msg(b'From: human@kernel.org\r\nTo: alice@example.com, bob@example.org\r\n\r\nBody')
+ blocked_rcpt = make_msg(b'From: human@kernel.org\r\nTo: alice@example.com, bot@example.com\r\n\r\nBody')
+ blocked_from = make_msg(b'From: ci@bots.org\r\nTo: alice@example.com\r\n\r\nBody')
+
+ assert evaluate_rules(rules, ok) == ['INBOX']
+ assert evaluate_rules(rules, blocked_rcpt) == []
+ assert evaluate_rules(rules, blocked_from) == []
+
+
+class TestSubjectAndHeaderMatching:
+ """Subject regexes, header regexes, logical AND/OR combinations."""
+
+ def test_subject_and_not_subject_with_encoded_and_folded_headers(self) -> None:
+ rules = parse_rules(
+ [
+ {
+ 'subject': [r'\[PATCH', r'\[GIT PULL\]'],
+ 'not_subject': [r'\[RFC', r'\bWIP\b'],
+ 'labels': ['Review'],
+ }
+ ],
+ 'test',
+ )
+ match = make_msg(b'Subject: =?utf-8?q?=5BPATCH_v2=5D?= input:\r\n fix <bug@kernel.org>\r\n\r\nBody')
+ excluded = make_msg(b'Subject: [RFC PATCH] input: test\r\n\r\nBody')
+ no_subj = make_msg(b'From: a@b.com\r\n\r\nBody')
+
+ assert evaluate_rules(rules, match) == ['Review']
+ assert evaluate_rules(rules, excluded) == []
+ assert evaluate_rules(rules, no_subj) == []
+
+ def test_missing_subject_passes_not_subject_only_rule(self) -> None:
+ rules = parse_rules([{'not_subject': r'\[WIP\]', 'labels': ['INBOX']}], 'test')
+ assert evaluate_rules(rules, make_msg(b'From: a@b.com\r\n\r\nBody')) == ['INBOX']
+
+ def test_header_table_and_multiple_instances(self) -> None:
+ rules = parse_rules(
+ [
+ {
+ 'header': {
+ 'List-Id': r'<linux-input\.vger\.kernel\.org>',
+ 'X-Tag': ['urgent', 'security'],
+ },
+ 'labels': ['Urgent'],
+ }
+ ],
+ 'test',
+ )
+ msg = make_msg(b'list-id: <linux-input.vger.kernel.org>\r\nX-Tag: normal\r\nX-Tag: Security-Fix\r\n\r\nBody')
+ missing_one = make_msg(b'List-Id: <linux-input.vger.kernel.org>\r\n\r\nBody')
+
+ assert evaluate_rules(rules, msg) == ['Urgent']
+ assert evaluate_rules(rules, missing_one) == []
+
+ def test_multiple_matching_rules_preserve_order_and_deduplicate(self) -> None:
+ rules = parse_rules(
+ [
+ {'recipient': 'alice@example.com', 'labels': ['INBOX', 'Direct']},
+ {'subject': 'urgent', 'labels': ['Direct', 'UNREAD', 'Urgent']},
+ ],
+ 'test',
+ )
+ msg = make_msg(b'To: alice@example.com\r\nSubject: Urgent patch\r\n\r\nBody')
+ assert evaluate_rules(rules, msg) == ['INBOX', 'Direct', 'UNREAD', 'Urgent']
diff --git a/tests/test_tracked_thread_delivery.py b/tests/test_tracked_thread_delivery.py
index 23308c5..f381182 100644
--- a/tests/test_tracked_thread_delivery.py
+++ b/tests/test_tracked_thread_delivery.py
@@ -93,6 +93,55 @@ class TestTrackedThreadDeliveryTuple:
_, _, labels, _ = deliveries[tracked.track_id]
assert labels == ['patch-review', 'urgent']
+ def test_target_rules_loaded_without_static_deliveries(self, tmp_path: Path) -> None:
+ """Tracked threads get Gmail modify scope and parsed target_rules without static deliveries."""
+ now = datetime.now(UTC)
+ tracked = TrackedThread(
+ track_id='track-rule1',
+ msgid='<rule@example.com>',
+ subject='Rule test',
+ target='personal',
+ labels=['Tracked'],
+ lei_path=tmp_path / 'lei-rule1',
+ created=now,
+ last_update=now,
+ last_new_message=now,
+ status=TrackStatus.ACTIVE,
+ message_count=1,
+ )
+ ctx = make_ctx(
+ {
+ 'config': {
+ 'targets': {
+ 'personal': {
+ 'type': 'gmail',
+ 'credentials': 'creds.json',
+ 'rules': [{'recipient': 'me@kernel.org', 'labels': ['INBOX']}],
+ }
+ },
+ 'deliveries': {},
+ },
+ 'targets': {},
+ 'feeds': {},
+ 'deliveries': {},
+ 'data_dir': tmp_path / 'kgl-test',
+ }
+ )
+ manifest = MagicMock()
+ manifest.check_and_expire_threads.return_value = []
+ manifest.get_active_threads.return_value = [tracked]
+ with (
+ patch('korgalore.cli.get_tracking_manifest', return_value=manifest),
+ patch('korgalore.cli.LeiFeed', return_value=MagicMock()),
+ patch('korgalore.cli.get_xdg_config_dir', return_value=tmp_path),
+ ):
+ map_tracked_threads(ctx)
+
+ _, target, _, _ = ctx.obj['deliveries'][tracked.track_id]
+ assert isinstance(target, GmailTarget)
+ assert target.requires_modify is True
+ assert len(ctx.obj['target_rules']['personal']) == 1
+
class TestTrackAddPreFlightAndFailureHandling:
"""Tests for pre-flight validation and mid-loop failure handling in track_add."""
--
2.56.1.987.g2ec0ab4260-goog
^ permalink raw reply related [flat|nested] 5+ messages in thread