Skip to content

feat: v2/identitiesDeleteIdentity#3151

Merged
chronark merged 20 commits intounkeyed:mainfrom
Flo4604:feat/api/v2/identities_deleteIdentity
Apr 23, 2025
Merged

feat: v2/identitiesDeleteIdentity#3151
chronark merged 20 commits intounkeyed:mainfrom
Flo4604:feat/api/v2/identities_deleteIdentity

Conversation

@Flo4604
Copy link
Member

@Flo4604 Flo4604 commented Apr 18, 2025

What does this PR do?

Fixes #3152

Also fixes the index for identities

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?

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

    • Introduced a new API endpoint to delete identities, supporting deletion by either internal or external ID.
    • Added support for soft deletion of identities, allowing them to be marked as deleted instead of being permanently removed.
    • Enhanced rate limit management with a dedicated type and updated schema.
  • Bug Fixes

    • Improved error handling and validation for identity deletion, including permission and workspace checks.
  • Tests

    • Added comprehensive tests for the new identity deletion endpoint, covering success, bad requests, unauthorized access, permission checks, and not found cases.
  • Chores

    • Updated database schema and indexes to support soft deletion and improved uniqueness constraints.
    • Added utility functions for duplicate key error detection and batch deletion of rate limits.

@changeset-bot
Copy link

changeset-bot bot commented Apr 18, 2025

⚠️ No Changeset found

Latest commit: 2ce6bea

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 Apr 18, 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 23, 2025 9:48am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Apr 23, 2025 9:48am

@vercel
Copy link

vercel bot commented Apr 18, 2025

@Flo4604 is attempting to deploy a commit to the Unkey Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Apr 18, 2025

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

This change introduces a new API endpoint /v2/identities.deleteIdentity that allows deletion of an identity by either its internal ID or external ID. It adds a soft-delete mechanism to the identities table, updates the database schema and queries to support a deleted flag, and refines unique constraints to include this flag. The OpenAPI schema and generated types are updated to reflect the new endpoint and request/response structures. The implementation includes comprehensive handler logic, error handling, audit logging, and extensive test coverage for authorization, permissions, and edge cases. Supporting changes include new and modified SQL queries, utility functions, and test adjustments.

Changes

File(s) / Path(s) Change Summary
go/apps/api/openapi/gen.go, go/apps/api/openapi/openapi.json Add Ratelimit struct, update identity creation ratelimits type, introduce polymorphic request/response types for identity deletion, add new endpoint and schema for /v2/identities.deleteIdentity.
go/apps/api/routes/register.go Register the new v2/identities.deleteIdentity route.
go/apps/api/routes/v2_identities_delete_identity/handler.go Implement handler for deleting an identity by internal or external ID, with permission checks, soft delete logic, audit logging, and error handling.
go/apps/api/routes/v2_identities_delete_identity/200_test.go Add integration tests for successful identity deletion scenarios, including with ratelimits and both ID types.
go/apps/api/routes/v2_identities_delete_identity/400_test.go, 401_test.go, 403_test.go, 404_test.go Add tests for bad requests, unauthorized, forbidden, and not found scenarios for the delete identity endpoint.
go/pkg/db/models_generated.go, go/pkg/db/schema.sql, internal/db/src/schema/identity.ts, ... Add deleted boolean column to identities, update unique constraint to include deleted, reorder fields, and update related schema and migration files.
go/pkg/db/queries/identity_soft_delete.sql, identity_soft_delete.sql_generated.go Add SQL and generated code for soft-deleting an identity (setting deleted to true).
go/pkg/db/queries/identity_delete.sql, identity_delete.sql_generated.go Add SQL and generated code for hard-deleting an identity by ID.
go/pkg/db/queries/identity_find_by_id.sql, identity_find_by_id.sql_generated.go Update query to select/filter by deleted, return full Identity struct, update method signature.
go/pkg/db/queries/identity_find_by_external_id.sql, identity_find_by_external_id.sql_generated.go Add SQL and generated code for finding identity by external ID and deleted status.
go/pkg/db/queries/ratelimit_delete_by_identity_id.sql, ratelimit_delete_by_identity_id.sql_generated.go Add SQL and generated code for deleting all ratelimits by identity ID.
go/pkg/db/queries/ratelimit_delete_many.sql, ratelimit_delete_many.sql_generated.go Add SQL and generated code for deleting multiple ratelimits by a list of IDs.
go/pkg/db/queries/identity_find_ratelimits_by_id.sql, identity_find_ratelimits_by_id.sql_generated.go Update ratelimit find query to return all columns, return Ratelimit type.
go/pkg/db/querier_generated.go Update Querier interface with new and updated methods for identity/ratelimit operations, including soft delete and find by external ID.
go/pkg/db/handle_err_duplicate_key.go Add utility function to detect MySQL duplicate key errors.
go/apps/api/routes/v2_identities_create_identity/handler.go, 200_test.go, 400_test.go, 409_test.go Update to use new ratelimit type and query signatures, adjust tests for new types and soft delete logic.
go/go.mod Add dependencies: github.com/oapi-codegen/runtime and github.com/apapsch/go-jsonmerge/v2.
internal/db/drizzle/0000_fat_the_hand.sql, meta/0000_snapshot.json, meta/_journal.json Update migration and snapshot files for schema changes to identities and apis tables, including new columns and unique indexes.
go/pkg/db/key_find_by_id.sql_generated.go, key_find_for_verification.sql_generated.go Update queries to include/select deleted field for identities.
go/pkg/fault/dst_test.go, go/pkg/testutil/seed/seed.go, go/internal/services/auditlogs/insert.go Minor test and logging adjustments, no logic changes.
go/pkg/codes/constants_gen.go Update generated timestamp only.
go/pkg/db/audit_log_bucket_id_find_by_workspace_and_name.sql_generated.go Remove unused generated code for audit log bucket lookup.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Router
    participant DeleteIdentityHandler
    participant DB
    participant AuditLogService
    participant PermissionsService

    Client->>API_Router: POST /v2/identities.deleteIdentity (with identityId or externalId)
    API_Router->>DeleteIdentityHandler: Route request
    DeleteIdentityHandler->>PermissionsService: Check delete_identity permission
    alt Permission OK
        DeleteIdentityHandler->>DB: Find identity by id or externalId (not deleted)
        alt Identity found
            DeleteIdentityHandler->>DB: Begin transaction
            DeleteIdentityHandler->>DB: Soft delete identity (set deleted=true)
            DeleteIdentityHandler->>AuditLogService: Write audit log(s)
            DeleteIdentityHandler->>DB: Commit transaction
            DeleteIdentityHandler-->>API_Router: 200 OK, empty body
        else Not found
            DeleteIdentityHandler-->>API_Router: 404 Not Found
        end
    else Permission denied
        DeleteIdentityHandler-->>API_Router: 403 Forbidden
    end
    API_Router-->>Client: Response
Loading

Assessment against linked issues

Objective Addressed Explanation
Implement the v2 delete identity API, including deletion by internal or external ID (#3152)
Soft-delete mechanism and schema/index changes for identities (#3152)
OpenAPI schema, handler, and tests for /v2/identities.deleteIdentity (#3152)
Authorization and permission checks for identity deletion (#3152)

Possibly related PRs

  • unkeyed/unkey#2955: Adds a new creation endpoint and related types for identities; related as both modify the identities API domain (create vs delete).
  • unkeyed/unkey#3151: Directly related; implements the same delete identity feature, endpoint, handler, and supporting code.

Suggested reviewers

  • perkinsjr
  • mcstepp
  • ogzhanolguncu
  • MichaelUnkey

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1503dac and 2ce6bea.

📒 Files selected for processing (29)
  • go/apps/api/openapi/openapi.json (3 hunks)
  • go/apps/api/routes/v2_identities_create_identity/200_test.go (8 hunks)
  • go/apps/api/routes/v2_identities_create_identity/409_test.go (1 hunks)
  • go/apps/api/routes/v2_identities_create_identity/handler.go (1 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/200_test.go (1 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/handler.go (1 hunks)
  • go/apps/api/routes/v2_ratelimit_get_override/handler.go (3 hunks)
  • go/pkg/codes/constants_gen.go (1 hunks)
  • go/pkg/db/identity_delete.sql_generated.go (1 hunks)
  • go/pkg/db/identity_find_by_external_id.sql_generated.go (1 hunks)
  • go/pkg/db/identity_find_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/identity_find_ratelimits_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/identity_soft_delete.sql_generated.go (1 hunks)
  • go/pkg/db/key_find_by_id.sql_generated.go (3 hunks)
  • go/pkg/db/key_find_for_verification.sql_generated.go (3 hunks)
  • go/pkg/db/models_generated.go (1 hunks)
  • go/pkg/db/querier_generated.go (6 hunks)
  • go/pkg/db/queries/identity_find_by_external_id.sql (1 hunks)
  • go/pkg/db/queries/identity_find_by_id.sql (1 hunks)
  • go/pkg/db/queries/identity_find_ratelimits_by_id.sql (1 hunks)
  • go/pkg/db/ratelimit_delete_by_identity_id.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_delete_many.sql_generated.go (1 hunks)
  • go/pkg/db/schema.sql (1 hunks)
  • go/pkg/fault/dst_test.go (2 hunks)
  • go/pkg/testutil/seed/seed.go (0 hunks)
  • internal/db/drizzle/0000_fat_the_hand.sql (1 hunks)
  • internal/db/drizzle/meta/0000_snapshot.json (3 hunks)
  • internal/db/drizzle/meta/_journal.json (1 hunks)
  • internal/db/src/schema/identity.ts (2 hunks)
✨ 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 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.

@github-actions
Copy link
Contributor

github-actions bot commented Apr 18, 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: 5

🧹 Nitpick comments (7)
go/apps/api/routes/v2_identities_delete_identity/401_test.go (1)

14-38: Unauthorized test case is properly implemented

Good job implementing a test for unauthorized access. The test correctly verifies that the endpoint returns a 401 status code when an invalid authorization token is provided.

Consider adding additional test cases for other unauthorized scenarios like missing tokens or expired tokens if they aren't covered by authentication middleware tests.

go/apps/api/routes/v2_identities_delete_identity/404_test.go (1)

55-55: Use require.NoError instead of require.Nil for errors.

For better readability and more descriptive failure messages, prefer using require.NoError() over require.Nil() when checking for nil errors.

-require.Nil(t, err)
+require.NoError(t, err)
go/apps/api/routes/v2_identities_delete_identity/403_test.go (1)

44-67: Test function name doesn't match expected status code.

The test name "delete identity from other workspace" is under TestWorkspacePermissions but it's actually testing for a 404 Not Found response, not a 403 Forbidden as might be expected from the function name.

Either move this test to TestNotFound in 404_test.go or consider renaming the test function to better reflect its purpose.

go/apps/api/routes/v2_identities_delete_identity/200_test.go (2)

124-148: Duplicate test name but different test cases.

There are two test cases with the same name "delete identity via identityID", but they test different functionality - one uses identity ID and the other uses external ID.

Rename the second test case to accurately reflect what it's testing:

-t.Run("delete identity via identityID", func(t *testing.T) {
+t.Run("delete identity via externalId", func(t *testing.T) {

64-165: Consider adding audit log verification.

The tests verify identity and ratelimit deletion, but don't check if audit logs are properly created during the delete operation.

Consider adding verification that audit log entries are created when identities are deleted, ensuring the audit trail is properly maintained.

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

118-124: Avoid a second allocation when collecting ratelimit IDs

You already know len(ratelimits); initialise the slice with that capacity to prevent an extra growth step:

-ids := make([]string, 0)
-for _, ratelimit := range ratelimits {
-    ids = append(ids, ratelimit.ID)
-}
+ids := make([]string, len(ratelimits))
+for i, rl := range ratelimits {
+    ids[i] = rl.ID
+}

This is a tiny optimisation, but it’s essentially free to make.

go/apps/api/openapi/gen.go (1)

455-511: (Minor) Double marshal/unmarshal incurs avoidable overhead

MarshalJSON first converts t.union to bytes, then re‑parses those
bytes into the object map, only to marshal the full map again at the
end. For larger payloads this allocates three times:

  1. t.union.MarshalJSON()
  2. json.Unmarshal(..) into object
  3. json.Marshal(object) for the final result.

Because this file is generated, changing it manually is not ideal, but
upstream oapi-codegen could inline step 1 by directly unmarshalling
json.RawMessage(t.union) into object, saving one marshal + one
allocation.

No action required for correctness; flagging purely for possible
generator improvement.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 728816c and 0d2c5c0.

⛔ Files ignored due to path filters (55)
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit100_duration1000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit100_duration1000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit100_duration1000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit100_duration3600000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit100_duration3600000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit100_duration3600000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit100_duration60000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit100_duration60000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit100_duration60000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit5_duration1000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit5_duration1000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit5_duration1000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit5_duration3600000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit5_duration3600000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit5_duration3600000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit5_duration60000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit5_duration60000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes1_limit5_duration60000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit100_duration1000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit100_duration1000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit100_duration1000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit100_duration3600000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit100_duration3600000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit100_duration3600000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit100_duration60000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit100_duration60000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit100_duration60000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit5_duration1000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit5_duration1000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit5_duration1000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit5_duration3600000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit5_duration3600000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit5_duration3600000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit5_duration60000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit5_duration60000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes3_limit5_duration60000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit100_duration1000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit100_duration1000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit100_duration1000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit100_duration3600000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit100_duration3600000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit100_duration3600000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit100_duration60000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit100_duration60000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit100_duration60000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit5_duration1000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit5_duration1000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit5_duration1000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit5_duration3600000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit5_duration3600000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit5_duration3600000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit5_duration60000_load0_90_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit5_duration60000_load10_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/apps/api/integration/multi_node_ratelimiting/generated/ratelimit_nodes9_limit5_duration60000_load2_00_windows10/generated_test.go is excluded by !**/generated/**
  • go/go.sum is excluded by !**/*.sum
📒 Files selected for processing (63)
  • go/apps/api/openapi/gen.go (4 hunks)
  • go/apps/api/openapi/openapi.json (3 hunks)
  • go/apps/api/routes/register.go (2 hunks)
  • go/apps/api/routes/v2_apis_create_api/401_test.go (0 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/200_test.go (1 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/400_test.go (1 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/401_test.go (1 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/403_test.go (1 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/404_test.go (1 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/handler.go (1 hunks)
  • go/apps/api/routes/v2_ratelimit_get_override/handler.go (2 hunks)
  • go/go.mod (2 hunks)
  • go/internal/services/auditlogs/insert.go (1 hunks)
  • go/pkg/codes/constants_gen.go (4 hunks)
  • go/pkg/db/api_find_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/api_insert.sql_generated.go (1 hunks)
  • go/pkg/db/audit_log_bucket_id_find_by_workspace_and_name.sql_generated.go (0 hunks)
  • go/pkg/db/audit_log_find_target_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/audit_log_insert.sql_generated.go (1 hunks)
  • go/pkg/db/audit_log_target_insert.sql_generated.go (1 hunks)
  • go/pkg/db/identity_delete.sql_generated.go (1 hunks)
  • go/pkg/db/identity_find_by_external_id.sql_generated.go (1 hunks)
  • go/pkg/db/identity_find_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/identity_find_ratelimits_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/identity_insert.sql_generated.go (1 hunks)
  • go/pkg/db/identity_insert_ratelimit.sql_generated.go (1 hunks)
  • go/pkg/db/key_find_by_hash.sql_generated.go (1 hunks)
  • go/pkg/db/key_find_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/key_find_for_verification.sql_generated.go (1 hunks)
  • go/pkg/db/key_insert.sql_generated.go (1 hunks)
  • go/pkg/db/keyring_find_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/keyring_insert.sql_generated.go (1 hunks)
  • go/pkg/db/models_generated.go (1 hunks)
  • go/pkg/db/permission_find_by_workspace_and_name.sql_generated.go (1 hunks)
  • go/pkg/db/permission_insert.sql_generated.go (1 hunks)
  • go/pkg/db/permission_insert_key_permission.sql_generated.go (1 hunks)
  • go/pkg/db/permissions_by_key_id.sql_generated.go (1 hunks)
  • go/pkg/db/querier_generated.go (3 hunks)
  • go/pkg/db/queries/identity_delete.sql (1 hunks)
  • go/pkg/db/queries/identity_find_by_external_id.sql (1 hunks)
  • go/pkg/db/queries/identity_find_by_id.sql (1 hunks)
  • go/pkg/db/queries/ratelimit_delete_many.sql (1 hunks)
  • go/pkg/db/ratelimit_delete_many.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_namespace_delete.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_namespace_find_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_namespace_find_by_name.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_namespace_insert.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_namespace_soft_delete.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_override_find_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_override_find_by_identifier.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_override_find_matches.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_override_insert.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_override_list_by_namespace_id.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_override_soft_delete.sql_generated.go (1 hunks)
  • go/pkg/db/ratelimit_override_update.sql_generated.go (1 hunks)
  • go/pkg/db/workspace_find_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/workspace_hard_delete.sql_generated.go (1 hunks)
  • go/pkg/db/workspace_insert.sql_generated.go (1 hunks)
  • go/pkg/db/workspace_soft_delete.sql_generated.go (1 hunks)
  • go/pkg/db/workspace_update_enabled.sql_generated.go (1 hunks)
  • go/pkg/db/workspace_update_plan.sql_generated.go (1 hunks)
  • go/pkg/db/workspaces_list.sql_generated.go (1 hunks)
  • internal/db/src/schema/identity.ts (2 hunks)
💤 Files with no reviewable changes (2)
  • go/apps/api/routes/v2_apis_create_api/401_test.go
  • go/pkg/db/audit_log_bucket_id_find_by_workspace_and_name.sql_generated.go
🧰 Additional context used
🧬 Code Graph Analysis (2)
go/pkg/codes/constants_gen.go (1)
go/pkg/urn/urn.go (1)
  • URN (12-19)
go/apps/api/routes/v2_ratelimit_get_override/handler.go (3)
go/pkg/fault/wrap.go (2)
  • Wrap (20-37)
  • WithDesc (75-91)
go/pkg/fault/code.go (1)
  • WithCode (37-51)
go/pkg/codes/unkey_application.go (1)
  • App (45-59)
🔇 Additional comments (79)
go/pkg/db/keyring_insert.sql_generated.go (1)

3-3: Generated code version bump is correct
The sqlc tool version in the header comment has been updated to v1.28.0. As this is a non-functional change in a generated file, no further review is required.

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

3-3: Skip review for generated file.
This update only bumps the sqlc version comment from v1.27.0 to v1.28.0 in an auto‑generated file. No manual changes are needed.

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

3-3: Approved: Updated sqlc codegen version.

This generated file’s header comment has been bumped from sqlc v1.27.0 to sqlc v1.28.0. There are no functional or logical changes, and the SQL and method implementation remain unchanged.

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

3-3: Bump sqlc tool version in generated code.

The version comment has been updated from sqlc v1.27.0 to sqlc v1.28.0. This is a non-functional change reflecting the upgraded code generation tool.

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

3-3: Update code generation tool version comment
The auto‐generated header has been bumped from sqlc v1.27.0 to sqlc v1.28.0. This change is expected when regenerating with the latest sqlc and has no impact on functionality.

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

3-3: Auto-generated version upgrade
The sqlc generation version comment has been updated from v1.27.0 to v1.28.0. There are no functional changes to the query or code.

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

3-3: Upgrade sqlc generator version
The code generation header has been updated from sqlc v1.27.0 to sqlc v1.28.0. This is a non-functional change and aligns with other regenerated files in the PR.

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

3-3: Generated code version bump is correct.

This file is auto-generated by sqlc, and the updated version comment to v1.28.0 matches the other generated artifacts in this PR. No manual changes needed.

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

3-3: Approved: bump SQLC generator version only
The comment was updated to sqlc v1.28.0 without any functional changes to the query or method.

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

3-3: Approved: bump SQLC generator version only
The version comment now reads sqlc v1.28.0. No modifications to the SQL or Go code logic.

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

3-3: Approved: bump SQLC generator version only
Only the tool version comment was updated to sqlc v1.28.0. The SQL and generated code remain unchanged.

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

3-3: Approved: bump SQLC generator version only
The code generator version comment has been refreshed to sqlc v1.28.0, with no impact on functionality.

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

3-3: Approved: bump SQLC generator version only
This update only reflects the upgrade to sqlc v1.28.0 in the generated header. Everything else is unchanged.

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

3-3: Bump sqlc code generation version
The version comment was updated from sqlc v1.27.0 to sqlc v1.28.0. This is expected in generated code and has no impact on functionality.

go/internal/services/auditlogs/insert.go (1)

60-60: Remove extraneous blank line
The blank line after the json.Marshal(l.ActorMeta) error check was removed for concise formatting. This whitespace-only change does not affect control flow or error handling.

go/pkg/db/models_generated.go (1)

3-3: Update sqlc tool version comment
The generated models file’s header now reflects sqlc v1.28.0 instead of v1.27.0. No functional code was altered.

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

3-3: Upgrade sqlc version annotation
The code generation version was bumped to sqlc v1.28.0. There are no changes to the SQL query or its implementation.

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

3-3: Refresh sqlc version header
The generated file comment now indicates sqlc v1.28.0. This version bump is standard for regeneration and does not alter behavior.

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

3-3: Generated code version bump only
This change updates the sqlc tool version comment to v1.28.0. There are no functional or structural changes in this generated file.

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

3-3: Generated code version bump only
This update adjusts the sqlc version comment to v1.28.0. No logic, query, or signature changes were introduced.

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

3-3: Generated code version bump only
The only modification is the sqlc version comment upgrade to v1.28.0. No other code was altered.

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

3-3: Generated code version bump only
This file’s change is solely the sqlc version comment update to v1.28.0. Functionality remains unchanged.

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

3-3: Generated code version bump only
Only the sqlc version comment was updated to v1.28.0; the query, types, and methods are intact.

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

3-3: SQLC tool version bump is expected
The version comment has been updated from sqlc v1.27.0 to sqlc v1.28.0, matching the regeneration of all SQLC‐generated files in this PR. No functional or signature changes were introduced.

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

3-3: SQLC tool version bump is expected
The version comment has been updated from sqlc v1.27.0 to sqlc v1.28.0, aligning with the rest of the regenerated SQLC files. No logic or API surface changes occurred.

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

3-3: SQLC tool version bump is expected
The only change is the version comment update to sqlc v1.28.0. The SQL query and generated code remain unchanged.

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

3-3: SQLC tool version bump is expected
Updated the codegen comment to sqlc v1.28.0 with no modifications to the query or function signature.

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

3-3: SQLC tool version bump is expected
The only change is bumping the version comment to sqlc v1.28.0. All query logic and types remain identical.

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

3-3: Update sqlc Code Generation Version
The generated sqlc version comment has been bumped to sqlc v1.28.0, aligning with the other DB query files. No functional changes detected.

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

3-3: Bump sqlc Tool Version
The sqlc version in the generated comment is updated to v1.28.0. This is a non-functional, consistent version bump.

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

3-3: sqlc Version Upgrade
The code generation header now reflects sqlc v1.28.0, matching the rest of the generated DB code. No logic changes.

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

3-3: Consistent sqlc Version Update
Updated the code generator version to sqlc v1.28.0. No alterations to SQL or function behavior.

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

3-3: Upgrade sqlc Version Comment
The sqlc comment is now v1.28.0 for consistency; there are no functional changes.

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

3-3: Generated code version bump only
This file is auto‑generated by sqlc; the change solely updates the version comment from v1.27.0 to v1.28.0. No functional or behavioral modifications were introduced.

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

3-3: Generated code version bump only
Only the sqlc version marker was updated to v1.28.0. The SQL query, data structures, and method logic remain unchanged.

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

3-3: Generated code version bump only
This update refreshes the sqlc tool version comment to v1.28.0. There are no modifications to the SQL, parameters, or method implementation.

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

3-3: Generated code version bump only
The only change is the sqlc version comment upgrade to v1.28.0; the InsertKey query and its parameters are unchanged.

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

3-3: Generated code version bump only
The sqlc version marker has been updated to v1.28.0. No alterations were made to the SQL statement or generated Go code logic.

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

3-3: Approve: Updated sqlc code generation version
The sqlc version comment has been bumped from the previous version to v1.28.0, aligning with the upgraded sqlc code generation across the PR.

go/go.mod (2)

13-13: Approve: Added github.com/oapi-codegen/runtime v1.1.1 dependency
This dependency is required for the new polymorphic JSON handling in the generated OpenAPI models.


48-48: Approve: Added indirect github.com/apapsch/go-jsonmerge/v2 v2.0.0 dependency
This indirect module supports JSON merge functionality used in the new API model logic.

go/pkg/db/queries/ratelimit_delete_many.sql (1)

1-2: Approve: Introduce DeleteManyRatelimitsByIDs exec query
Adds a batch delete for rate limits via sqlc.slice(ids), enabling cleanup of associated rate limits in the identity deletion flow.

go/pkg/db/queries/identity_delete.sql (1)

1-2: Approve: Introduce DeleteIdentity exec query
Defines the DeleteIdentity SQL exec query to remove an identity record by its ID within the transaction.

go/pkg/db/queries/identity_find_by_external_id.sql (1)

1-2: Approve: Introduce FindIdentityByExternalID query
Adds a select query to retrieve an identity by workspace_id and external_id, supporting the delete-by-external-ID endpoint.

go/pkg/codes/constants_gen.go (2)

2-2: Generate timestamp updated.

The timestamp has been updated to reflect the latest code generation time.


11-13: Comment alignment improved.

The indentation has been removed from section header comments, aligning them to the left margin for better readability and consistency.

Also applies to: 15-15, 24-24, 36-38, 40-40, 45-45, 50-50, 55-55, 60-60, 65-65, 70-70, 75-75, 80-80, 87-87, 92-94, 96-96, 103-103, 110-110

go/pkg/db/queries/identity_find_by_id.sql (1)

2-2: Column order adjusted in SQL query.

The query now includes the id column as the first selected field and moves meta to the end. This change likely aligns with the updated structure in the generated Go code for better consistency.

go/apps/api/routes/register.go (2)

13-13: New import added for identity deletion handler.

The import for the new v2IdentitiesDeleteIdentity package is correctly added.


107-117: New route registered for identity deletion.

The route registration for the new /v2/identities.deleteIdentity endpoint is properly implemented with the standard default middlewares and required services (Logger, Database, Keys, Permissions, and Auditlogs).

go/apps/api/routes/v2_ratelimit_get_override/handler.go (3)

53-56: Improved error handling for namespace lookup failures.

Error handling has been enhanced by wrapping database errors with more specific error codes and descriptive messages. This change adds the ServiceUnavailable error code and provides both internal and user-facing error descriptions.


108-111: Improved error handling for override lookup failures.

Similar to the namespace lookup error handling, this change enhances the override lookup error handling with specific error codes and descriptive messages, providing better context for troubleshooting and user feedback.


113-113: Added empty line for better code readability.

A blank line has been added to improve code readability and maintain consistent spacing in the codebase.

internal/db/src/schema/identity.ts (1)

22-25: Index optimization looks good!

The index has been improved by changing the order from external_id_workspace_id_idx to workspace_id_external_id_idx which is a better approach for multi-tenant systems. This ordering optimizes queries that filter by workspaceId first (which is the typical access pattern), and then by externalId.

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

12-22: Implementation looks correct for identity deletion

The generated SQL query and implementation follow standard patterns for deletion operations. This will be used in the identity deletion endpoint to remove identities by their ID.

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

20-33: Bulk deletion implementation is secure and efficient

The implementation for deleting multiple rate limits is well-structured:

  1. Dynamically constructs the SQL query based on the number of IDs
  2. Safely handles empty ID slices
  3. Properly parameterizes the query to prevent SQL injection

This will efficiently delete associated rate limits when deleting an identity.

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

1-37: LGTM: Generated code for finding identity by external ID looks correct.

The SQL query and Go code for finding an identity by external ID are correctly implemented. The function takes appropriate parameters (workspace_id and external_id) and returns the full Identity struct.

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

13-29: LGTM: Updated method signature properly returns full Identity struct.

The changes appropriately update the query to select all identity fields including the ID and modify the method signature to return the full Identity struct instead of a specialized row type. This aligns with the newly added FindIdentityByExternalID method for consistency.

go/apps/api/routes/v2_identities_delete_identity/400_test.go (4)

36-49: LGTM: Well-structured test for missing both identity identifiers.

The test correctly verifies the 400 response when neither externalId nor identityId is provided, with appropriate assertions on the error response structure.


51-64: LGTM: Properly testing empty external ID validation.

The test verifies that an empty string for externalId is rejected with a 400 response.


81-91: LGTM: Missing authorization header test case is comprehensive.

The test correctly verifies the 400 response when the authorization header is missing.


93-103: LGTM: Malformed authorization header test case is comprehensive.

The test correctly verifies the 400 response when the authorization header is malformed.

go/apps/api/openapi/openapi.json (3)

572-600: LGTM: Well-defined request and response schemas for the delete identity endpoint.

The schemas for delete identity request and response are well-defined:

  1. Request schema properly uses anyOf to require either externalId or identityId
  2. Both fields have appropriate min length validation
  3. Descriptions clearly explain the purpose of each field
  4. Empty response schema follows the pattern for delete operations

675-681: LGTM: Formatting improvement for required fields array.

The reformatting of the required fields array for RatelimitOverride improves readability without changing functionality.


1190-1273: LGTM: Well-defined API endpoint for delete identity operation.

The API endpoint definition is comprehensive with:

  1. Proper security requirements using the rootKey scheme
  2. Correct request and response body references
  3. All appropriate error response status codes (400, 401, 403, 404, 500)
  4. Consistent response content type for errors (application/problem+json)
  5. Path and operation ID following the established naming patterns
go/pkg/db/querier_generated.go (4)

13-16: LGTM! Clear and descriptive DB interface method for identity deletion.

The SQL query documentation and interface method signature accurately represent the identity deletion functionality.


17-20: LGTM! Well-designed batch deletion method for ratelimits.

The method appropriately handles deletion of multiple ratelimits by their IDs, which will be useful for cleaning up associated resources when deleting identities.


38-41: LGTM! New method for finding identity by external ID is correctly implemented.

This method allows for polymorphic identity lookup, supporting the ability to delete identities by external ID.


42-45: LGTM! Updated return type for FindIdentityByID.

The method now returns an Identity type instead of FindIdentityByIDRow, providing consistency with the new FindIdentityByExternalID method.

go/apps/api/routes/v2_identities_delete_identity/404_test.go (3)

18-30: LGTM! Test setup and handler registration looks good.

The test harness and route registration provide a solid foundation for testing the API endpoint behavior.


44-67: LGTM! Good workspace isolation test case.

This test properly verifies that attempts to delete identities across workspace boundaries return the appropriate 404 status code, maintaining proper isolation.


69-80: LGTM! Good test for non-existent identity.

This test case correctly verifies that attempting to delete a non-existent identity returns a 404 status code.

go/apps/api/routes/v2_identities_delete_identity/403_test.go (2)

18-30: LGTM! Test setup and handler registration looks good.

The test harness and route registration provide a solid foundation for testing the API endpoint behavior.


31-42: LGTM! Good test for insufficient permissions.

This test case properly verifies that attempts to delete identities without the required permissions return a 403 Forbidden status code.

go/apps/api/routes/v2_identities_delete_identity/200_test.go (5)

19-24: LGTM! Good struct definition for test data.

This Identity struct provides a clear and concise representation of the test data structure.


25-62: LGTM! Well-structured helper function.

The newIdentity helper function is well-documented and properly handles the creation of test identities with configurable ratelimits.


85-96: LGTM! Good unit test for direct database deletion.

This test effectively verifies the basic identity deletion functionality at the database level.


99-122: LGTM! Comprehensive test for ratelimit cleanup.

This test thoroughly verifies that both identities and their associated ratelimits can be properly deleted from the database.


150-164: LGTM! Comprehensive test for API deletion with ratelimits.

This test thoroughly verifies that both identities and their associated ratelimits are properly deleted when using the API endpoint.

go/apps/api/openapi/gen.go (1)

6-11: Dependency looks fine, but verify go.mod alignment

The new github.com/oapi-codegen/runtime import is required for the JSON‑merge helpers that follow. As long as go.mod already pins the exact version that was used during generation, nothing else is needed here.

If you have not run go mod tidy after code‑generation, please do so to ensure the indirect dependency graph is clean.

})

// Create a identity via DB and delete it again
t.Run("delete identity ratelimits via db", func(t *testing.T) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

this test doesn't really fit here, I think
we're testing the api route in this package, not db functionality.

the test is good though, should we move it into a different package?

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah one package for db tests make sense to me

@chronark chronark self-assigned this Apr 22, 2025
@chronark
Copy link
Collaborator

This test from task test-unit is consistently failing for me

--- FAIL: TestBadRequests/neither_namespace_ID_nor_name_provided (0.00s)

Apr 22 10:41:22.509 ERR api error error="database failed to find the ratelimit namespace: missing namespace id or name: missing namespace id or name" requestId=req_3xT2PKNdwjFnhKxS publicMessage="Error finding the ratelimit namespace. You must provide either a namespace ID or name." source=/Users/andreasthomas/github/unkeyed/unkey/go/pkg/zen/middleware_errors.go:189
    400_test.go:101:
        	Error Trace:	/Users/andreasthomas/github/unkeyed/unkey/go/apps/api/routes/v2_ratelimit_get_override/400_test.go:101
        	Error:      	Not equal:
        	            	expected: 400
        	            	actual  : 500
        	Test:       	TestBadRequests/neither_namespace_ID_nor_name_provided
        	Messages:   	expected 400, sent: {Identifier:user_123 NamespaceId:<nil> NamespaceName:<nil>}, received: {"error":{"detail":"Error finding the ratelimit namespace. You must provide either a namespace ID or name.","status":500,"title":"Internal Server Error","type":"https://unkey.com/docs/api-reference/errors-v2/unkey/application/service_unavailable"},"meta":{"requestId":"req_3xT2PKNdwjFnhKxS"}}```

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

♻️ Duplicate comments (4)
go/apps/api/routes/v2_identities_delete_identity/handler.go (3)

34-226: ⚠️ Potential issue

Cross-workspace lookup by raw identity ID may leak information.

When using FindIdentityByID, the query isn't scoped to the workspace ID, which could potentially leak information across workspaces and bypass DB-level tenant isolation.

Although you check for workspace mismatch after retrieval (lines 98-103), it's better to implement a workspace-scoped query at the database level:

-        return db.Query.FindIdentityByID(ctx, svc.DB.RO(), db.FindIdentityByIDParams{
-            ID:      *req.IdentityId,
-            Deleted: false,
-        })
+        // Create a query that includes workspace_id filter
+        identity, err := db.Query.FindIdentityByIDAndWorkspace(ctx, svc.DB.RO(), db.FindIdentityByIDAndWorkspaceParams{
+            ID:          *req.IdentityId,
+            WorkspaceID: workspaceID,
+            Deleted:     false,
+        })

Consider adding FindIdentityByIDAndWorkspace query to ensure proper multi-tenancy at the database level.


261-280: ⚠️ Potential issue

Read operations happen outside the running transaction.

The getIdentity function uses svc.DB.RO() instead of the transaction handle, which breaks transaction isolation and could lead to race conditions or inconsistent reads.

Refactor to pass the transaction handle to getIdentity:

-func getIdentity(ctx context.Context, svc Services, req Request, workspaceID string) (db.Identity, error) {
+func getIdentity(ctx context.Context, dbHandle db.DBTX, req Request, workspaceID string) (db.Identity, error) {
   switch {
   case req.IdentityId != nil:
-        return db.Query.FindIdentityByID(ctx, svc.DB.RO(), db.FindIdentityByIDParams{
+        return db.Query.FindIdentityByID(ctx, dbHandle, db.FindIdentityByIDParams{
           ID:      *req.IdentityId,
           Deleted: false,
        })
   case req.ExternalId != nil:
-        return db.Query.FindIdentityByExternalID(ctx, svc.DB.RO(), db.FindIdentityByExternalIDParams{
+        return db.Query.FindIdentityByExternalID(ctx, dbHandle, db.FindIdentityByExternalIDParams{
           WorkspaceID: workspaceID,
           ExternalID:  *req.ExternalId,
           Deleted:     false,
        })
   }
   // ...
}

Then in the handler:

-       identity, err := getIdentity(ctx, svc, req, auth.AuthorizedWorkspaceID)
+       // Get identity inside transaction for consistency
+       identity, err := getIdentity(ctx, tx, req, auth.AuthorizedWorkspaceID)

170-176: 🛠️ Refactor suggestion

Read for ratelimits should also occur within the transaction.

Similar to the getIdentity issue, reading ratelimits should occur within the same transaction for consistency.

-       ratelimits, err := db.Query.FindRatelimitsByIdentityID(ctx, tx, sql.NullString{String: identity.ID, Valid: true})
+       ratelimits, err := db.Query.FindRatelimitsByIdentityID(ctx, tx, sql.NullString{String: identity.ID, Valid: true})

Ensure this uses tx consistently (it already appears to be using tx here, which is good - just confirming this is correct).

go/apps/api/openapi/gen.go (1)

233-244: ⚠️ Potential issue

Exactly‑one identifier rule still unenforced

Both ExternalId and IdentityId are optional pointers; callers can send zero or both fields, making the target of the delete ambiguous. This is the same issue raised earlier. Runtime guard or a oneOf schema constraint is required.

if (req.ExternalId == nil) == (req.IdentityId == nil) {
    return badRequest("exactly one of externalId or identityId must be provided")
}

Better: encode this in the OpenAPI spec with

oneOf:
  - required: ["externalId"]
  - required: ["identityId"]

so codegen enforces it automatically.

Would you like a spec patch PR snippet?

🧹 Nitpick comments (6)
go/apps/api/routes/v2_identities_delete_identity/handler.go (3)

138-143: Code duplication in error handling.

The error handling for the second soft delete operation duplicates the logic from the first attempt.

Consider extracting this to a helper function:

+       func handleSoftDeleteError(err error) error {
+           if err != nil && !db.IsDuplicateKeyError(err) {
+               return fault.Wrap(err,
+                   fault.WithCode(codes.App.Internal.ServiceUnavailable.URN()),
+                   fault.WithDesc("database failed to soft delete identity", "Failed to delete Identity."),
+               )
+           }
+           return nil
+       }

        err = db.Query.SoftDeleteIdentity(ctx, tx, identity.ID)
-       if err != nil && !db.IsDuplicateKeyError(err) {
-           return fault.Wrap(err,
-               fault.WithCode(codes.App.Internal.ServiceUnavailable.URN()),
-               fault.WithDesc("database failed to soft delete identity", "Failed to delete Identity."),
-           )
-       }
+       if err := handleSoftDeleteError(err); err != nil {
+           return err
+       }

        // If we hit a duplicate key error, we know that we have an identity that was already soft deleted
        // so we can hard delete the "old" deleted version
        if err != nil && db.IsDuplicateKeyError(err) {
            // error handling for duplicate key...

            // Re-apply the soft delete operation
            err = db.Query.SoftDeleteIdentity(ctx, tx, identity.ID)
-           if err != nil && !db.IsDuplicateKeyError(err) {
-               return fault.Wrap(err,
-                   fault.WithCode(codes.App.Internal.ServiceUnavailable.URN()),
-                   fault.WithDesc("database failed to soft delete identity", "Failed to delete Identity."),
-               )
-           }
+           if err := handleSoftDeleteError(err); err != nil {
+               return err
+           }
        }

146-207: Consider factoring out audit log creation.

The audit log creation logic is quite verbose and could be refactored for better maintainability, especially for the ratelimit audit logs.

Consider creating helper functions to construct the audit logs:

+       func createIdentityDeleteAuditLog(identity db.Identity, auth keys.AuthVerificationResult, s *zen.Session) auditlog.AuditLog {
+           return auditlog.AuditLog{
+               WorkspaceID: auth.AuthorizedWorkspaceID,
+               Event:       auditlog.IdentityDeleteEvent,
+               Display:     fmt.Sprintf("Deleted identity %s.", identity.ID),
+               Bucket:      auditlogs.DEFAULT_BUCKET,
+               ActorID:     auth.KeyID,
+               ActorType:   auditlog.RootKeyActor,
+               ActorMeta:   nil,
+               ActorName:   "root key",
+               RemoteIP:    s.Location(),
+               UserAgent:   s.UserAgent(),
+               Resources: []auditlog.AuditLogResource{
+                   {
+                       ID:          identity.ID,
+                       Meta:        nil,
+                       Type:        auditlog.IdentityResourceType,
+                       DisplayName: identity.ExternalID,
+                       Name:        identity.ExternalID,
+                   },
+               },
+           }
+       }
+
+       func createRatelimitDeleteAuditLog(identity db.Identity, rl db.FindRatelimitsByIdentityIDRow, 
+                                         auth keys.AuthVerificationResult, s *zen.Session) auditlog.AuditLog {
+           return auditlog.AuditLog{
+               // similar construction for ratelimit audit log
+           }
+       }

-       auditLogs := []auditlog.AuditLog{
-           {
-               WorkspaceID: auth.AuthorizedWorkspaceID,
-               Event:       auditlog.IdentityDeleteEvent,
-               Display:     fmt.Sprintf("Deleted identity %s.", identity.ID),
-               // ... rest of the audit log construction
-           },
-       }
+       auditLogs := []auditlog.AuditLog{
+           createIdentityDeleteAuditLog(identity, auth, s),
+       }

        // ... ratelimit fetching logic

        for _, rl := range ratelimits {
-           auditLogs = append(auditLogs, auditlog.AuditLog{
-               // ... verbose audit log construction
-           })
+           auditLogs = append(auditLogs, createRatelimitDeleteAuditLog(identity, rl, auth, s))
        }

229-259: Potential for a simpler database operation for deleteOldIdentity.

The deleteOldIdentity function has sequential reads and deletes that could potentially be combined into fewer database operations.

Consider creating a more atomic database operation:

-- A single stored procedure or transaction could handle this more efficiently
DELETE FROM ratelimits WHERE identity_id = (
  SELECT id FROM identities 
  WHERE workspace_id = ? AND external_id = ? AND deleted = true
);

DELETE FROM identities WHERE workspace_id = ? AND external_id = ? AND deleted = true;

This would reduce the number of database roundtrips and potentially improve performance.

go/apps/api/openapi/gen.go (2)

221-225: Pointer‑of‑slice adds unnecessary indirection

*[]Ratelimit means “a pointer to a slice”. The zero value (nil) of a slice already represents “not provided”, so an extra pointer complicates usage (nil, &[]nil, empty slice) and JSON encoding.

-	Ratelimits *[]Ratelimit `json:"ratelimits,omitempty"`
+	Ratelimits []Ratelimit `json:"ratelimits,omitempty"`

The generator allows this tweak via x-oapi-codegen-skip-prune. Removing the double indirection improves ergonomics without changing wire format.


455-512: Marshal/Unmarshal silently preserve unknown union fields

Current implementation copies the raw union object into object and then blindly re‑marshals. If union contains keys that collide with the explicit fields (externalId, identityId) the explicit fields win – good – but you also resurrect any unknown keys, effectively allowing clients to smuggle arbitrary JSON that will survive round‑trips.

If this is unintended, filter object to an allow‑list before re‑marshalling or drop union handling altogether once the one‑of rule is enforced.

go/pkg/db/schema.sql (1)

221-236: Unique index may clash across workspaces

ratelimits.unique_name_idx is (name, key_id, identity_id) but omits workspace_id. Two workspaces could not share the same global limit name attached to the same kind of resource even though they are isolated elsewhere.

Confirm whether the uniqueness scope should include workspace_id; if yes:

UNIQUE KEY unique_name_idx (workspace_id, name, key_id, identity_id)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0f817cb and 1503dac.

📒 Files selected for processing (23)
  • go/apps/api/openapi/gen.go (6 hunks)
  • go/apps/api/openapi/openapi.json (4 hunks)
  • go/apps/api/routes/v2_identities_create_identity/200_test.go (7 hunks)
  • go/apps/api/routes/v2_identities_create_identity/400_test.go (3 hunks)
  • go/apps/api/routes/v2_identities_create_identity/handler.go (1 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/200_test.go (1 hunks)
  • go/apps/api/routes/v2_identities_delete_identity/handler.go (1 hunks)
  • go/pkg/codes/constants_gen.go (1 hunks)
  • go/pkg/db/handle_err_duplicate_key.go (1 hunks)
  • go/pkg/db/identity_find_by_external_id.sql_generated.go (1 hunks)
  • go/pkg/db/identity_find_by_id.sql_generated.go (1 hunks)
  • go/pkg/db/identity_soft_delete.sql_generated.go (1 hunks)
  • go/pkg/db/key_find_by_id.sql_generated.go (4 hunks)
  • go/pkg/db/key_find_for_verification.sql_generated.go (4 hunks)
  • go/pkg/db/models_generated.go (2 hunks)
  • go/pkg/db/querier_generated.go (6 hunks)
  • go/pkg/db/queries/identity_find_by_external_id.sql (1 hunks)
  • go/pkg/db/queries/identity_find_by_id.sql (1 hunks)
  • go/pkg/db/queries/identity_soft_delete.sql (1 hunks)
  • go/pkg/db/queries/ratelimit_delete_by_identity_id.sql (1 hunks)
  • go/pkg/db/ratelimit_delete_by_identity_id.sql_generated.go (1 hunks)
  • go/pkg/db/schema.sql (1 hunks)
  • internal/db/src/schema/identity.ts (2 hunks)
✅ Files skipped from review due to trivial changes (4)
  • go/pkg/codes/constants_gen.go
  • go/pkg/db/queries/ratelimit_delete_by_identity_id.sql
  • go/pkg/db/ratelimit_delete_by_identity_id.sql_generated.go
  • go/pkg/db/identity_soft_delete.sql_generated.go
🚧 Files skipped from review as they are similar to previous changes (9)
  • go/pkg/db/queries/identity_find_by_id.sql
  • go/pkg/db/key_find_by_id.sql_generated.go
  • go/pkg/db/key_find_for_verification.sql_generated.go
  • go/pkg/db/models_generated.go
  • internal/db/src/schema/identity.ts
  • go/apps/api/routes/v2_identities_delete_identity/200_test.go
  • go/apps/api/openapi/openapi.json
  • go/pkg/db/identity_find_by_id.sql_generated.go
  • go/pkg/db/querier_generated.go
🧰 Additional context used
🧠 Learnings (1)
go/apps/api/openapi/gen.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 destructive operations like deletion in the Unkey API, oneOf validation is preferred over anyOf to enforce explicit targeting and prevent ambiguity.
🧬 Code Graph Analysis (4)
go/apps/api/routes/v2_identities_create_identity/handler.go (1)
go/pkg/db/handle_err_duplicate_key.go (1)
  • IsDuplicateKeyError (7-13)
go/apps/api/routes/v2_identities_create_identity/200_test.go (3)
go/pkg/db/identity_find_by_id.sql_generated.go (1)
  • FindIdentityByIDParams (16-19)
go/pkg/db/models_generated.go (1)
  • Ratelimit (381-391)
go/apps/api/openapi/gen.go (1)
  • Ratelimit (129-138)
go/apps/api/routes/v2_identities_create_identity/400_test.go (3)
go/apps/api/routes/v2_identities_create_identity/handler.go (1)
  • MAX_META_LENGTH_MB (40-40)
go/pkg/ptr/pointer.go (1)
  • P (49-51)
go/apps/api/openapi/gen.go (1)
  • Ratelimit (129-138)
go/apps/api/openapi/gen.go (2)
go/pkg/db/models_generated.go (1)
  • Ratelimit (381-391)
packages/ratelimit/src/ratelimit.ts (1)
  • Ratelimit (121-214)
🔇 Additional comments (11)
go/apps/api/routes/v2_identities_create_identity/handler.go (1)

129-129: Improved error handling via abstraction

The code now uses a centralized utility function to check for duplicate key errors, which decouples the handler from MySQL-specific error types and makes the code more maintainable.

go/pkg/db/queries/identity_soft_delete.sql (1)

1-2: LGTM: Well-structured soft delete query

The SQL query is correctly implemented to perform a soft delete operation by setting the deleted flag to 1 for a specific identity ID, using a parameterized query for safety against SQL injection.

go/pkg/db/handle_err_duplicate_key.go (1)

7-13: Well-implemented utility function with minor considerations

This utility function effectively centralizes the logic for detecting MySQL duplicate key errors, improving code maintainability.

A few considerations for future enhancements:

  1. The type assertion could panic if err is nil (though it would typically be called with non-nil errors)
  2. The function is MySQL-specific, which is appropriate for the current database but creates a coupling to the MySQL driver
go/apps/api/routes/v2_identities_create_identity/400_test.go (3)

13-13: Good addition of ptr package.

The addition of the ptr package makes sense for the subsequent code changes that use the ptr.P helper function.


83-87: Modern type usage and improved code style.

Great changes:

  1. Modernizing to use map[string]any instead of map[string]interface{}
  2. Using range-based loop with ptr.P for creating pointers

107-113: Updated Ratelimit type reference.

Correctly updated from []openapi.V2Ratelimit to []openapi.Ratelimit, aligning with the API model update that replaced the V2Ratelimit type.

go/apps/api/routes/v2_identities_create_identity/200_test.go (2)

55-58: Updated FindIdentityByID calls with soft-delete support.

All calls to FindIdentityByID have been properly updated to use the new parameter struct with Deleted: false to filter out soft-deleted identities.

Also applies to: 77-80, 113-116, 136-139, 176-179


125-125: Modernized type usage in test cases.

Good updates:

  1. Changed map types from map[string]interface{} to map[string]any
  2. Updated ratelimit slice type from []openapi.V2Ratelimit to []openapi.Ratelimit

Also applies to: 143-143, 153-164

go/pkg/db/identity_find_by_external_id.sql_generated.go (3)

12-14: Well-structured query for finding identities by external ID.

The SQL query correctly includes filters for workspace ID, external ID, and deleted status, which supports proper multi-tenancy and soft-deletion functionality.


16-20: Comprehensive parameter struct for identity lookups.

The parameter struct includes all necessary fields for the query, including the new Deleted flag that supports soft deletion.


25-39: Well-implemented database query function.

The function follows the standard pattern for executing queries and properly handles error conditions.

Comment on lines +1 to +2
-- name: FindIdentityByExternalID :one
SELECT id, external_id, workspace_id, environment, created_at, updated_at, meta, deleted FROM identities WHERE workspace_id = ? AND external_id = ? AND deleted = ?;
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify parameter style consistency across SQL queries

The query correctly retrieves an identity by its external ID with workspace isolation and deletion status, but uses positional parameters (?) while other queries like identity_soft_delete.sql use named parameters (sqlc.arg('id')). Consider standardizing the parameter style across all SQL queries for consistency.


🏁 Script executed:

#!/bin/bash
# Check parameter style consistency across identity-related SQL queries
echo "Checking for SQL parameter styles in identity queries..."
grep -r --include="identity_*.sql" "sqlc.arg" go/pkg/db/queries/
echo "---"
grep -r --include="identity_*.sql" "WHERE.*?" go/pkg/db/queries/

Length of output: 2133


Standardize SQLC Parameter Usage in Identity Queries

Consistently use named parameters via sqlc.arg(...) instead of ? placeholders across all identity-related queries:

• go/pkg/db/queries/identity_find_by_external_id.sql
• go/pkg/db/queries/identity_find_by_id.sql

Suggested diffs:

--- a/go/pkg/db/queries/identity_find_by_external_id.sql
+++ b/go/pkg/db/queries/identity_find_by_external_id.sql
@@ -1,2 +1,2 @@
 -- name: FindIdentityByExternalID :one
-SELECT id, external_id, workspace_id, environment, created_at, updated_at, meta, deleted
-  FROM identities
- WHERE workspace_id = ? AND external_id = ? AND deleted = ?;
+SELECT id, external_id, workspace_id, environment, created_at, updated_at, meta, deleted
+  FROM identities
+ WHERE workspace_id = sqlc.arg('workspace_id')
+   AND external_id = sqlc.arg('external_id')
+   AND deleted      = sqlc.arg('deleted');
--- a/go/pkg/db/queries/identity_find_by_id.sql
+++ b/go/pkg/db/queries/identity_find_by_id.sql
@@ -1,2 +1,2 @@
 -- name: FindIdentityByID :one
-SELECT id, external_id, workspace_id, environment, created_at, updated_at, meta, deleted
-  FROM identities
- WHERE id = sqlc.arg(id) AND deleted = ?;
+SELECT id, external_id, workspace_id, environment, created_at, updated_at, meta, deleted
+  FROM identities
+ WHERE id      = sqlc.arg('id')
+   AND deleted = sqlc.arg('deleted');

This aligns these queries with the rest of the codebase’s SQLC parameter style.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +120 to +144
err = db.Query.SoftDeleteIdentity(ctx, tx, identity.ID)
if err != nil && !db.IsDuplicateKeyError(err) {
return fault.Wrap(err,
fault.WithCode(codes.App.Internal.ServiceUnavailable.URN()),
fault.WithDesc("database failed to soft delete identity", "Failed to delete Identity."),
)
}

// If we hit a duplicate key error, we know that we have an identity that was already soft deleted
// so we can hard delete the "old" deleted version
if err != nil && db.IsDuplicateKeyError(err) {
err = deleteOldIdentity(ctx, tx, auth.AuthorizedWorkspaceID, identity.ExternalID)
if err != nil {
return err
}

// Re-apply the soft delete operation
err = db.Query.SoftDeleteIdentity(ctx, tx, identity.ID)
if err != nil && !db.IsDuplicateKeyError(err) {
return fault.Wrap(err,
fault.WithCode(codes.App.Internal.ServiceUnavailable.URN()),
fault.WithDesc("database failed to soft delete identity", "Failed to delete Identity."),
)
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Potential race condition in duplicate key error handling.

The duplicate key error handling logic performs multiple database operations across different statements, which could lead to race conditions if multiple clients are attempting to delete the same identity simultaneously.

Consider enhancing the transaction isolation level or implementing row-level locking to prevent race conditions:

+       // Add an explicit lock on the external ID to prevent race conditions
+       err = db.Query.LockIdentityByExternalID(ctx, tx, db.LockIdentityByExternalIDParams{
+           WorkspaceID: auth.AuthorizedWorkspaceID,
+           ExternalID:  identity.ExternalID,
+       })
+       if err != nil {
+           return fault.Wrap(err,
+               fault.WithCode(codes.App.Internal.ServiceUnavailable.URN()),
+               fault.WithDesc("unable to lock identity", "Failed to lock identity for deletion."),
+           )
+       }

        err = db.Query.SoftDeleteIdentity(ctx, tx, identity.ID)
        if err != nil && !db.IsDuplicateKeyError(err) {
            // error handling...
        }

Alternatively, implement a more atomic deletion operation at the database level that handles this duplicate key case internally.

Committable suggestion skipped: line range outside the PR's diff.

Comment on lines +128 to +138
// Ratelimit defines model for Ratelimit.
type Ratelimit struct {
// Duration The duration for each ratelimit window in milliseconds.
Duration int64 `json:"duration"`

// Limit How many requests may pass within a given window before requests are rejected.
Limit int64 `json:"limit"`

// Name The name of this limit. You will need to use this again when verifying a key.
Name string `json:"name"`
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Keep JSON & DB numeric widths in sync

Ratelimit.Limit and Ratelimit.Duration are declared as int64, while the DB definition (go/pkg/db/models_generated.go, ratelimits.limit / ratelimits.duration) uses int32 / bigint.
If the API ever returns a value > 2³¹‑1 the insert/update will overflow and be truncated or fail. Consider:

-	Duration int64 `json:"duration"`
-	Limit    int64 `json:"limit"`
+	Duration int64 `json:"duration"` // DB: bigint – OK
+	Limit    int32 `json:"limit"`    // DB: int32 – prevent overflow mismatches

or enlarge the DB columns to BIGINT to match the API.
Both sides should agree on width to avoid silent data corruption.


I’ll verify the DB model’s field types to confirm whether Limit and Duration align with the OpenAPI struct:


🏁 Script executed:

#!/bin/bash
set -e

echo "1) Locate the generated models file"
fd models_generated.go

echo "2) Inspect the Ratelimit struct in DB models"
rg -n "type Ratelimit" -A5 go/pkg/db/models_generated.go

echo "3) Check the individual field types"
rg -n "Limit" -n go/pkg/db/models_generated.go
rg -n "Duration" -n go/pkg/db/models_generated.go

Length of output: 1866


Align numeric widths between API and DB for Ratelimit
In go/apps/api/openapi/gen.go (lines 128–138), the Ratelimit model declares both fields as int64, but in go/pkg/db/models_generated.go the DB struct uses int32 for limit and int64 (BIGINT) for duration. To avoid overflow or silent truncation, update the API model to match the DB types:

// Ratelimit defines model for Ratelimit.
type Ratelimit struct {
  // Duration The duration for each ratelimit window in milliseconds.
- Duration int64 `json:"duration"`
+ Duration int64 `json:"duration"` // DB: BIGINT – OK

  // Limit How many requests may pass within a given window before requests are rejected.
- Limit    int64 `json:"limit"`
+ Limit    int32 `json:"limit"`    // DB: INT

Alternatively, if you need higher limits, migrate the DB limit column to BIGINT. Both sides must agree on bit‑width to prevent data corruption.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Ratelimit defines model for Ratelimit.
type Ratelimit struct {
// Duration The duration for each ratelimit window in milliseconds.
Duration int64 `json:"duration"`
// Limit How many requests may pass within a given window before requests are rejected.
Limit int64 `json:"limit"`
// Name The name of this limit. You will need to use this again when verifying a key.
Name string `json:"name"`
}
// Ratelimit defines model for Ratelimit.
type Ratelimit struct {
// Duration The duration for each ratelimit window in milliseconds.
Duration int64 `json:"duration"` // DB: BIGINT – OK
// Limit How many requests may pass within a given window before requests are rejected.
Limit int32 `json:"limit"` // DB: INT
// Name The name of this limit. You will need to use this again when verifying a key.
Name string `json:"name"`
}

@chronark chronark merged commit d573dce into unkeyed:main Apr 23, 2025
2 of 5 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Oct 16, 2025
18 tasks
@coderabbitai coderabbitai bot mentioned this pull request Nov 10, 2025
19 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.

/v2/identities.deleteIdentity

2 participants