Skip to content

feat: implement UpdateCurrentUserPAT RPC#1467

Merged
AmanGIT07 merged 2 commits intomainfrom
feat/update-current-user-pat
Mar 23, 2026
Merged

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

Conversation

@AmanGIT07
Copy link
Copy Markdown
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
Copy Markdown

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
Copy Markdown
Contributor

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
Copy Markdown

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
Copy Markdown
Contributor

@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

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.

3 participants