Skip to content

feat: share an alert with a temporary public link - #731

Merged
MateoLostanlen merged 9 commits into
mainfrom
alexis/issue-planning-44507f
Nov 9, 2026
Merged

MateoLostanlen merged 9 commits into
mainfrom
alexis/issue-planning-44507f

Conversation

@Acruve15

@Acruve15 Acruve15 commented Oct 30, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #720, part of pyronear/roadmap#31.

What it does

An operator can send an alert to someone with no account (a dispatcher, a mayor) through a link that opens without logging in, stops working after 48 h, and can be cancelled.

Flow

  • Table alert_shares: alert, source organization, creator, SHA-256 of the token, created_at, expires_at, revoked_at. Only the hash is stored, so a link cannot be shown again after creation.
  • Authenticated routes, any role of the organization (admins across organizations, as on alerts):
    • POST /shares {alert_id} returns share_id, the token (once) and expires_at
    • GET /shares?alert_id= lists the organization's links with a status (active, expired, revoked)
    • DELETE /shares/{share_id} cancels (soft revoke, idempotent)
  • Public routes, no auth, both an explicit whitelist built in services/shares.py:
    • GET /shares/public/{token}: alert time and fire position, and per sequence its id, the camera name and position, azimuths, and the 10 latest real detections as a preview. No organization, labels, device IPs, livestream or occlusion masks.
    • GET /shares/public/{token}/sequences/{sequence_id}/detections: browse a sequence the way the platform does, with the same limit, offset, desc, sampling, with_crop and X-Sampled-* headers as GET /sequences/{sequence_id}/detections (both call fetch_detection_page), continuity rows included, so the sharer and the recipient see the same frames. 404 unless the sequence belongs to the shared alert. Detections carry id, created_at, recorded_at, bbox, url, crop_url, the platform's field names, so the existing sequence viewer can read them; camera, pose and bucket keys stay out.
  • Answers: 404 for an unknown token, 410 once expired or cancelled. 256-bit tokens (secrets.token_urlsafe(32)) make enumeration infeasible, so the distinction leaks nothing and lets the public page say "expired" rather than "invalid".
  • Images: presigned for 15 min (SHARE_URL_EXPIRATION) on the camera organization's bucket. The lifetime is fixed so the existing per-bucket URL cache keeps working. Cache-Control: no-store on the public response.

Alert lifecycle

Alerts are deleted in three places (DELETE /alerts/{id}, the bulk delete in _merge_alerts, and refresh_alert_state when an alert loses its last sequence), and none of them knew about other tables. So:

  • alert_shares.alert_id is ON DELETE CASCADE at DB level, which also covers the bulk delete.
  • _merge_alerts repoints shares to the surviving alert before deleting the absorbed one, so a link sent just before a merge keeps working.

Next steps: sharing with another organization (pyronear/roadmap#33)

This PR is meant as the first case of the model #33 would extend, not a parallel mechanism. Proposal for the #33 discussion: reference, not copy.

  • Copying an alert into the target organization would leave its sequences, detections and images owned by the source, and every existing access check compares the caller's organization to camera.organization_id. Each of those routes would need loosening.
  • Instead, the share row is the one place that grants cross-organization access. A public link is a share whose recipient is "whoever holds the token"; an organization share is the same row with a target_organization_id (and token_hash nullable, with a CHECK that exactly one recipient is set, or an explicit recipient_kind).
  • The receiving organization reads through new read-only routes (e.g. GET /shares/received) that reuse build_shared_alert, so it gets the same whitelist. Existing alert, sequence and detection routes stay untouched.
  • "Appears as a new alert" becomes a platform concern (the feed merges received shares). Receiver labelling, acceptance, and Telegram/Slack notification of the target belong on the share row, not on the source alert.
  • Images stay in the source bucket, presigned per camera organization, which also covers an alert triangulated from two organizations' cameras.

Nothing for #33 is built here; the table name, the source-organization column and the service split are what keep that path open.

Known limits

  • The token is in the URL path. It is masked in uvicorn access logs (ShareTokenFilter on uvicorn.access) and in Sentry events (scrub_share_token masks the URL, drops the Referer and drops frame locals). Other places that see the raw path, such as a reverse proxy's logs, still record it.
  • A presigned image URL keeps working until its own expiry (15 min max) after the link expires or is cancelled.
  • When the alert disappears (admin deletion, or emptied by unmatch or a relabel), its links go with it and answer 404. Only merges repoint.
  • No rate limiting on the public route and no clean-up job: expired rows are filtered at read and kept as an audit trail.

Tests

  • tests/endpoints/test_shares.py: create, list, cancel across roles and organizations; public route for valid, unknown, expired, revoked and freshly cancelled links; payload whitelist; continuity frames skipped in the preview; browsing route scoped to the shared alert, and returning the same frames and X-Sampled-* headers as the platform route across paging and sampling; cascade on alert deletion; repoint on merge.
  • Token helpers in test_security.py, Sentry scrub and access log filter in test_main.py.
  • Full suite in the dev stack: 752 passed, 1 skipped. Migration upgrade, downgrade -1, upgrade round trip OK, alembic check reports no drift. ruff and ty clean.

Add an alert_shares table and /shares routes: an org user creates, lists
and cancels links to an alert of their organization; anyone holding the
link reads a whitelisted view of the alert on /shares/public/{token},
with short-lived image URLs. Only the SHA-256 of the 256-bit token is
stored. Links expire after 48 h; expired or cancelled links answer 410,
unknown ones 404.

Shares cascade on alert deletion and follow the surviving alert on
merge. Share tokens are scrubbed from Sentry events.

Closes #720
Comment thread src/tests/endpoints/test_shares.py Fixed
Comment thread src/tests/endpoints/test_shares.py Fixed
Comment thread src/tests/endpoints/test_shares.py Fixed
Comment thread src/tests/endpoints/test_shares.py Fixed
Comment thread src/tests/endpoints/test_shares.py Fixed
Comment thread src/tests/endpoints/test_shares.py Fixed
Comment thread src/tests/endpoints/test_shares.py Fixed
Comment thread src/tests/endpoints/test_shares.py Fixed
@codecov

codecov Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 95.68%. Comparing base (f2c1604) to head (c84d127).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #731      +/-   ##
==========================================
+ Coverage   95.17%   95.68%   +0.50%     
==========================================
  Files          60       65       +5     
  Lines        3402     3685     +283     
==========================================
+ Hits         3238     3526     +288     
+ Misses        164      159       -5     
Flag Coverage Δ
backend 95.84% <100.00%> (+0.51%) ⬆️
client 91.83% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@MateoLostanlen MateoLostanlen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @Acruve15, thanks for the PR! Really clean work, and the write-up is great.

One change needed:

  • main got a new migration (ff5b6d1f9e3f, from #724) with the same parent e7a4b9c3d5f2. After merge we would have two Alembic heads. Can you rebase and set down_revision = "ff5b6d1f9e3f"?

Thanks!

…-44507f

# Conflicts:
#	src/app/api/api_v1/endpoints/detections.py

@MateoLostanlen MateoLostanlen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @Acruve15, thanks for the PR! The migration is chained correctly now, thanks for the quick fix.

One question before I approve: the Sentry scrub only cleans request.url. If an error happens on the public route, I think Sentry frame locals still hold the ASGI scope (path, raw_path) with the token. Can you confirm? If so, dropping the frame vars for /shares/public/ events in scrub_share_token would cover it, here or in a follow-up PR.

(nit) Uvicorn access logs also show the token. A small logging.Filter on uvicorn.access would hide it.

@fe51 fe51 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

hi @Acruve15 !

Great work, thanks a lot! One product point: the recipient only gets the 10 latest frames per sequence. Ideally they'd see what the sharer sees, and be able to browse a sequence the way the platform does: load more frames and use sampling to get a spread from the start of the fire to now.

Would it be feasible to add something like:

GET /shares/public/{token}/sequences/{sequence_ref}/detections?sampling=&limit=&offset=&desc=

It would reuse DetectionCRUD.fetch_by_sequence (same sampling, X-Sampled-Total headers and presigned URLs as /sequences/{id}/detections), after checking that the sequence belongs to the shared alert. The open question is sequence_ref. You could expose the sequence id, which is harmless once scoped to the share. Or you could use a reference that only makes sense within the share, to keep the "no ids" whitelist. The sequence's position in the list won't work as that reference, because the order changes as last_seen_at moves.

It would probably also make the frontend side simpler. Since the endpoint would have the same parameters and response shape as /sequences/{id}/detections, the public page could reuse the existing sequence viewer components instead of building a separate view for a fixed list of frames.

If that's too much for this PR, no problem: just raise _MAX_DETECTIONS_PER_SEQUENCE to 20, and we can do the browsing in a follow-up.

Happy to discuss it, otherwise, the PR is fine for a first iteration !

@fe51 fe51 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Following up on my comment above: on second thought, I think matching how the platform loads detections is needed rather than optional. Otherwise the sharer and the recipient see different frames, and the frontend has to build a separate view instead of reusing the existing sequence components.

Requesting changes for that point only, everything else looks good to me.

@MateoLostanlen

Copy link
Copy Markdown
Member

I agree with @fe51. I first thought the 10 latest frames would be enough for someone outside the platform, but the recipient should see the same view as the sharer. If the frames differ, the two of them will talk past each other on the phone.

Thanks @Acruve15 for the update!

@Acruve15

Acruve15 commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

hi @fe51 @MateoLostanlen, agreed, done in c84d127 😊 Any other comments or ready to approve?

GET /shares/public/{token}/sequences/{sequence_id}/detections takes the same params and returns the same X-Sampled-* headers as /sequences/{id}/detections, through one shared helper. A test checks both return the same frames. 404 if the sequence isn't part of the shared alert.

The main link keeps a 10-frame preview per sequence. It skips continuity rows. The browse route keeps them, like the platform.

Small ask: could you leave future comments as a PR review with inline comments on the code? Much easier for me to follow and resolve 🙇

Thanks!

@fe51 fe51 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @Acruve15 thanks a lot for taking the feedbacks into account.

We are good to merge for this first version !

Sorry, thought i have added comment as a review, dully noted for next time :)

@Acruve15
Acruve15 removed the request for review from MateoLostanlen November 9, 2026 12:52
@Acruve15

Acruve15 commented Nov 9, 2026

Copy link
Copy Markdown
Collaborator Author

@MateoLostanlen I still need your approval please 🥲

@MateoLostanlen
MateoLostanlen self-requested a review November 9, 2026 13:33

@MateoLostanlen MateoLostanlen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks

@MateoLostanlen
MateoLostanlen merged commit fe02974 into main Nov 9, 2026
25 of 26 checks passed
@MateoLostanlen
MateoLostanlen deleted the alexis/issue-planning-44507f branch November 9, 2026 13:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Share an alert with a temporary public link

3 participants