Skip to content

refactor: extract common helpers in PAT handler and service#1556

Merged
AmanGIT07 merged 4 commits intomainfrom
refactor/pat-handler-common-helpers
Apr 20, 2026
Merged

refactor: extract common helpers in PAT handler and service#1556
AmanGIT07 merged 4 commits intomainfrom
refactor/pat-handler-common-helpers

Conversation

@AmanGIT07
Copy link
Copy Markdown
Contributor

Description:

Summary

  • Extract mapPATError helper — single error-to-gRPC-code mapping replacing 8 duplicate switch blocks in PAT handlers
  • Extract getLoggedInPrincipalWithUser helper — replaces repeated GetLoggedInPrincipal + nil check across 5 handlers
  • Extract createPATPolicy helper in service — single policy creation method replacing repeated policy.Policy struct building
  • Define supportedPATResourceTypes package-level var replacing 3 hardcoded []string{OrganizationNamespace, ProjectNamespace}
  • Replace custom applySort with shared utils.AddRQLSortInQuery + default sort fallback
  • Use explicit schema.RoleGrantRelationName instead of relying on DB default for grant relation
  • Proto: updated

Test plan

  • go build ./... passes
  • make lint-fix — 0 issues
  • All existing tests pass (3 test expectations updated to match enriched error messages)

@vercel
Copy link
Copy Markdown

vercel Bot commented Apr 20, 2026

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

Project Deployment Actions Updated (UTC)
frontier Ready Ready Preview, Comment Apr 20, 2026 0:24am

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 20, 2026

Warning

Rate limit exceeded

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

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 42 minutes and 12 seconds.

⌛ 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: 939b9d43-5fb0-4d41-a6d8-bbe76b712005

📥 Commits

Reviewing files that changed from the base of the PR and between 9619c38 and 8e08f61.

📒 Files selected for processing (3)
  • core/userpat/service.go
  • core/userpat/service_test.go
  • internal/api/v1beta1connect/user_pat_test.go
📝 Walkthrough

Walkthrough

This PR updates the Proton dependency hash in the Makefile and refactors Personal Access Token (PAT) service, API handler, and repository code to consolidate policy creation logic, centralize error mapping, and delegate sort operations to external utilities, while updating associated tests.

Changes

Cohort / File(s) Summary
Dependency Update
Makefile
Updated PROTON_COMMIT variable to new hash for protobuf code generation.
Service Refactoring
core/userpat/service.go, core/userpat/service_test.go
Introduced supportedPATResourceTypes constant, centralized policy creation via createPATPolicy helper, and refactored createOrgScopedPolicy and createProjectScopedPolicies to delegate to the helper; updated mock expectations to include GrantRelation field.
API Handler Refactoring
internal/api/v1beta1connect/user_pat.go, internal/api/v1beta1connect/user_pat_test.go
Added getLoggedInPrincipalWithUser() for centralized principal retrieval and mapPATError() for unified error mapping across PAT handlers; updated handlers to use consolidated error mapping and removed duplicated auth/error handling logic; adjusted test expectations to match wrapped error context.
Repository Refactoring
internal/store/postgres/userpat_repository.go
Delegated RQL sort construction to utils.AddRQLSortInQuery utility and removed local applySort method; added explicit default ORDER BY created_at DESC when sort is empty.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Suggested reviewers

  • whoAbhishekSah
  • rohilsurana

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.

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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/store/postgres/userpat_repository.go (1)

122-140: ⚠️ Potential issue | 🟡 Minor

Potential nil-pointer dereference on rqlQuery in List.

buildPATFilteredQuery guards against rqlQuery == nil by reassigning the parameter to a new rql.Query, but that reassignment is local (Go passes the pointer by value). The outer rqlQuery in List is unaffected, so the subsequent utils.AddRQLSortInQuery(..., rqlQuery) at Line 133 and rqlQuery.Sort access at Line 137 will panic if a caller passes nil.

Consider initializing the query once at the top of List, or having buildPATFilteredQuery return the (possibly-substituted) *rql.Query along with the statement:

🛡️ Proposed fix
 func (r UserPATRepository) List(ctx context.Context, userID, orgID string, rqlQuery *rql.Query) (models.PATList, error) {
+	if rqlQuery == nil {
+		rqlQuery = utils.NewRQLQuery("", utils.DefaultOffset, utils.DefaultLimit, []rql.Filter{}, []rql.Sort{}, []string{})
+	}
 	baseStmt, err := r.buildPATFilteredQuery(userID, orgID, rqlQuery)

…and drop the redundant nil guard inside buildPATFilteredQuery.

🧹 Nitpick comments (2)
core/userpat/service.go (2)

608-621: Minor: simplify createPATPolicy body.

The if err != nil { return err }; return nil can collapse to a single return of the call's error:

♻️ Proposed tweak
 func (s *Service) createPATPolicy(ctx context.Context, patID, roleID, resourceID, resourceType, grantRelation string) error {
-	if _, err := s.policyService.Create(ctx, policy.Policy{
+	_, err := s.policyService.Create(ctx, policy.Policy{
 		RoleID:        roleID,
 		ResourceID:    resourceID,
 		ResourceType:  resourceType,
 		PrincipalID:   patID,
 		PrincipalType: schema.PATPrincipal,
 		GrantRelation: grantRelation,
-	}); err != nil {
-		return err
-	}
-	return nil
+	})
+	return err
 }

30-35: Optional: make supportedPATResourceTypes immutable.

As a package-level slice, it is mutable and vulnerable to accidental modification (e.g., append aliasing) from any function in the package. Only read-sites exist today, so the risk is low, but since the value is logically a constant set, consider one of:

  • A small accessor that returns a fresh slice, or
  • A map[string]struct{} plus an exported helper if membership-test is the only use (both validateScopes and ListAllowedRoles only call slices.Contains on it).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 34e0aeea-edf8-409d-ad5a-b3e0119da98a

📥 Commits

Reviewing files that changed from the base of the PR and between d967c88 and 9619c38.

⛔ Files ignored due to path filters (4)
  • proto/v1beta1/admin.pb.go is excluded by !**/*.pb.go, !proto/**
  • proto/v1beta1/frontier.pb.go is excluded by !**/*.pb.go, !proto/**
  • proto/v1beta1/frontierv1beta1connect/admin.connect.go is excluded by !proto/**
  • proto/v1beta1/frontierv1beta1connect/frontier.connect.go is excluded by !proto/**
📒 Files selected for processing (6)
  • Makefile
  • core/userpat/service.go
  • core/userpat/service_test.go
  • internal/api/v1beta1connect/user_pat.go
  • internal/api/v1beta1connect/user_pat_test.go
  • internal/store/postgres/userpat_repository.go

Comment thread internal/api/v1beta1connect/user_pat.go
@coveralls
Copy link
Copy Markdown

coveralls commented Apr 20, 2026

Coverage Report for CI Build 24666310198

Coverage decreased (-0.07%) to 42.192%

Details

  • Coverage decreased (-0.07%) from the base build.
  • Patch coverage: 8 uncovered changes across 2 files (52 of 60 lines covered, 86.67%).
  • 1 coverage regression across 1 file.

Uncovered Changes

File Changed Covered %
internal/store/postgres/userpat_repository.go 7 0 0.0%
core/userpat/service.go 17 16 94.12%

Coverage Regressions

1 previously-covered line in 1 file lost coverage.

File Lines Losing Coverage Coverage
core/userpat/service.go 1 89.45%

Coverage Stats

Coverage Status
Relevant Lines: 36879
Covered Lines: 15560
Line Coverage: 42.19%
Coverage Strength: 11.9 hits per line

💛 - Coveralls

@AmanGIT07 AmanGIT07 merged commit 901863f into main Apr 20, 2026
8 checks passed
@AmanGIT07 AmanGIT07 deleted the refactor/pat-handler-common-helpers branch April 20, 2026 12:45
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