Skip to content

feat: customer feedback sdk permissions#3068

Merged
chronark merged 3 commits intomainfrom
customer-feedback-sdk-permissions
Apr 2, 2025
Merged

feat: customer feedback sdk permissions#3068
chronark merged 3 commits intomainfrom
customer-feedback-sdk-permissions

Conversation

@chronark
Copy link
Collaborator

@chronark chronark commented Apr 2, 2025

  • feat: upsert permissions and roles
  • feat: add permissions to sdk
  • chore: changeset

Summary by CodeRabbit

  • New Features
    • Expanded the API client with new asynchronous methods for managing permissions and roles, enabling streamlined additions, updates, and removals.
    • Improved the key creation process to dynamically handle role and permission associations.
  • Tests
    • Added comprehensive tests to verify proper role/permission linking and to ensure unauthorized actions are correctly blocked.
  • Documentation
    • Updated version documentation reflecting the enhancements to permissions management.

@vercel
Copy link

vercel bot commented Apr 2, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 2, 2025 0:42am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 2, 2025 0:42am
play ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 2, 2025 0:42am
www ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 2, 2025 0:42am

@changeset-bot
Copy link

changeset-bot bot commented Apr 2, 2025

🦋 Changeset detected

Latest commit: f2f3376

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages
Name Type
@unkey/api Minor
@unkey/hono Patch
@unkey/nextjs Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 2, 2025

📝 Walkthrough

Walkthrough

This pull request introduces updates for permissions and roles management. A changelog document now details a minor version change for the "@unkey/api" package. New tests have been added and updated for the key creation functionality to validate both roles and permissions assignment, including checks for insufficient permissions. The API route for key creation now accepts additional parameters (auth and rbac) to handle permissions dynamically, incorporating improved error handling and logic for creating missing entities. The client library has also been enhanced with new asynchronous methods and a getter for permissions and roles management.

Changes

File(s) Change Summary
.changeset/witty-spoons-flow.md Added a changelog document for a minor version bump of the "@unkey/api" package with a note on new permission features.
apps/api/src/routes/v1_keys_createKey.happy.test.ts
apps/api/src/routes/v1_keys_createKey.security.test.ts
Added new tests for key creation: tests for upserting specified roles and permissions, and tests ensuring users without required permissions cannot create roles or permissions.
apps/api/src/routes/v1_keys_createKey.ts Updated the getPermissionIds and getRoleIds functions to accept auth and rbac parameters; added permission evaluation, error handling for insufficient permissions, and logic to create missing permissions/roles.
packages/api/src/client.ts Introduced new async methods (addPermissions, setPermissions, removePermissions, addRoles, removeRoles, setRoles) and a getter for permissions to enhance client-side management of permissions and roles.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API
    participant RBAC
    participant DB

    Client->>API: POST /v1/keys.createKey (with roles & permissions)
    API->>DB: Retrieve existing roles and permissions
    alt All entities exist
        API-->>Client: Return created key
    else Some entities missing
        API->>RBAC: Evaluate requested permissions/roles
        alt Evaluation fails (insufficient permissions)
            API-->>Client: 403 Error (INSUFFICIENT_PERMISSIONS)
        else Evaluation passes
            API->>DB: Create missing roles/permissions
            API-->>Client: Return created key with combined IDs
        end
    end
Loading
sequenceDiagram
    participant App
    participant Unkey
    participant API

    App->>Unkey: Call permissions.addPermissions(...)
    Unkey->>API: HTTP POST /v1/keys.addPermissions
    API-->>Unkey: Return result
    Unkey-->>App: Deliver response
Loading

Possibly related PRs

Suggested labels

Feature, 🕹️ oss.gg, :joystick: 150 points

Suggested reviewers

  • mcstepp
  • perkinsjr
  • ogzhanolguncu
✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions
Copy link
Contributor

github-actions bot commented Apr 2, 2025

Thank you for following the naming conventions for pull request titles! 🙏

@vercel vercel bot temporarily deployed to Preview – play April 2, 2025 12:41 Inactive
@vercel vercel bot temporarily deployed to Preview – engineering April 2, 2025 12:41 Inactive
@vercel vercel bot temporarily deployed to Preview – www April 2, 2025 12:42 Inactive
@vercel vercel bot temporarily deployed to Preview – dashboard April 2, 2025 12:42 Inactive
Copy link
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: 0

🧹 Nitpick comments (3)
apps/api/src/routes/v1_keys_createKey.ts (3)

538-587: Consider refactoring to reduce duplication with getRoleIds function.

The getPermissionIds and getRoleIds functions have very similar implementations which could be extracted into a more generic function to reduce code duplication.

+async function getEntityIds<T extends { id: string; name: string }>(
+  entityType: "permission" | "role",
+  auth: { permissions: Array<string> },
+  rbac: RBAC,
+  db: Database,
+  workspaceId: string,
+  entityNames: Array<string>,
+  findEntities: (db: Database, workspaceId: string, names: string[]) => Promise<T[]>,
+  createEntities: (workspaceId: string, names: string[]) => Array<T>
+): Promise<Array<string>> {
+  if (entityNames.length === 0) {
+    return [];
+  }
+  
+  const entities = await findEntities(db, workspaceId, entityNames);
+  
+  if (entities.length === entityNames.length) {
+    return entities.map((e) => e.id);
+  }
+  
+  const permissionQuery = entityType === "permission" 
+    ? "rbac.*.create_permission" 
+    : "rbac.*.create_role";
+  
+  const { val, err } = rbac.evaluatePermissions(
+    buildUnkeyQuery(({ or }) => or("*", permissionQuery)),
+    auth.permissions,
+  );
+  
+  if (err) {
+    throw new UnkeyApiError({
+      code: "INTERNAL_SERVER_ERROR",
+      message: `Failed to evaluate permissions: ${err.message}`,
+    });
+  }
+  
+  if (!val.valid) {
+    throw new UnkeyApiError({ code: "INSUFFICIENT_PERMISSIONS", message: val.message });
+  }
+  
+  const missingNames = entityNames.filter(
+    (name) => !entities.some((entity) => entity.name === name)
+  );
+  
+  const newEntities = createEntities(workspaceId, missingNames);
+  
+  await db.insert(entityType === "permission" ? schema.permissions : schema.roles)
+    .values(newEntities);
+  
+  return [...entities, ...newEntities].map((entity) => entity.id);
+}

Then update the existing functions to use this generic implementation.


556-586: Handle case-sensitivity in permission name matching.

The current implementation doesn't explicitly handle case-sensitivity when matching permission names. If there are permissions with similar names but different casing, the length check might pass but the wrong permissions could be matched.

Consider adding a more robust matching mechanism, such as:

-  if (permissions.length === permissionNames.length) {
+  // Check if every requested permission exists with exact name match
+  const allPermissionsExist = permissionNames.every(name => 
+    permissions.some(p => p.name === name)
+  );
+  if (allPermissionsExist) {

589-636: Similar refactoring needed for role handling.

The getRoleIds function has the same potential issues and refactoring opportunities as getPermissionIds. Apply the same improvements for consistency.

Follow the same pattern recommended for the getPermissionIds function:

  1. Use the generic helper function to reduce duplication
  2. Add more robust name matching to handle case sensitivity
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 21b5de5 and f2f3376.

📒 Files selected for processing (5)
  • .changeset/witty-spoons-flow.md (1 hunks)
  • apps/api/src/routes/v1_keys_createKey.happy.test.ts (2 hunks)
  • apps/api/src/routes/v1_keys_createKey.security.test.ts (1 hunks)
  • apps/api/src/routes/v1_keys_createKey.ts (5 hunks)
  • packages/api/src/client.ts (2 hunks)
🧰 Additional context used
🧬 Code Definitions (3)
apps/api/src/routes/v1_keys_createKey.security.test.ts (1)
apps/api/src/routes/v1_keys_createKey.ts (1)
  • V1KeysCreateKeyRequest (254-256)
apps/api/src/routes/v1_keys_createKey.happy.test.ts (1)
apps/api/src/routes/v1_keys_createKey.ts (2)
  • V1KeysCreateKeyRequest (254-256)
  • V1KeysCreateKeyResponse (257-259)
packages/api/src/client.ts (1)
packages/api/src/openapi.d.ts (1)
  • paths (15-149)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Go API Local / Test (Shard 8/8)
  • GitHub Check: Test Go API Local / Test (Shard 5/8)
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Build / Build
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Agent Local / test_agent_local
🔇 Additional comments (10)
.changeset/witty-spoons-flow.md (1)

1-6: LGTM - Changeset file correctly documents the API changes.

The changeset file properly indicates a minor version bump for the "@unkey/api" package, which aligns with adding new permissions functionality. This follows semantic versioning conventions for feature additions.

apps/api/src/routes/v1_keys_createKey.security.test.ts (2)

113-139: Well-structured security test for role creation permissions.

This test properly validates that users without the necessary permissions cannot create roles. It follows the same pattern as other security tests in the file and checks for the correct error response.


141-167: Security test properly validates permission creation restrictions.

This test ensures that users without the proper permissions cannot create permissions, maintaining the security model integrity. The test structure is consistent with the other security tests.

apps/api/src/routes/v1_keys_createKey.happy.test.ts (3)

225-240: Test correctly checks role association.

The updated test properly verifies that roles are connected to the created key, with appropriate assertions.


241-279: Good test for dynamic role creation and association.

This test validates that roles can be created dynamically when they don't exist, and properly associated with the key. It includes the correct permission setup and verification of the results.


328-366: Test properly validates permission upsert functionality.

This test ensures that permissions can be dynamically created and associated with keys when the user has the necessary authorization. The assertion logic correctly verifies the relationships.

apps/api/src/routes/v1_keys_createKey.ts (2)

13-13: LGTM - Adding RBAC import.

Correctly imports the RBAC type and buildUnkeyQuery function from the @unkey/rbac package.


338-344: LGTM - Updated permission and role handling in Promise.all.

The Promise.all correctly passes the auth and rbac parameters to the getPermissionIds and getRoleIds functions.

packages/api/src/client.ts (2)

230-307: Well-implemented permission and role management methods for keys

These new methods extend the keys namespace with comprehensive management capabilities for permissions and roles. The implementation follows the established pattern in the codebase, with consistent error handling and type safety through OpenAPI definitions.

The methods include:

  • addPermissions, setPermissions, removePermissions for permission management
  • addRoles, setRoles, removeRoles for role management

Each method properly uses the fetch utility and maintains type safety through the OpenAPI definitions.


442-523: Clean implementation of permissions management namespace

The new permissions getter provides a well-structured API for managing roles and permissions directly:

  • Role management: createRole, getRole, deleteRole
  • Permission management: createPermission, getPermission, deletePermission

Each method follows the established pattern in the codebase, maintaining consistency with other parts of the SDK. The implementation leverages TypeScript's type system through OpenAPI definitions to ensure type safety.

@chronark chronark changed the title customer feedback sdk permissions feat: customer feedback sdk permissions Apr 2, 2025
@chronark chronark merged commit f73fc7e into main Apr 2, 2025
36 of 39 checks passed
@chronark chronark deleted the customer-feedback-sdk-permissions branch April 2, 2025 13:21
@coderabbitai coderabbitai bot mentioned this pull request Jul 8, 2025
18 tasks
@coderabbitai coderabbitai bot mentioned this pull request Aug 15, 2025
18 tasks
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