Skip to content

feat: harden imports and preserve sender history - #241

Merged
GeiserX merged 2 commits into
mainfrom
ai/v7.28-security-and-issues
Jul 27, 2026
Merged

GeiserX merged 2 commits into
mainfrom
ai/v7.28-security-and-issues

Conversation

@GeiserX

@GeiserX GeiserX commented Jul 27, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • confine Telegram Desktop media imports to the selected export and media roots, enforce filename byte limits, and continue after individual copy failures
  • preserve first-seen sender names across import, sweep, listener, API, export, push, and viewer paths with migration 020
  • fix imported-supergroup attribution, sender-run spacing, sender details, and prepare the v7.28.0 release

Addresses #236, #238, #239, and #240.

Type of Change

  • Bug fix (non-breaking change that fixes an issue)
  • New feature (non-breaking change that adds functionality)
  • Breaking change (fix or feature that causes existing functionality to change)
  • Documentation update
  • Infrastructure/CI change

Database Changes

  • Schema changes (Alembic migration required)
  • Data migration script added in scripts/
  • No database changes

Migration 020 adds nullable messages.sender_name; existing rows remain unchanged. Pre-Alembic databases still stamp at 018 so data-only migration 019 runs before guarded migration 020.

Data Consistency Checklist

  • All chat_id values use marked format (via _get_marked_id())
  • All datetime values pass through _strip_tz() before DB operations
  • INSERT and UPDATE operations handle the same fields identically

sender_name is normalized and first-nonblank/write-once in both single and batch upserts.

Testing

  • Tests pass locally (.venv/bin/python -m pytest tests/ -q: 2,407 passed, 150 subtests)
  • Linting passes (.venv/bin/ruff check .)
  • Formatting passes (.venv/bin/ruff format --check .)
  • Manually tested in development environment

Additional review: independent code review approved with no medium-or-higher findings; independent security review found no medium-or-higher issues.

Security Checklist

  • No secrets or credentials committed
  • User input properly validated/sanitized
  • Authentication/authorization properly checked

Import control files, source paths, destination names, and destination roots are constrained before filesystem access. Copy failures are isolated per media item.

Deployment Notes

  • Tagging v7.28.0 after merge publishes the release and both production Docker images.
  • Startup applies migration 020 automatically; no manual backfill is required.

Summary by CodeRabbit

  • New Features

    • Preserves each message’s historical sender name for more accurate archives and exports.
    • Added sender details from group avatars, including archived name, latest known name, and Telegram ID.
    • Improved message grouping with clearer spacing when senders change.
    • Supergroup messages now display sender names and avatars correctly.
  • Bug Fixes

    • Hardened media imports against unsafe paths and symlinks.
    • Long or malformed filenames no longer interrupt imports; failed media items are skipped.
    • Media filenames are safely shortened while respecting configured limits.
  • Upgrade

    • Version 7.28.0 includes an automatic database migration for sender-name snapshots.

Confine imported media to trusted roots while making imports resilient, and preserve per-message sender identity across capture and viewing.
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Sender archive and presentation

Layer / File(s) Summary
Sender snapshot pipeline
src/db/*, src/listener.py, src/message_utils.py, src/telegram_backup.py, src/web/main.py, tests/test_db_adapter_soft_delete_upsert.py, tests/test_listener_*, tests/test_telegram_backup.py, tests/test_web_messages_api.py, tests/test_web_routes.py
Messages capture normalized historical sender names, preserve them during upserts, and expose them in exports, media results, realtime notifications, and API responses.
Telegram import validation and media copying
src/telegram_import.py, src/__main__.py, tests/test_telegram_import.py
Telegram export files and media paths are validated against the export root; imported sender fields are normalized; filenames are byte-bounded; failed media copies are skipped individually.
Sender details and message runs
src/web/templates/index.html, tests/test_frontend_bootstrap.py, tests/test_sender_avatars.py
Group avatars open an accessible sender-details dialog, supergroups use group rendering, media names are normalized, and message spacing follows sender runs.

Schema rollout and release metadata

Layer / File(s) Summary
Migration detection and release metadata
scripts/entrypoint.sh, tests/test_entrypoint_schema_detection.py, tests/test_migration_020.py, pyproject.toml, src/__init__.py, docs/CHANGELOG.md
Migration 020 schema detection and idempotency coverage are added, pre-Alembic stamping remains capped at 018, and release metadata is updated to 7.28.0.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 46.15% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title concisely matches the main change: import hardening and sender-history preservation.
Description check ✅ Passed All required template sections are present and filled with relevant details, including summary, changes, testing, and deployment notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ai/v7.28-security-and-issues

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

🐳 Dev images published!

  • drumsergio/telegram-archive:dev
  • drumsergio/telegram-archive-viewer:dev

The dev/test instance will pick up these changes automatically (Portainer GitOps).

To test locally:

docker pull drumsergio/telegram-archive:dev
docker pull drumsergio/telegram-archive-viewer:dev

@codecov

codecov Bot commented Jul 27, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 91.61290% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.47%. Comparing base (d9a7fed) to head (08a6ce8).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/telegram_import.py 92.66% 8 Missing ⚠️
src/listener.py 73.33% 4 Missing ⚠️
src/message_utils.py 92.30% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #241      +/-   ##
==========================================
+ Coverage   93.45%   93.47%   +0.01%     
==========================================
  Files          27       27              
  Lines        8423     8532     +109     
==========================================
+ Hits         7872     7975     +103     
- Misses        551      557       +6     
Files with missing lines Coverage Δ
src/__init__.py 100.00% <100.00%> (ø)
src/__main__.py 98.07% <100.00%> (ø)
src/db/adapter.py 91.87% <100.00%> (+0.72%) ⬆️
src/db/models.py 100.00% <100.00%> (ø)
src/telegram_backup.py 94.86% <100.00%> (ø)
src/web/main.py 88.59% <100.00%> (+<0.01%) ⬆️
src/message_utils.py 84.01% <92.30%> (+0.38%) ⬆️
src/listener.py 95.87% <73.33%> (-0.45%) ⬇️
src/telegram_import.py 98.13% <92.66%> (-1.87%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (7)
tests/test_web_routes.py (1)

1718-1718: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add the return type annotation.

Annotate the new async test as -> None to comply with the repository’s Python type-hinting requirement.

Proposed fix
-    async def test_push_prefers_archived_sender_snapshot(self):
+    async def test_push_prefers_archived_sender_snapshot(self) -> None:
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_web_routes.py` at line 1718, Update the
test_push_prefers_archived_sender_snapshot async test definition to include the
repository-required None return type annotation.

Source: Coding guidelines

src/web/templates/index.html (2)

1416-1421: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Label can say "Latest known name" for a synthesized placeholder.

When sender_name is absent and the profile fields are empty, getSenderInfoName falls back to User <id> / Deleted Account via getSenderName, but the dt still reads "Latest known name". Consider "Name" for that case.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/web/templates/index.html` around lines 1416 - 1421, Update the label
logic in the sender information block to display “Name” when sender_name is
absent and the profile fields are empty, matching the synthesized fallback
returned by getSenderInfoName; retain “Archived name” for archived names and
“Latest known name” when an actual latest profile name exists.

4052-4061: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

isRunEnd and isSenderBreak are now the same predicate.

Both compare getSenderRunKey(newerMsg) !== getSenderRunKey(currMsg). They serve different consumers (bubble tail vs. spacing), so keeping both names is defensible, but define one and alias the other so they can't silently drift.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/web/templates/index.html` around lines 4052 - 4061, Consolidate the
duplicated sender-transition predicate used by isRunEnd and isSenderBreak:
retain one implementation and make the other delegate to or alias it. Preserve
both named helpers for their separate consumers while ensuring both use
identical getSenderRunKey comparison behavior.
src/telegram_import.py (3)

763-815: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

continue on media-path failure skips the batch-size flush for that iteration.

Lines 774 and 781 jump past the len(batch) >= BATCH_SIZE check at line 807. The message row is already appended, so nothing is lost — the flush is just deferred to the next message. Harmless today, but it makes the batching contract implicit; consider setting a flag and falling through instead.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/telegram_import.py` around lines 763 - 815, Replace the media-path
failure continues in the import loop around _resolve_export_media_path with
control flow that records the media skip and still reaches the len(batch) >=
BATCH_SIZE flush check for the current message. Preserve the existing warning
behavior and ensure the message row remains appended while invalid media is
omitted.

835-861: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

Blocking shutil.copy2 on the event loop.

_flush_batch is async but copies files synchronously; a large media import stalls the loop. For the one-shot CLI importer this is benign, but asyncio.to_thread(shutil.copy2, source, dest_path) would be a drop-in fix if this ever runs alongside other tasks.

Destination re-validation and per-item error isolation look right.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/telegram_import.py` around lines 835 - 861, Update the media copy in
_flush_batch to run shutil.copy2(source, dest_path) via asyncio.to_thread,
awaiting its result so the async event loop is not blocked. Preserve the
existing destination validation, filesystem exception handling, and per-item
continuation behavior.

164-176: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

export_path is now unused in _detect_media.

The rewritten body never touches it; path resolution moved to _resolve_export_media_path. Drop the parameter (and update the three call sites/tests) when convenient.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/telegram_import.py` around lines 164 - 176, Remove the unused export_path
parameter from _detect_media, since path resolution is handled by
_resolve_export_media_path. Update all three callers and related tests to use
the revised signature without changing media detection behavior.
tests/test_frontend_bootstrap.py (1)

32-85: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Plain pytest functions instead of unittest.TestCase.

The repo guideline asks for unittest.TestCase for test consistency. This file already uses module-level functions, so the new tests match local style — flagging only so the deviation is deliberate.

Otherwise the assertions are fine; note that html.count("getSenderRunKey(") >= 6 currently matches exactly 6 call sites, so any refactor that inlines one will fail the test.

As per coding guidelines: "Use unittest.TestCase with MagicMock/AsyncMock for test consistency".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_frontend_bootstrap.py` around lines 32 - 85, Convert the new
module-level tests in tests/test_frontend_bootstrap.py into methods on a
unittest.TestCase subclass, preserving their existing assertions and test
coverage. Keep the getSenderRunKey call-site count requirement intact, and
follow the repository’s unittest style without adding unrelated mocking.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/listener.py`:
- Around line 1028-1033: Update the fallback sender resolution in
listener.py:1028-1033 and the service-message path in listener.py:1197-1204 to
invoke event.get_sender() or msg.get_sender() through
call_with_flood_retry(...), retrying FloodWaitError while treating other
exceptions as non-retryable; if no sender is directly attached and resolution
still fails, leave the snapshot unset.

In `@tests/test_entrypoint_schema_detection.py`:
- Around line 125-145: Update tests/test_entrypoint_schema_detection.py:125-145,
159-168, and 254-260 by converting the affected module-level tests into methods
on unittest.TestCase classes and adding complete parameter and return
annotations, including -> None for the PostgreSQL detection test. In
tests/test_migration_020.py:15-64, annotate every helper signature and convert
all migration tests into unittest.TestCase methods, preserving their existing
assertions and behavior.

In `@tests/test_migration_020.py`:
- Around line 15-25: Update _load_migration and _run with complete type
annotations, including return types and appropriate parameter types. Convert the
module-level tests in tests/test_migration_020.py into methods on a
unittest.TestCase subclass, preserving their existing assertions and migration
behavior.

---

Nitpick comments:
In `@src/telegram_import.py`:
- Around line 763-815: Replace the media-path failure continues in the import
loop around _resolve_export_media_path with control flow that records the media
skip and still reaches the len(batch) >= BATCH_SIZE flush check for the current
message. Preserve the existing warning behavior and ensure the message row
remains appended while invalid media is omitted.
- Around line 835-861: Update the media copy in _flush_batch to run
shutil.copy2(source, dest_path) via asyncio.to_thread, awaiting its result so
the async event loop is not blocked. Preserve the existing destination
validation, filesystem exception handling, and per-item continuation behavior.
- Around line 164-176: Remove the unused export_path parameter from
_detect_media, since path resolution is handled by _resolve_export_media_path.
Update all three callers and related tests to use the revised signature without
changing media detection behavior.

In `@src/web/templates/index.html`:
- Around line 1416-1421: Update the label logic in the sender information block
to display “Name” when sender_name is absent and the profile fields are empty,
matching the synthesized fallback returned by getSenderInfoName; retain
“Archived name” for archived names and “Latest known name” when an actual latest
profile name exists.
- Around line 4052-4061: Consolidate the duplicated sender-transition predicate
used by isRunEnd and isSenderBreak: retain one implementation and make the other
delegate to or alias it. Preserve both named helpers for their separate
consumers while ensuring both use identical getSenderRunKey comparison behavior.

In `@tests/test_frontend_bootstrap.py`:
- Around line 32-85: Convert the new module-level tests in
tests/test_frontend_bootstrap.py into methods on a unittest.TestCase subclass,
preserving their existing assertions and test coverage. Keep the getSenderRunKey
call-site count requirement intact, and follow the repository’s unittest style
without adding unrelated mocking.

In `@tests/test_web_routes.py`:
- Line 1718: Update the test_push_prefers_archived_sender_snapshot async test
definition to include the repository-required None return type annotation.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a4793a19-c64c-4eec-b6c6-8b50a4e3b689

📥 Commits

Reviewing files that changed from the base of the PR and between d9a7fed and 8527ba7.

⛔ Files ignored due to path filters (2)
  • alembic/versions/20260727_020_add_message_sender_name.py is excluded by !alembic/versions/**
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (24)
  • docs/CHANGELOG.md
  • pyproject.toml
  • scripts/entrypoint.sh
  • src/__init__.py
  • src/__main__.py
  • src/db/adapter.py
  • src/db/models.py
  • src/listener.py
  • src/message_utils.py
  • src/telegram_backup.py
  • src/telegram_import.py
  • src/web/main.py
  • src/web/templates/index.html
  • tests/test_db_adapter_soft_delete_upsert.py
  • tests/test_entrypoint_schema_detection.py
  • tests/test_frontend_bootstrap.py
  • tests/test_listener_chat_actions.py
  • tests/test_listener_extended.py
  • tests/test_migration_020.py
  • tests/test_sender_avatars.py
  • tests/test_telegram_backup.py
  • tests/test_telegram_import.py
  • tests/test_web_messages_api.py
  • tests/test_web_routes.py

Comment thread src/listener.py Resolved
Comment thread tests/test_migration_020.py Resolved
Keep importer batching and the event loop responsive on media failures, preserve flood-aware sender resolution, and align UI and tests with repository conventions.
@github-actions

Copy link
Copy Markdown

🐳 Dev images published!

  • drumsergio/telegram-archive:dev
  • drumsergio/telegram-archive-viewer:dev

The dev/test instance will pick up these changes automatically (Portainer GitOps).

To test locally:

docker pull drumsergio/telegram-archive:dev
docker pull drumsergio/telegram-archive-viewer:dev

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
tests/test_telegram_import.py (3)

176-180: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the complete no-media result.

This test checks media_type and rel but not fname. Add self.assertIsNone(fname) so a stale or unexpected filename cannot pass unnoticed.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_telegram_import.py` around lines 176 - 180, Update test_no_media
to also assert that the fname result from _detect_media({}) is None, while
preserving the existing assertions for media_type and rel.

469-475: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Skip when symlink creation is unavailable.

hasattr(os, "symlink") does not guarantee permission to create symlinks; on some platforms, os.symlink(...) can raise OSError and fail the suite. Catch that setup error and call self.skipTest(...) in all three tests.

Also applies to: 661-668, 674-678

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_telegram_import.py` around lines 469 - 475, Update the setup of
all three symlink tests, including
test_import_rejects_media_symlink_outside_export_root and the tests at the
referenced locations, to catch OSError from os.symlink and call
self.skipTest(...) when creation is unavailable. Keep the existing hasattr(os,
"symlink") guard and test behavior unchanged when symlink creation succeeds.

181-181: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add type annotations to new test signatures.

The newly added test methods and fail_first_copy helper lack type hints. Add -> None to test methods and concrete argument/return annotations to the helper.

As per coding guidelines, Python files must use type hints for function signatures.

Also applies to: 365-365, 435-435, 470-470, 500-500, 538-538, 566-566, 581-581, 662-662, 675-675

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_telegram_import.py` at line 181, Add type annotations to the newly
added test methods in the test class, including
test_non_string_paths_and_names_are_ignored_safely and the other affected tests,
using -> None. Annotate the fail_first_copy helper with concrete types for every
parameter and its return value, following the surrounding test conventions.

Source: Coding guidelines

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tests/test_telegram_import.py`:
- Around line 176-180: Update test_no_media to also assert that the fname result
from _detect_media({}) is None, while preserving the existing assertions for
media_type and rel.
- Around line 469-475: Update the setup of all three symlink tests, including
test_import_rejects_media_symlink_outside_export_root and the tests at the
referenced locations, to catch OSError from os.symlink and call
self.skipTest(...) when creation is unavailable. Keep the existing hasattr(os,
"symlink") guard and test behavior unchanged when symlink creation succeeds.
- Line 181: Add type annotations to the newly added test methods in the test
class, including test_non_string_paths_and_names_are_ignored_safely and the
other affected tests, using -> None. Annotate the fail_first_copy helper with
concrete types for every parameter and its return value, following the
surrounding test conventions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: c343a6a1-6ef7-4c54-9004-043b243d50fa

📥 Commits

Reviewing files that changed from the base of the PR and between 8527ba7 and 08a6ce8.

📒 Files selected for processing (8)
  • src/listener.py
  • src/telegram_import.py
  • src/web/templates/index.html
  • tests/test_entrypoint_schema_detection.py
  • tests/test_frontend_bootstrap.py
  • tests/test_migration_020.py
  • tests/test_telegram_import.py
  • tests/test_web_routes.py
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/listener.py
  • tests/test_frontend_bootstrap.py
  • tests/test_migration_020.py
  • tests/test_entrypoint_schema_detection.py
  • src/web/templates/index.html
  • src/telegram_import.py

@GeiserX
GeiserX merged commit 9a58643 into main Jul 27, 2026
10 checks passed
@GeiserX
GeiserX deleted the ai/v7.28-security-and-issues branch July 27, 2026 10:54
GeiserX added a commit that referenced this pull request Jul 28, 2026
* feat: secure imports and preserve sender history

Confine imported media to trusted roots while making imports resilient, and preserve per-message sender identity across capture and viewing.

* fix: address v7.28 review findings

Keep importer batching and the event loop responsive on media failures, preserve flood-aware sender resolution, and align UI and tests with repository conventions.
GeiserX added a commit that referenced this pull request Oct 2, 2026
* feat: secure imports and preserve sender history

Confine imported media to trusted roots while making imports resilient, and preserve per-message sender identity across capture and viewing.

* fix: address v7.28 review findings

Keep importer batching and the event loop responsive on media failures, preserve flood-aware sender resolution, and align UI and tests with repository conventions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant