Skip to content

feat: implement UpdateCurrentUserPAT RPC#1467

Open
AmanGIT07 wants to merge 2 commits intomainfrom
feat/update-current-user-pat
Open

feat: implement UpdateCurrentUserPAT RPC#1467
AmanGIT07 wants to merge 2 commits intomainfrom
feat/update-current-user-pat

Conversation

@AmanGIT07
Copy link
Contributor

Description:

Summary

  • Add UpdateCurrentUserPAT RPC to replace a PAT's title, metadata, and scope (roles + projects)
  • Scope changes use revoke-all + recreate pattern with TOCTOU guard against concurrent Delete
  • Audit record captures old and new state (title, role_ids, project_ids)

Changes

  • Proto: UpdateCurrentUserPAT RPC, request (UUID-validated id, title, role_ids, project_ids, metadata), response with updated PAT
  • Repository: Update method — updates title + metadata, returns updated row via RETURNING, handles ErrNotFound/ErrConflict
  • Service: Update method with helpers: getOwnedPAT, captureOldScope, replacePolicies, auditUpdate
  • Handler: principal auth, validation (same rules as Create), error mapping (FailedPrecondition/NotFound/AlreadyExists/InvalidArgument/Internal)
  • Authorization: added to skip endpoints (ownership enforced in service layer)
  • Audit: added PATUpdatedEvent with old_title, old_role_ids, old_project_ids in metadata
  • Tests: 10 service test cases, 8 handler test cases

Manual test verification

  • PAT title, metadata, and scope updated correctly in Postgres after RPC call
  • Invalid inputs (missing title, bad role IDs, non-existent PAT) return appropriate error codes
  • Audit record created with pat.updated event, including old and new title, role_ids, and project_ids
  • Old SpiceDB tuples removed and new tuples created matching updated scope (verified via script)
  • API calls using the updated PAT enforce new scope — permissions granted/denied match the updated roles and projects

@vercel
Copy link

vercel bot commented Mar 20, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
frontier Ready Ready Preview, Comment Mar 20, 2026 6:01am

@coderabbitai
Copy link

coderabbitai bot commented Mar 20, 2026

Warning

Rate limit exceeded

@AmanGIT07 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 3 minutes and 22 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8ebe78c1-5c98-4db6-bc0c-c3ad07b304ce

📥 Commits

Reviewing files that changed from the base of the PR and between df6dddb and 2b9782b.

📒 Files selected for processing (1)
  • internal/api/v1beta1connect/user_pat_test.go
📝 Walkthrough

Walkthrough

This PR adds Personal Access Token (PAT) update functionality across the stack: repository interface and PostgreSQL implementation, service layer with validation and policy management, Connect RPC handler with error mapping, proto message validation, interface mocks, and audit event tracking. The Makefile's PROTON_COMMIT hash is updated to enable proto regeneration.

Changes

Cohort / File(s) Summary
Core PAT Service Layer
core/userpat/service.go, core/userpat/service_test.go, core/userpat/userpat.go, core/userpat/mocks/repository.go
Added Service.Update() method with validation, role resolution, policy replacement, and audit logging. Introduced helper methods (getOwnedPAT, captureOldScope, replacePolicies, auditUpdate). Extended repository interface with Update() and added mock implementation. Comprehensive test coverage for success and error scenarios.
API Handler & Interface Mocks
internal/api/v1beta1connect/user_pat.go, internal/api/v1beta1connect/user_pat_test.go, internal/api/v1beta1connect/interfaces.go, internal/api/v1beta1connect/mocks/user_pat_service.go
Added UpdateCurrentUserPAT RPC handler with authentication, validation, error mapping to Connect codes, and audit logging. Extended UserPATService interface and created mock implementation. Handler tests verify error cases and success flow with correct response transformation.
Proto & Generated Code
proto/v1beta1/frontier.pb.validate.go, proto/v1beta1/frontierv1beta1connect/frontier.connect.go
Generated validation for UpdateCurrentUserPATRequest (UUID, title, role/project IDs) and UpdateCurrentUserPATResponse. Generated Connect RPC procedure constant, client/handler interfaces, and unimplemented handler stub.
Database Layer
internal/store/postgres/userpat_repository.go
Added Update() method that persists PAT title and metadata changes, includes TOCTOU safety via RETURNING clause, and maps SQL errors to domain-specific error types (ErrNotFound, ErrConflict).
Audit & Security Configuration
pkg/auditrecord/consts.go, pkg/server/connect_interceptors/authorization.go, Makefile
Added PATUpdatedEvent audit event constant. Added UpdateCurrentUserPAT endpoint to authorization skip list. Updated PROTON_COMMIT hash for proto regeneration.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

  • rohilsurana
  • whoAbhishekSah
📝 Coding Plan
  • Generate coding plan for human review comments

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 and usage tips.

@coveralls
Copy link

coveralls commented Mar 20, 2026

Pull Request Test Coverage Report for Build 23331104157

Details

  • 99 of 145 (68.28%) changed or added relevant lines in 3 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage increased (+0.1%) to 40.957%

Changes Missing Coverage Covered Lines Changed/Added Lines %
internal/api/v1beta1connect/user_pat.go 38 44 86.36%
core/userpat/service.go 61 69 88.41%
internal/store/postgres/userpat_repository.go 0 32 0.0%
Totals Coverage Status
Change from base Build 23241230789: 0.1%
Covered Lines: 14480
Relevant Lines: 35354

💛 - Coveralls

@AmanGIT07 AmanGIT07 enabled auto-merge (squash) March 20, 2026 06:05
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (3)
internal/api/v1beta1connect/user_pat_test.go (1)

1066-1110: This happy-path test doesn't exercise the fields the RPC is supposed to update.

UserPATService.Update is matched with mock.Anything, the request omits ProjectIds/Metadata, and the assertions only check Id/Title. A handler regression that drops UserID, ProjectIds, or Metadata would still pass. Please match the outbound models.PAT and assert the response carries the updated scope/metadata as well.

core/userpat/service_test.go (1)

2061-2093: The happy path never proves stale policies are revoked.

This success case starts from an empty old scope, so a regression that appends new policies without deleting the old ones would still pass. Seed policySvc.List with at least one existing policy and assert the matching Delete calls before Create.

core/userpat/service.go (1)

233-239: Prefer auditing the effective scope from updated.

role_ids and project_ids here are taken from toUpdate, while the effective scope is already computed into updated on Lines 184-186. Using updated.RoleIDs / updated.ProjectIDs keeps the audit payload aligned with whatever normalization or scope pruning happened during policy replacement.

Suggested change
 func (s *Service) auditUpdate(ctx context.Context, updated patmodels.PAT, toUpdate patmodels.PAT, oldTitle string, oldRoleIDs []string, oldProjectIDs []string) {
 	if err := s.createAuditRecord(ctx, pkgAuditRecord.PATUpdatedEvent, updated, time.Now().UTC(), map[string]any{
-		"role_ids":        toUpdate.RoleIDs,
-		"project_ids":     toUpdate.ProjectIDs,
+		"role_ids":        updated.RoleIDs,
+		"project_ids":     updated.ProjectIDs,
 		"old_title":       oldTitle,
 		"old_role_ids":    oldRoleIDs,
 		"old_project_ids": oldProjectIDs,
 	}); err != nil {

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: e8928912-f18b-4e71-9aaa-6c9f876377b5

📥 Commits

Reviewing files that changed from the base of the PR and between 625d802 and df6dddb.

⛔ Files ignored due to path filters (1)
  • proto/v1beta1/frontier.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (14)
  • Makefile
  • core/userpat/mocks/repository.go
  • core/userpat/service.go
  • core/userpat/service_test.go
  • core/userpat/userpat.go
  • internal/api/v1beta1connect/interfaces.go
  • internal/api/v1beta1connect/mocks/user_pat_service.go
  • internal/api/v1beta1connect/user_pat.go
  • internal/api/v1beta1connect/user_pat_test.go
  • internal/store/postgres/userpat_repository.go
  • pkg/auditrecord/consts.go
  • pkg/server/connect_interceptors/authorization.go
  • proto/v1beta1/frontier.pb.validate.go
  • proto/v1beta1/frontierv1beta1connect/frontier.connect.go

Comment on lines +2024 to +2031
repo.EXPECT().Update(mock.Anything, mock.Anything).
Return(updatedPAT, nil)
// deletePolicies call
policySvc.EXPECT().List(mock.Anything, policy.Filter{
PrincipalID: "pat-1",
PrincipalType: schema.PATPrincipal,
}).Return(nil, errors.New("spicedb down")).Once()
return userpat.NewService(log.NewNoop(), repo, defaultConfig, nil, roleSvc, policySvc, nil)
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- Update flow and helper order ---'
rg -n -C5 'func \(.*Service\) Update|captureOldScope|replacePolicies|repo\.Update\(' core/userpat

echo
echo '--- Any compensating rollback / fail-closed logic ---'
rg -n -C3 'rollback|restore|reconcile|ErrDisabled' core/userpat/service.go

Repository: raystack/frontier

Length of output: 7677


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- replacePolicies and deletePolicies implementation ---'
sed -n '214,260p' core/userpat/service.go

echo
echo '--- deletePolicies method ---'
rg -n -A20 'func \(.*Service\) deletePolicies' core/userpat/service.go

echo
echo '--- Error handling in Update after repo.Update ---'
sed -n '171,195p' core/userpat/service.go

Repository: raystack/frontier

Length of output: 3881


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- Test at lines 2024-2031 (failure setup context) ---'
sed -n '2010,2045p' core/userpat/service_test.go

echo
echo '--- Test success path at 2061-2093 ---'
sed -n '2050,2100p' core/userpat/service_test.go

echo
echo '--- Full test case name around 2024-2031 ---'
sed -n '1980,2035p' core/userpat/service_test.go | grep -A 50 'func Test'

Repository: raystack/frontier

Length of output: 3650


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo '--- Test case name for lines 2024-2031 ---'
sed -n '1968,1980p' core/userpat/service_test.go

echo
echo '--- Verify if success test includes Delete assertion ---'
sed -n '2084,2115p' core/userpat/service_test.go

echo
echo '--- Check what the success test is checking ---'
grep -n 'should update successfully' core/userpat/service_test.go -A 50 | head -60

Repository: raystack/frontier

Length of output: 4557


repo.Update commits to Postgres before replacePolicies updates SpiceDB, creating a split-brain risk if the latter fails.

If deletePolicies or createPolicies fails (e.g., SpiceDB unavailable), the Postgres PAT row is already updated with new title/metadata while the authz state is stale or partially changed. The error is returned, but there is no rollback or compensating action. This leaves the PAT and its permissions in an inconsistent state.

Additionally, the success test (lines 2061–2093) does not exercise the old-policy revocation path because the old scope is empty. A test with pre-existing policies being replaced would better validate this critical path.

Comment on lines +171 to +178
updated, err := s.repo.Update(ctx, patmodels.PAT{
ID: toUpdate.ID,
Title: toUpdate.Title,
Metadata: toUpdate.Metadata,
})
if err != nil {
return patmodels.PAT{}, fmt.Errorf("updating PAT: %w", err)
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Update can return an error after persisting a partial state.

The read on Line 222 only proves the PAT existed at that instant; Delete can still soft-delete it before createPolicies runs, leaving orphaned policies behind. Also, because Lines 171-175 commit title/metadata before Line 217 removes the old bindings, any later delete/create failure returns an error after the PAT has already been mutated and can leave it with partial or empty scope. Please serialize Update/Delete on the PAT row (or version) and add compensation/swap semantics here instead of a standalone GetByID guard. Based on learnings, writes to the app DB and authz engine are non-atomic in core/userpat, so this path needs an explicit partial-failure safeguard.

Also applies to: 217-227

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.

2 participants