Skip to content

feat: v2/keys.deleteKey#3445

Merged
chronark merged 6 commits intomainfrom
feat/v2/keys.deleteKey
Jul 7, 2025
Merged

feat: v2/keys.deleteKey#3445
chronark merged 6 commits intomainfrom
feat/v2/keys.deleteKey

Conversation

@Flo4604
Copy link
Member

@Flo4604 Flo4604 commented Jul 4, 2025

What does this PR do?

For #3419

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

Unit tests

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • Added support for deleting API keys, including both soft delete (marking as deleted) and permanent delete (removing all related data).
    • Introduced a new endpoint for key deletion with appropriate authentication and permission checks.
  • Bug Fixes

    • Improved error responses for unauthorized, forbidden, not found, and malformed key deletion requests.
  • Tests

    • Added comprehensive tests for successful deletion, bad requests, unauthorized access, forbidden actions, and not found scenarios.

@changeset-bot
Copy link

changeset-bot bot commented Jul 4, 2025

⚠️ No Changeset found

Latest commit: 668c875

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

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

@vercel
Copy link

vercel bot commented Jul 4, 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 Jul 7, 2025 1:17pm
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 7, 2025 1:17pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 4, 2025

📝 Walkthrough

Walkthrough

This change introduces a new HTTP POST route handler for /v2/keys.deleteKey, supporting both soft and permanent deletion of keys. It adds database queries for soft and hard deletes, updates the handler logic, and provides comprehensive tests covering success, bad request, unauthorized, forbidden, and not found scenarios.

Changes

File(s) Change Summary
go/apps/api/routes/v2_keys_delete_key/handler.go Added new route handler for deleting keys, supporting soft and permanent deletion with permission checks.
go/apps/api/routes/v2_keys_delete_key/200_test.go Added tests for successful soft and permanent key deletion, including cleanup verification.
go/apps/api/routes/v2_keys_delete_key/400_test.go Added tests for bad request scenarios (missing or empty keyId).
go/apps/api/routes/v2_keys_delete_key/401_test.go Added tests for unauthorized access (missing/malformed/invalid Authorization headers).
go/apps/api/routes/v2_keys_delete_key/403_test.go Added tests for forbidden access (insufficient permissions, cross-workspace/API attempts).
go/apps/api/routes/v2_keys_delete_key/404_test.go Added tests for not found scenarios (nonexistent or already soft-deleted keys).
go/pkg/db/queries/key_delete_by_id.sql, go/pkg/db/key_delete_by_id.sql_generated.go Added SQL and generated Go code for hard deleting a key and related records by key ID.
go/pkg/db/queries/key_soft_delete_by_id.sql, go/pkg/db/key_soft_delete_by_id.sql_generated.go Added SQL and generated Go code for soft deleting a key (setting deleted_at_m timestamp).
go/pkg/db/querier_generated.go Added new methods to Querier interface for soft and hard key deletion.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Handler
    participant DB
    participant AuditLog

    Client->>Handler: POST /v2/keys.deleteKey (with keyId, Permanent flag)
    Handler->>DB: Authenticate root key
    Handler->>DB: Fetch key by ID
    alt Key not found or not in workspace
        Handler-->>Client: 404 Not Found / 403 Forbidden
    else Permission check fails
        Handler-->>Client: 403 Forbidden
    else Permanent flag is true
        Handler->>DB: DeleteKeyByID (hard delete, cascade)
        Handler->>AuditLog: Log permanent deletion
        Handler-->>Client: 200 OK (empty data)
    else Soft delete
        Handler->>DB: SoftDeleteKeyByID (set deleted_at_m)
        Handler->>AuditLog: Log soft deletion
        Handler-->>Client: 200 OK (empty data)
    end
Loading

Possibly related PRs

  • unkeyed/unkey#2847: Implements and tests permanent (hard) deletion of keys in the key deletion API route, modifying handler logic and adding tests for soft and hard delete scenarios.

Suggested reviewers

  • imeyer
  • perkinsjr
  • chronark

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 3e48ca9 and bad3551.

📒 Files selected for processing (1)
  • go/pkg/db/querier_generated.go (2 hunks)
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: chronark
PR: unkeyed/unkey#2693
File: apps/api/src/routes/v1_keys_updateKey.ts:350-368
Timestamp: 2024-11-29T15:15:47.308Z
Learning: In `apps/api/src/routes/v1_keys_updateKey.ts`, the code intentionally handles `externalId` and `ownerId` separately for clarity. The `ownerId` field will be removed in the future, simplifying the code.
go/pkg/db/querier_generated.go (1)
Learnt from: Flo4604
PR: unkeyed/unkey#3151
File: go/apps/api/openapi/gen.go:221-233
Timestamp: 2025-04-18T20:01:33.812Z
Learning: For identity deletion operations in the Unkey API, identityId takes precedence over externalId when both are provided in the request body.
🧬 Code Graph Analysis (1)
go/pkg/db/querier_generated.go (1)
go/pkg/db/key_soft_delete_by_id.sql_generated.go (1)
  • SoftDeleteKeyByIDParams (17-20)
⏰ Context from checks skipped due to timeout of 90000ms (24)
  • GitHub Check: Test Go API Local / Test (Shard 5/8)
  • GitHub Check: Test Go API Local / Test (Shard 8/8)
  • GitHub Check: Test Go API Local / Test (Shard 6/8)
  • GitHub Check: Test Go API Local / Test (Shard 4/8)
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test Go API Local / Test (Shard 3/8)
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Build / Build
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Packages / Test ./packages/rbac
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./apps/dashboard
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./internal/billing
  • GitHub Check: Test Packages / Test ./internal/resend
  • GitHub Check: Test Packages / Test ./internal/hash
  • GitHub Check: Test Packages / Test ./internal/encryption
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: autofix
🔇 Additional comments (2)
go/pkg/db/querier_generated.go (2)

17-26: Hard delete implementation looks correct with proper cascading.

The DeleteKeyByID method implements a comprehensive hard delete that removes the key and all its associated records from multiple tables using LEFT JOINs. This approach ensures data consistency by cleaning up:

  • Key permissions (keys_permissions)
  • Key roles (keys_roles)
  • Rate limits (ratelimits)
  • Encrypted keys (encrypted_keys)

The SQL structure is efficient and prevents orphaned records.


829-832: Soft delete implementation is appropriate for the use case.

The SoftDeleteKeyByID method correctly implements soft deletion by updating only the deleted_at_m timestamp in the keys table. This approach:

  • Preserves data integrity by keeping the key record
  • Allows for potential recovery of soft-deleted keys
  • Doesn't require cascading to related tables since the parent key's soft deletion effectively renders child records inaccessible

The method signature using SoftDeleteKeyByIDParams is consistent with the existing pattern in the codebase.

✨ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @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.

@vercel vercel bot temporarily deployed to Preview – engineering July 4, 2025 09:31 Inactive
@Flo4604 Flo4604 marked this pull request as ready for review July 4, 2025 09:34
@github-actions
Copy link
Contributor

github-actions bot commented Jul 4, 2025

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

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

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fb28466 and 1c5800b.

📒 Files selected for processing (11)
  • go/apps/api/routes/v2_keys_delete_key/200_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_delete_key/400_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_delete_key/401_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_delete_key/403_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_delete_key/404_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_delete_key/handler.go (1 hunks)
  • go/pkg/db/key_delete_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/key_soft_delete_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/querier_generated.go (2 hunks)
  • go/pkg/db/queries/key_delete_by_id.sql (1 hunks)
  • go/pkg/db/queries/key_soft_delete_by_id.sql (1 hunks)
🧰 Additional context used
🧠 Learnings (5)
📓 Common learnings
Learnt from: chronark
PR: unkeyed/unkey#2693
File: apps/api/src/routes/v1_keys_updateKey.ts:350-368
Timestamp: 2024-11-29T15:15:47.308Z
Learning: In `apps/api/src/routes/v1_keys_updateKey.ts`, the code intentionally handles `externalId` and `ownerId` separately for clarity. The `ownerId` field will be removed in the future, simplifying the code.
go/apps/api/routes/v2_keys_delete_key/400_test.go (2)
Learnt from: MichaelUnkey
PR: unkeyed/unkey#2114
File: apps/api/src/routes/v1_keys_updateKey.error.test.ts:0-0
Timestamp: 2024-09-27T15:20:05.475Z
Learning: In the `v1/keys.updateKey` endpoint, the server validates the refill configuration before checking if the key exists. Therefore, tests can assert validation errors without needing to create the key first.
Learnt from: Flo4604
PR: unkeyed/unkey#2955
File: go/apps/api/routes/v2_identities_create_identity/handler.go:162-202
Timestamp: 2025-03-19T09:25:59.751Z
Learning: In the Unkey codebase, input validation for API endpoints is primarily handled through OpenAPI schema validation, which occurs before requests reach the handler code. For example, in the identities.createIdentity endpoint, minimum values for ratelimit duration and limit are defined in the OpenAPI schema rather than duplicating these checks in the handler.
go/pkg/db/queries/key_delete_by_id.sql (2)
Learnt from: chronark
PR: unkeyed/unkey#3420
File: go/pkg/hydra/store/gorm/gorm.go:486-498
Timestamp: 2025-07-02T11:51:58.572Z
Learning: The Hydra package (go/pkg/hydra) is planned to be migrated from GORM to sqlc for database operations, which explains why raw SQL queries are acceptable in the current implementation.
Learnt from: Flo4604
PR: unkeyed/unkey#3151
File: go/apps/api/openapi/gen.go:221-233
Timestamp: 2025-04-18T20:01:33.812Z
Learning: For identity deletion operations in the Unkey API, identityId takes precedence over externalId when both are provided in the request body.
go/apps/api/routes/v2_keys_delete_key/404_test.go (1)
Learnt from: MichaelUnkey
PR: unkeyed/unkey#2114
File: apps/api/src/routes/v1_keys_updateKey.error.test.ts:0-0
Timestamp: 2024-09-27T15:20:05.475Z
Learning: In the `v1/keys.updateKey` endpoint, the server validates the refill configuration before checking if the key exists. Therefore, tests can assert validation errors without needing to create the key first.
go/pkg/db/querier_generated.go (1)
Learnt from: Flo4604
PR: unkeyed/unkey#3151
File: go/apps/api/openapi/gen.go:221-233
Timestamp: 2025-04-18T20:01:33.812Z
Learning: For identity deletion operations in the Unkey API, identityId takes precedence over externalId when both are provided in the request body.
🧬 Code Graph Analysis (1)
go/pkg/db/querier_generated.go (1)
go/pkg/db/key_soft_delete_by_id.sql_generated.go (1)
  • SoftDeleteKeyByIDParams (17-20)
🔇 Additional comments (10)
go/pkg/db/queries/key_delete_by_id.sql (1)

1-8: LGTM! Well-structured multi-table DELETE query.

The SQL query correctly implements permanent key deletion by:

  • Using LEFT JOINs to include all related tables that reference the key
  • Cleaning up associated data from keys_permissions, keys_roles, ratelimits, and encrypted_keys tables
  • Using parameterized queries for security
  • Performing the deletion atomically in a single operation
go/pkg/db/queries/key_soft_delete_by_id.sql (1)

1-2: LGTM! Correct soft delete implementation.

The query properly implements soft deletion by updating the deleted_at_m timestamp while preserving all related data. The parameterized approach ensures type safety and prevents SQL injection.

go/pkg/db/key_delete_by_id.sql_generated.go (1)

22-34: LGTM! Generated code follows established patterns.

The DeleteKeyByID method is properly generated with:

  • Consistent method signature using context and DBTX interface
  • Appropriate error handling
  • Clear documentation including the SQL query
  • Follows the same patterns as other sqlc-generated deletion methods
go/pkg/db/key_soft_delete_by_id.sql_generated.go (1)

17-28: LGTM! Proper parameter structure and method implementation.

The generated code correctly implements soft deletion with:

  • Well-defined SoftDeleteKeyByIDParams struct using appropriate Go types
  • sql.NullInt64 for the timestamp field allows for proper null handling
  • Method signature consistent with other parameterized sqlc methods
  • Proper error handling and context usage
go/pkg/db/querier_generated.go (1)

17-26: LGTM! Interface updates are consistent and well-documented.

The new deletion methods are properly added to the Querier interface with:

  • Method signatures that exactly match the generated implementations
  • Comprehensive documentation including the underlying SQL queries
  • Logical placement within the interface structure
  • Consistent naming and parameter patterns with existing methods

Also applies to: 829-832

go/apps/api/routes/v2_keys_delete_key/401_test.go (1)

86-143: Additional context needed: please show the implementation of VerifyRootKey in go/internal/services/keys/verify_root_key.go, especially how it handles errors after extracting the bearer token and when the key does not exist. This will let me confirm whether malformed headers map to 400 and missing keys to 401.

go/apps/api/routes/v2_keys_delete_key/handler.go (1)

46-171: Well-implemented handler with proper security and error handling.

The handler correctly implements:

  • Authentication via root key verification
  • Authorization with granular permission checks
  • Workspace validation to prevent cross-workspace access
  • Transaction-based deletion with audit logging
  • Proper error handling with appropriate fault codes

The use of ptr.SafeDeref for the optional permanent flag is a good defensive programming practice.

go/apps/api/routes/v2_keys_delete_key/403_test.go (3)

1-18: LGTM! Clean imports and package structure.

The imports are well-organized and include all necessary dependencies for testing the delete key endpoint's permission validation.


131-189: Excellent test coverage for permission scenarios.

The test cases comprehensively cover all forbidden access scenarios:

  • No permissions
  • Wrong permissions (create vs delete)
  • Cross-workspace access
  • Cross-API access

Each test properly validates both the HTTP status code and the presence of an error response body.


172-172: Cross-workspace access correctly returns 404

The handler’s workspace-scoping intentionally treats keys in other workspaces as “not found” before any permission check:

  • In handler.go (around line 33), you’ll see:
    if key.WorkspaceID != auth.AuthorizedWorkspaceID {
      return fault.New("key not found",
        fault.Code(codes.Data.Key.NotFound.URN()),
        fault.Internal("key belongs to different workspace"),
        fault.Public("The specified key was not found."),
      )
    }
  • The cross-workspace test in 403_test.go asserts a 404, matching this logic.
  • Other forbidden scenarios (missing permissions) occur later in the flow and rightly return 403.

No changes required.

@chronark chronark enabled auto-merge July 4, 2025 09:42
@chronark chronark self-requested a review July 4, 2025 09:48
Copy link
Collaborator

@chronark chronark left a comment

Choose a reason for hiding this comment

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

a few code rabbit comments are good, let's fix those before merging

@Flo4604 Flo4604 requested a review from chronark July 4, 2025 09:56
@vercel vercel bot temporarily deployed to Preview – engineering July 7, 2025 13:17 Inactive
@vercel vercel bot temporarily deployed to Preview – dashboard July 7, 2025 13:17 Inactive
@chronark chronark added this pull request to the merge queue Jul 7, 2025
Merged via the queue into main with commit 3538716 Jul 7, 2025
29 of 37 checks passed
@chronark chronark deleted the feat/v2/keys.deleteKey branch July 7, 2025 13:19
This was referenced Jul 28, 2025
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