Skip to content

feat: enhance-realtime-authorization - #620

Merged
pikann merged 2 commits into
masterfrom
feature/enhance-realtime-authorization
Oct 21, 2026
Merged

pikann merged 2 commits into
masterfrom
feature/enhance-realtime-authorization

Conversation

@pikann

@pikann pikann commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Redesigns how services/realtime authorizes live events so it follows the API's IAM authorization instead of approximating it.

Before: a socket joined project-wide rooms from the account's project-wide actions, and everything in a room was delivered to everyone in it. Only conversations were checked per entity. So a Deny on one task, or a role limited to one sprint's tasks, was not honoured by live events (a leak in one case, no updates at all in the other). Permissions were a snapshot taken at join, a role edit or removed member had no effect on an open socket, a socket outlived its access token, and the event-to-permission mapping lived separately in TypeScript.

Now: the API stays the only decision-maker and realtime only asks it and caches the answers.

  1. Events say what they need. Every realtime message carries authz: {action, resource} (for example tasks:read on project/<p>/task/<id>), derived in events.AuthzFor. TestEveryTopicIsClassified fails when a topic has neither a rule nor an explicit "not realtime" entry, so a new topic cannot skip IAM.
  2. Rooms prefilter, each event is checked. A socket joins the rooms its effective actions allow (including actions granted only on some resource). For each event the candidate sockets are checked against POST /projects/{id}/members/me/permissions/check, as that socket's own account, using the same IAM engine as the REST gates. Questions from one event-loop turn share one request, answers are cached 30s, failures deliver nothing, and events of one resource stay in order.
  3. Changes take effect on open sockets. The API publishes iam.changed when a role, an attachment, a membership or an account changes. Realtime drops its cached answers, re-syncs room membership and emits permissions:changed (a 60s resync is the backstop for a missed message).
  4. A socket never outlives its token. reauth is sent about a minute before expiry and the socket is disconnected at expiry, from one shared scan rather than a timer per socket.
  5. No persisted sessions. The write-only Valkey session store is removed.

What changed

services/api

  • events/authz.go: Authz, AuthzFor, PublishRealtime. Fanout and the direct publishers (view, environment, automation) use the new envelope.
  • POST .../members/me/permissions/check: ProbeAccess middleware evaluates through the new Authorizer.AuthorizeMany (grants read once per batch). It reports and gates nothing, like the other "my permissions" routes, and the handler only writes the answers.
  • events/iam.go: NotifyIAMChanges wraps the authorizer's invalidator, wired for role edits and attachment changes, and for removing a member or agent and deleting a user, agent, service account or project.
  • Removed the unused ProjectWideActions and ?scope=project.

services/agent-runner: PublishRealtime attaches conversations:read on the conversation for project-shared conversations. The API derives the same for agent.session.started.

services/realtime: access.ts (decider, batching, per-resource queue), subscriber.ts (routes on authz), rooms.ts, resync.ts, token-expiry.ts; join is acked with the granted namespaces; new views room (views:read). Replaces conversation-access.ts; deletes session.ts.

apps/web: answers reauth (refresh then reconnect, with one shared refresh request so the rotating refresh token is used once), records the join ack and retries an unacked join, refetches permissions on permissions:changed (and the whole project when a namespace was lost), and refetches the project after a reconnect once the rejoin is acked.

Docs: docs/architecture/authorization.md ("Realtime events"), docs/architecture/service-boundaries.md, the two API docs, and the realtime README.

Behaviour changes to be aware of

  • view.* events now require views:read on the view, matching the REST routes. Realtime previously used sprints:read.
  • fetchProjectPermissions previously threw a plain Error, so the "401 on join, then disconnect" path never fired. It now throws ApiRequestError.
  • Project events published without an authz descriptor (a publisher that predates it) fall back to the old prefix routing and are logged once per type. agent.* conversation events without one are checked as conversations:read on the conversation.
  • Owner-private and global agent conversations, notifications and the ACP bridge status are still routed to their owner's or recipient's own room.

Testing

  • API go vet and go test ./... pass; the Go e2e suite (PACA_E2E=1) passes.
  • agent-runner messaging tests, realtime (tsc, biome, 39 tests) and web (tsc -b, biome, vitest) pass.
  • Run against the dev stack with real sockets (26 checks): a Deny on one task stops that task's events for the account while it still gets the rest; role edits take effect on an open socket without reconnecting; an Allow limited to one task still places the account in the room; a short-lived token gets reauth and is disconnected at expiry; removing a member and deleting a user both take the account out of every room.
  • That run also caught that removing a member published no iam.changed; fixed, with tests for every removal and deletion path.
  • Not run: the Playwright specs in apps/e2e, so the web client's reauth and reconnect handling is covered by unit tests and the server-side run, not by a real browser.

Type of Change

  • Other (realtime authorization)

Checklist

  • The change is focused and scoped.
  • Related documentation is updated.
  • New structure or direction is explained clearly.
  • I avoided unnecessary detail or premature abstraction.

🤖 Generated with Claude Code

- Removed the session management logic that persisted session data in Valkey.
- Updated the socket connection logic to handle token expiry in memory.
- Introduced ExpiryWatcher to manage token expiration and reauthentication.
- Enhanced event routing to utilize authorization descriptors for event delivery.
- Added tests for the new token expiry handling and event routing logic.

@pullfrog pullfrog 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.

ℹ️ No critical issues — one minor suggestion inline.

Reviewed changes

  • Event envelopes now carry IAM metadata. services/api/internal/events/authz.go adds Authz, AuthzFor and PublishRealtime; Fanout and the direct view/environment/automation publishers emit authz via realtimeMessage, and TestEveryTopicIsClassified forces a rule (or an explicit notRealtimeTopics entry) for every topic.
  • Batched access probe. New POST /projects/{id}/members/me/permissions/check (CheckMyAccess + middleware.ProbeAccess over iam.Authorizer.AuthorizeMany) evaluates {action, resource} pairs as the caller, resources constrained to the URL project, gating nothing.
  • Realtime consumes authz. New access.ts (cached, batched, fail-closed decider; per-resource KeyedQueue; 401 disconnect), subscriber.ts routing on the descriptor with an explicit prefix fallback, rooms.ts, resync.ts (on iam.changed/60s), token-expiry.ts; conversation-access.ts and the Valkey session.ts are deleted.
  • iam.changed wiring. events.NotifyIAMChanges wraps the invalidator and is threaded through bootstrap/app.go to role, project, agent, service-account and user services.
  • Web client. Join-ack recording + retry, permissions:changed handling, reauth via a shared refreshSession, and reconnect refetch in use-project-realtime.ts.
  • Behavior changes: view.* now views:read; ProjectWideActions / ?scope=project removed; rooms join on EffectiveActions (child-only grants included) with per-event enforcement.

I read the full diff, traced the security-critical paths (the per-event check uses each socket's own account/token, the resource comes from authz not the payload, unknown actions drop, API failure fails closed, and task activities set TaskID so a task-scoped Deny applies), and confirmed go build ./... and the changed Go tests pass locally. The realtime TS tests were not re-run here (dependencies not installed); note the author did not run the apps/e2e Playwright specs, so the browser-side reauth/reconnect handling rests on unit tests.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

Comment thread services/realtime/src/resync.ts Resolved
- services/api: put WithAuthorizer's doc comment back on WithAuthorizer and
  give WithGrantsNotifier its own; the misplaced comment failed revive in CI.
- services/realtime: a 401 for one socket token no longer disconnects every
  socket of the account. Try each distinct token, end only the sockets whose
  own token is rejected, and apply the accepted answer to the rest.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

Reviewed the delta since the prior pullfrog review at c61c81e: a per-token fix to the realtime resync path plus a Go doc-comment relocation.

  • resyncGroup re-syncs per token. A 401 for one socket's token no longer disconnects every socket of the account; the resync now tries each distinct token, ends only the sockets whose own token the API rejected, and applies the accepted answer to the rest.
  • New tests cover the split. A stale token beside a fresh one (only the stale socket ends, the healthy one is re-synced) and all tokens rejected (every socket ends).
  • Go doc comments relocated. WithAuthorizer's comment is back on WithAuthorizer and WithGrantsNotifier gets its own — the misplaced comment failed revive in CI.

The prior inline thread on resyncGroup is resolved by this change.

Pullfrog  | View workflow run | Using deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pikann
pikann merged commit 4ad93d8 into master Oct 21, 2026
12 checks passed
@pikann
pikann deleted the feature/enhance-realtime-authorization branch October 21, 2026 16:32
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