Skip to content

UN-3494 [GATED-FEAT] Email users and groups on access grant and revoke - #2224

Draft
kirtimanmishrazipstack wants to merge 11 commits into
mainfrom
UN-3494-group-sharing-notification
Draft

UN-3494 [GATED-FEAT] Email users and groups on access grant and revoke#2224
kirtimanmishrazipstack wants to merge 11 commits into
mainfrom
UN-3494-group-sharing-notification

Conversation

@kirtimanmishrazipstack

@kirtimanmishrazipstack kirtimanmishrazipstack commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

What

  • Emails every resource access change: granted or revoked, to a person or to a group's members — plus added to / removed from a group.
  • New internal APIs under /internal/v1/group-notification/ and two workers/notification tasks that call them.
  • Collapses the 7 per-viewset copies of the user notification hook into ResourceShareManagementMixin and drops the dead PATCH path.
  • Co-owner modal: removal now waits for Apply instead of firing on click.

Why

  • Sharing a resource granted access silently, revoking it told nobody, and group members had no way to know in either direction.
  • _notify_shared_users was still wired to partial_update, which no client has called since UN-2977, so even the direct-user share email had quietly stopped.
  • Co-owner adds waited for Apply but removals fired instantly, so Cancel could not undo a revoke.

How

  • One hook in ResourceShareManagementMixin.share covers all 7 shareable resources plus cloud agentic; dispatch reuses resolve_transport (PG queue where pg_queue_enabled is on for the org, Celery otherwise).
  • Group revoke rides the existing resource-shared route with a share_action discriminator, mirroring membership-changed.
  • A revoke email is suppressed when the recipient still reaches the resource another way — direct row, another group, shared_to_org, or ownership. Both the direct and the group path run that filter.
  • CoOwnerManagement stages one owner list and diffs it at Apply like SharePermission; the hook's two callbacks collapse into onApplyCoOwners, adds before removes.

Can this PR break any existing features. If yes, please list possible items. If no, please explain why. (PS: Admins do not merge the PR without this section filled)

  • Low risk: notification-only side effects, all wrapped. Flipt group_sharing_notifications_enabled gates the group paths (share/revoke to a group, group membership change). The direct-user share and revoke mail is not on that flag — like the co-owner mail it reuses, it is bounded only by the cloud ENABLE_EMAIL_NOTIFICATIONS setting, and it goes live for every org on merge. That path was the intended behaviour before UN-2977 broke it, so it is a restore rather than a new dark feature.
  • The deletions are dead code — the partial_update hooks cannot fire since shared_users became ResourceMembership rows in UN-2202 Phase 2. Membership changes with no actor (org-removal cascade, Django admin, group deletion) deliberately do not notify. Co-owner removal is intentionally no longer instant; the widget prop became onApplyCoOwners and all consumers are updated.
  • Delivery is at-least-once. A response lost after the backend has already sent re-posts the same payload, so a recipient can occasionally get one duplicate email. The send path writes nothing, so that is the only effect.

Database Migrations

  • None

Env Config

  • Flipt group_sharing_notifications_enabled — new, gates the group notification paths. Off or unreachable means no group emails.
  • Flipt pg_queue_enabled — existing, reused to pick PG queue vs Celery transport.
  • k8s deploy order for the PG transport is documented in the cloud PR (Zipstack/unstract-cloud#1698): workerPgNotification must be enabled in an environment before pg_queue_enabled is ramped there, or notifications land durably in the PG notifications queue with nothing consuming them.

Relevant Docs

Related Issues or PRs

  • Zipstack/unstract-cloud#1698 — cloud half. Must merge at or before this PR.

Dependencies Versions

  • None

Notes on Testing

  • Verified manually against a dev org: grant, revoke, group grant, group revoke, co-owner add and co-owner remove all dispatch with the expected recipients and payloads, and a revoke is correctly suppressed while the user retains access through a group.
  • Co-owner modal checked manually: stage, cancel, apply, and a combined add+revoke.

Screenshots

Checklist

I have read and understood the Contribution Guidelines.

…ship changes

Sharing a resource with a group gave its members access silently, and adding
or removing someone from a group told nobody. Both now send email.

- share_notifications.py holds the feature flag, the two task names and the two
  enqueue hooks. Dispatch uses the same resolve_transport branch the execution
  path uses: the PG queue where pg_queue_enabled is on for the org, Celery
  otherwise.
- One hook in ResourceShareManagementMixin.share covers all 7 resource types
  plus cloud agentic, including service-account shares — every group share
  funnels through it and shared_groups has no PATCH path. No on_commit needed:
  _commit's transaction has closed by the time the view resumes, so the diff
  reads committed state.
- Group membership hooks on the add and remove actions. The add serializer
  already subtracts existing members, so nobody is mailed twice.
- Internal endpoints under /internal/v1/group-notification/ do the work the
  worker cannot: group expansion, OrganizationMember re-validation (this is
  where the offboarding race closes), resource lookup via ShareableResource,
  and the kind -> ResourceType mapping, which is not 1:1 — pipelines split on
  pipeline_type and adapters four ways on adapter_type.
- Two worker tasks that only POST to that endpoint, since workers/ has no
  Django. They raise on failure, unlike _mark_buffer_outcome which has a reaper
  behind it, and retry transient 5xx in-task because a raise is terminal on the
  Celery transport.
- The whole feature is gated on Flipt group_sharing_notifications_enabled and
  fails closed: a blind Flipt, a missing org, or any dispatch error means no
  notification, never a broken share.
- worker-pg-notification compose service so the PG arm is not a black hole.

Membership changes with no actor (the org-removal cascade, Django admin, group
deletion) do not notify — SharingNotificationService requires an actor.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Summary by CodeRabbit

  • New Features

    • Added email notifications for group resource sharing, access revocation, and membership changes.
    • Added notifications when users are added to or removed from groups.
    • Co-owner management now stages additions and removals together for one Apply action.
  • Bug Fixes

    • Improved co-owner failure handling with clear alerts, retry support, and protection against removing the final owner.
    • Sharing notifications now account for users who retain access through another path.
  • Changes

    • Sharing notifications are now handled through dedicated sharing actions rather than general updates.

Walkthrough

The change adds asynchronous group resource-sharing and membership notifications through feature-gated dispatch, worker tasks, internal APIs, and notification services. Legacy partial-update notification paths are removed. Frontend co-owner management now stages and applies combined additions and removals.

Changes

Group notification pipeline

Layer / File(s) Summary
Feature-gated notification dispatch
backend/tenant_account_v2/shareable_resources.py, backend/tenant_account_v2/share_notifications.py
Adds resource lookup helpers, notification actions, feature-flag checks, transport selection, and asynchronous dispatch.
Worker delivery and internal API
workers/notification/tasks.py, backend/tenant_account_v2/internal_views.py, backend/tenant_account_v2/internal_urls.py, backend/backend/internal_base_urls.py
Adds authenticated worker requests, retry handling, payload serializers, organization resolution, and notification endpoints.
Notification service and integrations
backend/tenant_account_v2/group_notification_service.py, backend/permissions/resource_share_views.py, backend/tenant_account_v2/group_views.py, backend/permissions/membership_views.py
Validates resources, groups, actors, and recipients. Sends share and membership notifications. Uses fixed supported share axes.
Legacy update path removal
backend/adapter_processor_v2/views.py, backend/connector_v2/views.py, backend/pipeline_v2/views.py, backend/prompt_studio/prompt_studio_core_v2/views.py, backend/workflow_manager/workflow_v2/views.py
Removes partial-update sharing snapshots, diffing, and notification dispatch.

Staged co-owner management

Layer / File(s) Summary
Staged roster and apply behavior
frontend/src/hooks/useCoOwnerManagement.jsx, frontend/src/components/widgets/co-owner-management/CoOwnerManagement.jsx
Stages the owner roster, applies additions before removals, aggregates failures, refreshes state, and supports retry.
Callback wiring
frontend/src/components/widgets/co-owner-management/CoOwnerModal.jsx, frontend/src/components/deployments/api-deployment/ApiDeployment.jsx, frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx
Replaces separate add/remove callbacks with onApplyCoOwners.

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

Sequence Diagram(s)

sequenceDiagram
  participant ShareChange
  participant share_notifications
  participant NotificationWorker
  participant InternalNotificationAPI
  participant group_notification_service
  participant NotificationPlugin
  ShareChange->>share_notifications: Dispatch share or membership event
  share_notifications->>NotificationWorker: Enqueue organization-scoped task
  NotificationWorker->>InternalNotificationAPI: POST notification payload
  InternalNotificationAPI->>group_notification_service: Validate and process payload
  group_notification_service->>NotificationPlugin: Send filtered notification
Loading
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 70.00% 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 clearly summarizes the main change: email notifications for user and group access grants and revokes.
Description check ✅ Passed The description covers the required sections, implementation, risks, configuration, related issue, and testing; blank documentation and screenshot sections are non-critical.
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 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch UN-3494-group-sharing-notification

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.

UN-2977 moved sharing from PATCH to POST /{id}/share/, but the mixin's
share action only diffed the groups axis. The per-viewset
_notify_shared_users hooks stayed on partial_update, which nothing calls
anymore, so sharing a resource with a user sent no email.

Snapshot every declared axis and invoke the hook after the commit; declare
it on the mixin as a no-op for hosts without a direct-share email.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@kirtimanmishrazipstack kirtimanmishrazipstack changed the title UN-3494 [FEAT] Email group members on resource share and group member… UN-3494 [GATED-FEAT] Email group members on share and membership change Aug 4, 2026
…revoked

Sharing already emailed on grant; revoking told nobody. Both axes now notify,
and the seven duplicated copies of the user hook collapse into the share mixin.

- ResourceShareManagementMixin gains a concrete _notify_shared_users covering
  grant and revoke, driven by the OwnerManagementMixin seam every host already
  declares. The seven per-viewset overrides and their dead partial_update
  wrappers go with it — a host override would otherwise shadow the mixin and
  silently swallow the revoke mail.
- share() diffs both axes through _read_axis directly; AxisDiff,
  snapshot_share_axes, diff_share_axes and the share_axes ClassVar had no
  callers left.
- Group revoke rides the existing resource-shared route with a share_action
  discriminator, mirroring membership-changed — no new endpoint or worker task.
  Defaulted at every hop so in-flight messages still run.
- Suppressed when the user still reaches the resource via a group or
  shared_to_org: losing one axis is not losing access.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@kirtimanmishrazipstack kirtimanmishrazipstack changed the title UN-3494 [GATED-FEAT] Email group members on share and membership change UN-3494 [GATED-FEAT] Email users and groups on access grant and revoke Aug 4, 2026
…tton

Adding a co-owner was staged until Apply, but revoking one fired the DELETE
straight from the Popconfirm — so Cancel could not undo it, Apply stayed
disabled for a removal-only edit, and the revoke email went out on click.

Stage the roster the way SharePermission does: one selected-owners list seeded
from the server, edited locally by both add and revoke, committed only by Apply.
Collapse the hook's two mutation callbacks into one onApplyCoOwners that runs
adds before removes (so a one-shot owner swap clears the backend's last-owner
guard), refreshes once, and emits one summary alert. Apply now closes on a clean
run and stays open on failure, matching useShareModal.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

@kirtimanmishrazipstack kirtimanmishrazipstack left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Self-review — UN-3494 (OSS)

Ran a multi-pass review over this branch (correctness, error handling, type design, comments) and verified each finding against the code rather than taking the analysis at face value. Six candidate findings turned out to be false and are not listed. Low-severity items are withheld; below is everything blocking / high / medium.

Cloud half: Zipstack/unstract-cloud#1698 — findings that span both repos are stated there from the cloud side.


Blocking

B1 — Every send result is discarded, so a failed send reports success and the queue acks it.

backend/tenant_account_v2/group_notification_service.py:102 and :153 call service.send_group_resource_shared_notification(...) / send_group_membership_notification(...) as bare statements. Both return bool. backend/tenant_account_v2/internal_views.py:83 and :95 then return 200 {"status": "success"} unconditionally, _post_group_notification sees 200 and returns, and the PG consumer deletes the message.

Failure path: SendGrid 429/503 → the plugin returns False → email silently lost, message acked, nothing above DEBUG anywhere.

This inverts the contract this file states about itself at internal_views.py:8-10 ("any unhandled problem must surface as non-2xx so the queue redelivers"), and it makes the whole retry apparatus in workers/notification/tasks.py — the 3-attempt loop, the httpx transport retries, the 120s VT, and the "deliberately raises on failure … a swallowed error would be a silently unsent email" docstring — guard a path that can no longer fail.

The plugin-missing case has the same shape: _service() returns None behind a logger.debug (:162-166). A backend built without sendgrid emails nobody while every layer reports green — and the recipient_count= INFO line never executes, so the one metric you would grep for is absent rather than zero, which is indistinguishable from "nobody was shared with".

Fix: collect the booleans in send_resource_shared / send_membership_changed and return non-2xx when any send failed retryably; log non-retryable causes (template unset, notifications disabled) at WARNING with a distinct {"status": "skipped", "reason": ...} so misconfiguration is separable from delivery.

B2 — Group-revoke emails ignore remaining access.

group_notification_service.py:89-111 mails every current member of each revoked group with no effective-access check. The direct-user path deliberately does the opposite — _users_left_without_access in backend/permissions/resource_share_views.py:81-93, with the comment "telling them their access was removed would be wrong."

Failure path: workflow W is shared with Group A and Group B; Alice is in both; an owner removes Group B. Alice is told her access was removed, and because share_action == revoked the cloud side rewrites both the CTA and resource URL to the dashboard — so the email walks her away from a resource she still fully reaches via Group A. Same for a shared_to_org=True resource, where nobody lost anything, and for members who also hold a direct VIEWER row.

The revoke recipient list should go through the same compute_effective_members filter the direct path uses.


High

H1 — The notification path in share() can 500 a share that already committed.

permissions/resource_share_views.py:175-195: only _send_share_notification and _send_revoke_notification are wrapped. _notification_context (:188, which invokes the host viewset's get_notification_resource_type override) and _users_left_without_access (:193, a DB query) run bare — after ShareAuthorizationService.authorize_and_commit has already committed at :155-161. A DB hiccup or a raising seam returns 500 for a share that succeeded, and the client retries.

The group path escapes this only by luck: _organization_slug and kind_for_instance are pure getattr/_meta reads and _feature_enabled is wrapped. Wrap the whole _notify_shared_users body plus the notify_resource_group_share_changed call at the share() call site.

H2 — A synchronous SendGrid HTTPS call is now on the live POST /share/ path.

The group path was deliberately made async (worker + internal API); the direct-user path in _notify_shared_users calls the plugin inline. This is newly-introduced request latency, not pre-existing — the previous home (partial_update) was dead code, so these emails were not firing at all before this branch.

H3 — Unbounded org-member scan pulled into that same request.

_users_left_without_accesscompute_effective_members_add_org_members (backend/tenant_account_v2/sharing_helpers.py:316-340) runs OrganizationMember.objects.filter(organization=...) with no pagination and iterates the whole result in Python, whenever shared_to_org is true. Un-sharing one user on an org-shared workflow in a 5,000-member org hydrates 5,000 OrganizationMember + User rows to answer "does this one user still have access?" Against ARCHITECTURE_PRINCIPLES §6 on unbounded querysets and heavy work in the request cycle.

Cheap and correct: guard-clause if getattr(instance, "shared_to_org", False): return [] — if the resource is org-shared, nobody who lost a direct row actually lost access.

H4 — The new direct-share revoke email ships with no feature flag.

_notify_shared_users has no Flipt check at all; only the group path is gated by GROUP_NOTIFICATION_FLAG_KEY. So the new revoke email goes live for every org the moment this deploys, with no kill switch. The module docstring at backend/tenant_account_v2/share_notifications.py:13-15 claims "The whole feature sits behind its own Flipt flag and fails closed everywhere", and the PR description repeats it — neither is true for this path. Either gate it or correct both statements. (Template-reuse half of this is on the cloud PR.)

H5 — Lookups are group-shareable but get no group email, and nothing logs it.

LookupDefinition is absent from SHAREABLE_RESOURCES (backend/tenant_account_v2/shareable_resources.py:28-52), so kind_for_instance returns None and share_notifications.py:100 returns with no log line at allkind is None is collapsed into the same silent early-return as feature-flag-off. Direct-user lookup emails do fire (the cloud PR wires get_notification_resource_type for exactly that), so the result reads as a flaky feature rather than a gap.

Split that guard: flag-off is expected silence, but an unregistered kind and a resource with no organization are both bugs and should log at WARNING. Then either register LookupDefinition or reject shared_groups for hosts absent from the registry.

H6 — _get_user is the one org-unscoped query on a tenant-scoped path.

group_notification_service.py:170-171 resolves the actor with User.objects.filter(pk=user_id).first(). Every sibling lookup on this path re-validates against the org (_groups_in_org, _live_member_users, and _load_resource, which filters organization= explicitly and explains why). The resolved user's name and email render into the outgoing mail. Not exploitable today since the payload is worker-generated, but it is an unscoped query on a multi-tenant path. One filter through OrganizationMember fixes it.

H7 — Rolling deploy: new backend to an old worker drops the message.

notify_resource_shared_with_group (workers/notification/tasks.py:528-535) has a closed signature. A message carrying share_action delivered to a pod on the previous build raises TypeError — terminal on Celery, burns the attempt cap on PG. The producer has already returned 200 to the user via _dispatch_quietly, so nothing surfaces. **_: Any on both new task signatures closes it.

Related: the "defaulted so messages enqueued before this field existed still validate" comments (internal_views.py:40, tasks.py:538) describe a state that never existed — both the task and share_action were added on this branch, so there are no in-flight messages. The defaults are fine to keep; the stated rationale is not, and it obscures the fact that the real hazard runs the other way.

H8 — Rollout ordering: PG transport with no consumer deployed.

_dispatch routes to the PG queue whenever resolve_transport says so, and the notification consumer is off by default. Any org with pg_queue_enabled ramped but the consumer not running gets messages durably stored and never executed — logged as "group-notification: %s enqueued on PG queue %r (msg_id=%s)" at INFO, which reads as delivery. Needs to be an explicit ordering constraint in Env Config, not an inference. (Chart side on the cloud PR.)


Medium

  • Dead exception handler. The except Exception in _feature_enabled (share_notifications.py:164-170) can never fire — both check_feature_flag_status and FliptClient.evaluate_boolean catch and return False first. Remove it or stop relying on it.
  • The default Flipt path logs nothing. FLIPT_SERVICE_AVAILABLE != "true" at :154 returns False with zero logging, and that is the default. Combined with H5's collapsed guard, "I ramped the flag and no email arrived" has no log line distinguishing which of four causes applied.
  • recipient_count is post-filter only. group_notification_service.py:93-99 and :144-150 log the surviving count; the requested count is never logged, and _groups_in_org / _live_member_users both drop silently. "Half my team didn't get it" is unfalsifiable from logs. Log requested / resolved / dropped.
  • 2N+1 on the group fan-out. :89-92 runs one values_list plus one OrganizationMember query per group. Collapse to a single GroupMembership.objects.filter(group__in=…).select_related("user", "group") grouped in Python.
  • Over the 30-line ceiling (CLAUDE.md): send_resource_shared 40, _post_group_notification 35, send_membership_changed 31.
  • _notification_context is duplicated. The module-level function at resource_share_views.py:62 is a line-for-line copy of OwnerManagementMixin._notification_context (permissions/membership_views.py:88). Two copies that will drift, and their docstrings already contradict each other on whether hosts override get_notification_resource_type — all seven do.
  • Docstrings that misstate contracts:
    • internal_views.py:8-10 — "non-2xx so the queue redelivers" holds only on the PG transport; on Celery a raise is terminal, as tasks.py:471-472 itself says.
    • tasks.py:481-487 — self-contradictory: "a 4xx is not retried" versus "the raise leaves the message on the queue for redelivery". The break at :513 still falls through to the raise at :524. Also the guard is < 500, not 4xx.
    • share_notifications.py:9-10 — transport is resolved per resource, not per org: _dispatch passes the resource/group pk as execution_id, which is what resolve_transport buckets the rollout on.
    • resource_share_views.py:3-6 — the mixin is no longer axis-agnostic (the share_axes ClassVar is gone and _read_axis hardcodes both names), and it does not read _SUPPORTED_SHARE_AXES — only _extract_desired_share_state does.
  • Frontend, partial-failure UX contradicts itself. CoOwnerManagement.jsx keeps the modal open on partial failure "so the user can see what was rejected and retry", but onApplyCoOwners always calls refreshCoOwnerData first, and the useEffect re-seeds selectedOwners from the refreshed roster — so the staged edits are already wiped and there is nothing to retry from.

Verified clean

The dead-code removal holds up: the shared_users M2Ms were dropped by the UN-2202 migrations and every serializer now exposes shared_users as a read-only SerializerMethodField, so those partial_update hooks could never have fired. No references to share_axes, AxisDiff, snapshot_share_axes, or diff_share_axes remain in either repo.

Auth on the new internal endpoints is genuinely enforced — InternalAPIAuthMiddleware gates every /internal/ path before DRF runs, and the route is reachable in all three deployments. Org scoping on _load_resource / _groups_in_org / _live_member_users is correct. Every OSS→cloud ResourceType mapping checks out. The onApplyCoOwners rename is fully propagated across all 11 consumers in both repos.

_users_left_without_access is safe despite compute_effective_members excluding owners: ResourceMembership has UniqueConstraint(user, content_type, object_id), so a user is OWNER or VIEWER and never both. Reading the diffs after _commit is also safe — ATOMIC_REQUESTS defaults to False and is pinned False in the chart.

@kirtimanmishrazipstack
kirtimanmishrazipstack marked this pull request as ready for review August 5, 2026 08:55
@greptile-apps

greptile-apps Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR adds asynchronous notifications for direct and group-based access changes, consolidates direct-share notification wiring, and stages co-owner removals until Apply.

  • Adds organization-scoped internal endpoints and notification-worker tasks for group resource and membership events.
  • Revalidates live group access and effective recipient access before delivery, including revoke-time membership cutoffs.
  • Moves direct grant/revoke notification handling into the shared resource-sharing mixin.
  • Updates co-owner UI state management so additions and removals are applied together.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains; the previously reported stale-grant, retained-access, and late-join recipient issues are addressed by live access revalidation and the revoke-time membership cutoff.

Important Files Changed

Filename Overview
backend/tenant_account_v2/group_notification_service.py Resolves resources and recipients at delivery time, filters stale grants and retained access, and applies the revoke membership cutoff correctly.
backend/tenant_account_v2/share_notifications.py Feature-gates and dispatches group notification events while capturing revoke timestamps before external flag evaluation.
backend/permissions/resource_share_views.py Centralizes post-commit direct grant and revoke notifications while suppressing revokes for users retaining effective access.
backend/tenant_account_v2/internal_views.py Validates worker payloads, resolves organization context, and preserves retry behavior for transient failures.
workers/notification/tasks.py Adds thin Django-free worker callbacks for the new internal group-notification endpoints.
frontend/src/components/widgets/co-owner-management/CoOwnerManagement.jsx Stages co-owner changes locally so removals occur only when the user applies the modal.
frontend/src/hooks/useCoOwnerManagement.jsx Consolidates co-owner additions and removals into a single apply callback.

Sequence Diagram

sequenceDiagram
    participant User
    participant API as Django share/group API
    participant Queue as Notification queue
    participant Worker as Notification worker
    participant Internal as Internal notification API
    participant Email as Email service
    User->>API: Grant or revoke access
    API->>API: Commit sharing change
    API->>Queue: Enqueue notification event
    Queue->>Worker: Deliver task
    Worker->>Internal: POST event with organization context
    Internal->>Internal: Revalidate resource, group, and recipients
    Internal->>Email: Send notification to eligible recipients
    Internal-->>Worker: Success
Loading

Reviews (8): Last reviewed commit: "UN-3494 [TEST] Cover share/revoke notifi..." | Re-trigger Greptile

Comment thread backend/tenant_account_v2/group_notification_service.py Outdated

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (3)
frontend/src/components/widgets/co-owner-management/CoOwnerManagement.jsx (2)

140-142: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Set an explicit rowKey on the List.

List falls back to the array index when rowKey is absent. selectedOwners now changes by insertion and removal, so index keys make React reuse a row component for a different user. The key on the inner Popconfirm does not control List.Item reconciliation, so an open confirm popup can attach to the wrong row after a staged removal.

♻️ Proposed change
             <List
               dataSource={selectedOwners}
+              rowKey={(item) => item?.id}
               renderItem={(item) => (
🤖 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 `@frontend/src/components/widgets/co-owner-management/CoOwnerManagement.jsx`
around lines 140 - 142, Update the List rendering in CoOwnerManagement to
provide an explicit rowKey based on each selected owner’s stable unique
identifier, rather than allowing index-based keys. Keep the existing renderItem
and Popconfirm behavior unchanged.

114-119: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Close and Cancel stay active during Apply.

confirmLoading disables the OK button only. The close icon and the Cancel button remain clickable while applying is true. The user can dismiss the modal while requests are in flight. The requests still complete and the alert still appears, so the outcome is not lost, but the state is confusing.

Disable both controls while applying is true.

♻️ Proposed change
       confirmLoading={applying}
       okButtonProps={{ disabled: !hasChanges }}
+      cancelButtonProps={{ disabled: applying }}
       maskClosable={false}
       centered
-      closable={true}
+      closable={!applying}
🤖 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 `@frontend/src/components/widgets/co-owner-management/CoOwnerManagement.jsx`
around lines 114 - 119, Update the CoOwnerManagement modal configuration so both
the close control and Cancel action are disabled while applying is true, while
preserving the existing confirmLoading behavior. Use the existing applying state
in the modal’s closable and cancel-button properties.
frontend/src/hooks/useCoOwnerManagement.jsx (1)

19-22: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Guard the zero-change call in the hook.

If addUsers and removeUsers are both empty, total is 0 and failed.length === total is true. buildApplyAlert then calls handleException(null, "Unable to update co-owners") and shows an error alert for a no-op. CoOwnerManagement.handleApply currently blocks this case, but the hook is a shared export and should not depend on that caller guard.

♻️ Proposed guard
   const total = addUsers.length + removeUsers.length;
-  if (failed.length === total) {
+  if (total === 0) {
+    return null;
+  }
+  if (failed.length === total) {
     return handleException(lastError, "Unable to update co-owners");
   }

setAlertDetails would then need to skip a null alert in onApplyCoOwners.

🤖 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 `@frontend/src/hooks/useCoOwnerManagement.jsx` around lines 19 - 22, Guard the
zero-change case in the hook’s apply-result handling before comparing
failed.length with total: when both addUsers and removeUsers are empty, skip
error handling and avoid calling handleException with null. Update the related
onApplyCoOwners alert flow as needed so setAlertDetails does not process a null
alert, while preserving failure handling for actual changes.
🤖 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 `@backend/tenant_account_v2/share_notifications.py`:
- Around line 150-170: Update the internal sender flow after organization
resolution to call _feature_enabled again before delivering the notification.
When the flag is disabled or Flipt is unavailable, skip delivery and return the
existing successful skipped response, preserving normal sending when the flag
remains enabled.

In `@docker/docker-compose.yaml`:
- Around line 854-857: Update the notification worker visibility-timeout
configuration around WORKER_PG_QUEUE_CONSUMER_VT_SECONDS to account for up to
three 30-second POST attempts with HTTPTransport retries=2, ensuring the
configured timeout exceeds the worst-case transport retry duration; keep
WORKER_PG_QUEUE_CONSUMER_HEALTH_STALE_SECONDS above the resulting visibility
timeout.

In `@frontend/src/hooks/useCoOwnerManagement.jsx`:
- Around line 144-155: Update refreshCoOwnerData and its caller in the apply
flow so it returns whether the resource-not-found (404) branch was reached;
after awaiting refreshCoOwnerData, only call setAlertDetails with
buildApplyAlert when that result indicates no 404 occurred, preserving the
existing resource-gone alert and modal/list behavior.

In `@workers/notification/tasks.py`:
- Around line 503-524: Add an immutable job ID to each notification task and
propagate it through the internal notification API and payload. In the backend
handler, deduplicate requests using that job ID before invoking the notification
plugin, recording successful delivery so retries and PG queue redelivery do not
send the same notification again. Update the retry flow around client.post and
the corresponding task/API symbols while preserving existing retry behavior for
failed deliveries.

---

Nitpick comments:
In `@frontend/src/components/widgets/co-owner-management/CoOwnerManagement.jsx`:
- Around line 140-142: Update the List rendering in CoOwnerManagement to provide
an explicit rowKey based on each selected owner’s stable unique identifier,
rather than allowing index-based keys. Keep the existing renderItem and
Popconfirm behavior unchanged.
- Around line 114-119: Update the CoOwnerManagement modal configuration so both
the close control and Cancel action are disabled while applying is true, while
preserving the existing confirmLoading behavior. Use the existing applying state
in the modal’s closable and cancel-button properties.

In `@frontend/src/hooks/useCoOwnerManagement.jsx`:
- Around line 19-22: Guard the zero-change case in the hook’s apply-result
handling before comparing failed.length with total: when both addUsers and
removeUsers are empty, skip error handling and avoid calling handleException
with null. Update the related onApplyCoOwners alert flow as needed so
setAlertDetails does not process a null alert, while preserving failure handling
for actual changes.
🪄 Autofix

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b71cb647-64c1-4252-a93d-5996186b95b2

📥 Commits

Reviewing files that changed from the base of the PR and between 1c737df and 3392ebe.

📒 Files selected for processing (22)
  • backend/adapter_processor_v2/views.py
  • backend/api_v2/api_deployment_views.py
  • backend/backend/internal_base_urls.py
  • backend/connector_v2/views.py
  • backend/permissions/resource_share_views.py
  • backend/pipeline_v2/views.py
  • backend/prompt_studio/prompt_studio_core_v2/views.py
  • backend/tenant_account_v2/group_notification_service.py
  • backend/tenant_account_v2/group_views.py
  • backend/tenant_account_v2/internal_urls.py
  • backend/tenant_account_v2/internal_views.py
  • backend/tenant_account_v2/share_notifications.py
  • backend/tenant_account_v2/shareable_resources.py
  • backend/workflow_manager/workflow_v2/views.py
  • docker/docker-compose.yaml
  • frontend/src/components/deployments/api-deployment/ApiDeployment.jsx
  • frontend/src/components/pipelines-or-deployments/pipelines/Pipelines.jsx
  • frontend/src/components/widgets/co-owner-management/CoOwnerManagement.css
  • frontend/src/components/widgets/co-owner-management/CoOwnerManagement.jsx
  • frontend/src/components/widgets/co-owner-management/CoOwnerModal.jsx
  • frontend/src/hooks/useCoOwnerManagement.jsx
  • workers/notification/tasks.py
💤 Files with no reviewable changes (7)
  • frontend/src/components/widgets/co-owner-management/CoOwnerManagement.css
  • backend/prompt_studio/prompt_studio_core_v2/views.py
  • backend/pipeline_v2/views.py
  • backend/api_v2/api_deployment_views.py
  • backend/workflow_manager/workflow_v2/views.py
  • backend/adapter_processor_v2/views.py
  • backend/connector_v2/views.py

Comment thread backend/tenant_account_v2/share_notifications.py
Comment thread docker/docker-compose.yaml Outdated
Comment thread frontend/src/hooks/useCoOwnerManagement.jsx
Comment thread workers/notification/tasks.py
kirtimanmishrazipstack and others added 3 commits August 5, 2026 17:23
Group revoke no longer mails members who kept access another way. The revoke
recipient list now runs through the same effective-access filter the direct
path uses, with owners folded in — compute_effective_members excludes them by
design, and the sharer is usually a member of the group they shared with, so
revoking told the owner their own access was removed and pointed them at the
dashboard.

- _get_user is org-scoped through OrganizationMember, the one unscoped query
  left on this tenant path. Service accounts are kept so a platform-account
  share still notifies.
- _notify_shared_users is wrapped: the share has already committed by the time
  it runs, so a raising seam or a DB hiccup must not 500 a share that worked.
- _users_left_without_access short-circuits on shared_to_org — nobody lost
  access, and answering it otherwise hydrates every member of the org.
- _notification_context loses its duplicate copy and uses the
  OwnerManagementMixin definition every host already inherits.
- Logs the Flipt decision, and how many recipients were dropped versus
  requested, so a missing email is diagnosable.
- Docstrings corrected: the mixin is not axis-agnostic, transport resolves per
  resource id not per org, the flag is evaluated once at enqueue, and delivery
  is at-least-once.
- Sonar S7632: the noqa directive carried trailing prose.
- Co-owner apply no longer overwrites the resource-gone alert with its summary.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…vice

The PG-queue notification consumer is local dev config and does not belong in
the PR. The k8s chart already carries workerPgNotification from UN-3445 (#1688),
which is the real deployment surface.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@kirtimanmishrazipstack

Copy link
Copy Markdown
Contributor Author

Self-review dispositions (OSS)

Re-verified every finding from my review above against the code, with an independent adversarial pass on each verdict. Five of my own findings did not survive and are withdrawn below rather than quietly dropped.

Code changes in c1d3095; the compose service removal in 9e9f57c.

Fixed

B2 group revoke ignores remaining access _retained_user_ids filters the revoke recipients through compute_effective_members, owners folded in. Details in the Greptile thread.
H1 share() can 500 a committed share _notify_shared_users wrapped. The two inner handlers stay — dropping them would couple the grant and revoke sends, so a raise in the first would silently skip the second.
H3 unbounded org-member scan _users_left_without_access short-circuits on shared_to_org: nobody lost access, so there is nothing to compute.
H6 _get_user org-unscoped Scoped through OrganizationMember. Deliberately not reused _live_member_users — it filters service accounts, so a platform-account share would have sent zero emails.
H8 rollout ordering Env Config now points at the cloud PR, which owns values.yaml and carries the runbook.
M Flipt path logs nothing Blind-Flipt at WARNING, flag-off at INFO.
M recipient_count post-filter only _live_member_users logs dropped-of-requested.
M _notification_context duplicated Copy deleted; hosts use the OwnerManagementMixin definition they already inherit.
M docstrings misstate contracts All four corrected, by deletion where possible.
M over the 30-line ceiling send_resource_shared 40 → 27. _post_group_notification (35) and send_membership_changed (31) left alone — the first reads as one retry unit and sits next to pre-existing 51-, 67- and 82-line siblings; carving it up while those stand is arbitrary.

Withdrawn — my findings, wrong

  • B1 "every send result is discarded, nothing above DEBUG." The mechanics are right but the consequence is not. Walking all ten False-producing branches, every one logs at INFO or higher — a SendGrid non-202 is an ERROR in email_service.py. And "any unhandled problem must surface as non-2xx" is not inverted: a caught-and-returned False is handled, and real exceptions still reach 500. The remedy would also have been harmful — non-2xx on a config cause (ENABLE_EMAIL_NOTIFICATIONS defaults False) storms until the attempt cap on every share, and non-2xx after a partial send re-mails the groups that already succeeded.
  • H5 "lookups are group-shareable but get no group email." They are not group-shareable. LookupDefinition.for_user is the only share host that never calls resources_visible_via_groups, the viewset is IsOrganizationMember rather than IsOwnerOrSharedUserOrSharedToOrg, and the only client hardcodes shared_groups: []. Registering it would advertise access that does not exist.
  • H7 "rolling deploy drops the message." The tasks are new on this branch, so an older pod has no registration at all — the PG consumer hits its unknown-task branch and **_: Any is never reached. My note that the "defaulted so in-flight messages still validate" comments describe a state that never existed was correct, and that wording is gone from the PR description.
  • M "2N+1 on the group fan-out." Correct count, but the single-query fix drops the OrganizationMember re-validation, which is the documented offboarding-race close — leaving a group does not delete GroupMembership rows, so it would mail ex-org-members. Correctness regression for ~20 indexed lookups in a background worker.
  • M "frontend partial-failure UX contradicts itself." Staged edits are wiped, but the refreshed roster is a working retry surface and the warning toast names the failures. Behaviour is coherent; only half a comment sentence was loose.

Not changing

  • H2 sync SendGrid call on POST /share/. Premise confirmed — the old partial_update home was dead twice over, so this is newly-introduced latency. Worth its own ticket rather than reshaping the direct path inside this PR.
  • H4 direct-share revoke has no feature flag. Not gating it. The flag is literally named group_sharing_notifications_enabled; _feature_enabled returns False whenever Flipt is unavailable, so on-prem installs without Flipt would permanently lose the restored direct mail with no log line; and membership_views already ships the co-owner add/remove mail un-gated on main, so gating one route and not its sibling is the trap, not the fix. Corrected the claims instead — the module docstring and the PR description now state exactly which paths the flag covers.
  • M dead exception handler in _feature_enabled. Unreachable today, but transport.py and scheduler/ownership.py carry the identical defensive wrap on main with the rationale in-code. It also guards a call made outside _dispatch_quietly, so a future change to check_feature_flag_status would break a user-facing share request. Convention, kept.

… revoked

A revoke resolves recipients from the group's live membership at delivery
time, so anyone who joined between the click and the send was told their
access was removed for a group through which they never held it. Normally a
few seconds; on the PG transport with no consumer deployed the backlog can
sit far longer.

The revoke now carries the timestamp of the change and delivery drops
memberships created after it. One string on the payload rather than the frozen
member list, which would grow with the group.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Comment thread backend/tenant_account_v2/group_notification_service.py Outdated
…ready gone

A grant enqueued before a revoke could still be delivered after it, mailing the
resource name and id to members who can no longer reach the resource. Delivery
now revalidates the live ResourceGroupShare on the grant direction and drops
groups that no longer hold it.

The revoke direction needs no equivalent check — its share row is gone by
delivery, and _retained_user_ids already covers members who kept access
another way.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Comment thread backend/tenant_account_v2/group_notification_service.py
@kirtimanmishrazipstack

Copy link
Copy Markdown
Contributor Author

@greptileai review

Comment thread backend/tenant_account_v2/share_notifications.py Outdated
revoked_at was captured after _feature_enabled(), so the window between the
share-removal commit and the timestamp spanned a Flipt network call. A user
joining the group inside it passed the cutoff and was mailed a revocation.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@kirtimanmishrazipstack
kirtimanmishrazipstack force-pushed the UN-3494-group-sharing-notification branch from 965f4d2 to 70b42c8 Compare August 5, 2026 14:15
@kirtimanmishrazipstack

Copy link
Copy Markdown
Contributor Author

@greptileai please review

Enqueue side (unit tier, no DB): payload shape, the revoked_at stamp
landing before the Flipt round-trip, and the skip/swallow paths.

Delivery side (integration tier): recipient selection - the live re-read
on a grant, the revoked_at cutoff, org scoping and retained access - plus
the direct-user share/revoke wiring on the share endpoint.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Frontend Lint Report (Biome)

All checks passed! No linting or formatting issues found.

@sonarqubecloud

sonarqubecloud Bot commented Aug 5, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Unstract test results

Per-group results

Status Group Tier Passed Failed Errors Skipped Duration (s)
e2e-api-deployment e2e 3 0 0 0 20.5
e2e-coowners e2e 1 0 0 0 1.3
e2e-etl e2e 1 0 0 0 8.2
e2e-login e2e 2 0 0 0 1.3
e2e-prompt-studio e2e 1 0 0 0 4.6
e2e-smoke e2e 2 0 0 0 1.0
e2e-workflow e2e 1 0 0 0 16.6
integration-backend integration 216 0 0 26 41.1
integration-connectors integration 1 0 0 7 7.8
integration-workers integration 140 0 0 1 50.5
unit-backend unit 310 0 0 1 38.1
unit-connectors unit 63 0 0 0 9.8
unit-core unit 33 0 0 0 1.4
unit-platform-service unit 15 0 0 0 2.7
unit-rig unit 109 0 0 0 5.3
unit-sdk1 unit 480 0 0 0 26.1
unit-workers unit 1335 0 0 1 97.2
TOTAL 2713 0 0 36 333.5

Critical paths

⚠️ Critical paths not yet covered

  • workflow-execution-fan-out — Multi-file workflow execution fans out to file-processing workers and rejoins. (declared coverage: no groups declared)
✅ Covered critical paths
  • auth-login — covered by e2e-login
  • adapter-register-llm — covered by integration-backend
  • workflow-author — covered by integration-backend
  • co-owner-manage — covered by integration-backend, e2e-coowners
  • workflow-create-execute — covered by e2e-workflow
  • api-deployment-provision — covered by integration-backend
  • api-deployment-auth — covered by integration-backend
  • api-deployment-run — covered by e2e-api-deployment
  • prompt-studio-author — covered by integration-backend
  • prompt-studio-fetch-response — covered by e2e-prompt-studio
  • connector-register-test — covered by integration-backend
  • pipeline-etl-execute — covered by e2e-etl
  • usage-aggregate-read — covered by integration-backend
  • usage-token-tracking — covered by e2e-api-deployment
  • callback-result-delivery — covered by e2e-api-deployment

@kirtimanmishrazipstack
kirtimanmishrazipstack marked this pull request as draft August 5, 2026 16:50
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