Skip to content

feat: v2/keys.updateCredits#3443

Merged
chronark merged 7 commits intounkeyed:mainfrom
Flo4604:feat/v2/keys.updateCredits
Jul 4, 2025
Merged

feat: v2/keys.updateCredits#3443
chronark merged 7 commits intounkeyed:mainfrom
Flo4604:feat/v2/keys.updateCredits

Conversation

@Flo4604
Copy link
Member

@Flo4604 Flo4604 commented Jul 3, 2025

What does this PR do?

UpdateCredits endpoint 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

    • Introduced a flexible API endpoint for updating API key credits, supporting set, increment, and decrement operations.
    • Added comprehensive error handling and permission checks for credit updates.
    • Provided detailed responses with updated credit and refill information.
  • Bug Fixes

    • Improved handling of unlimited credits and prevented negative balances on decrement.
  • Documentation

    • Updated API documentation to reflect the new credit update model and endpoint changes.
  • Tests

    • Added extensive tests for successful updates, bad requests, unauthorized access, forbidden actions, and not-found errors.
  • Chores

    • Refactored and simplified internal constants for refill intervals.

@changeset-bot
Copy link

changeset-bot bot commented Jul 3, 2025

⚠️ No Changeset found

Latest commit: ab2e17b

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 3, 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 Jul 3, 2025

📝 Walkthrough

Walkthrough

This change introduces a new, operation-based API and backend model for updating API key credits, replacing the previous refill/remaining model. It adds a new handler, OpenAPI schema, SQL queries, and tests for incrementing, decrementing, or setting credits, and updates related constants and route registration. Extensive tests cover success, error, and permission scenarios.

Changes

File(s) Change Summary
go/apps/api/openapi/gen.go, go/apps/api/openapi/openapi.yaml Replaced "updateRemaining" model with "updateCredits" model, supporting set/increment/decrement ops.
go/apps/api/routes/register.go Registered new v2/keys.updateCredits route and handler.
go/apps/api/routes/v2_apis_list_keys/handler.go
go/apps/api/routes/v2_keys_create_key/handler.go
go/apps/api/routes/v2_keys_get_key/handler.go
Updated refill interval constant references to new values (Daily, Monthly).
go/apps/api/routes/v2_keys_update_credits/handler.go Added new handler for updating credits with operation-based logic and audit logging.
go/apps/api/routes/v2_keys_update_credits/200_test.go Added integration test for successful credits update operations.
go/apps/api/routes/v2_keys_update_credits/400_test.go Added tests for invalid/bad request scenarios for credits update.
go/apps/api/routes/v2_keys_update_credits/401_test.go Added tests for unauthorized access attempts to credits update.
go/apps/api/routes/v2_keys_update_credits/403_test.go Added tests for forbidden/permission-denied scenarios for credits update.
go/apps/api/routes/v2_keys_update_credits/404_test.go Added test for not found (nonexistent key) scenario for credits update.
go/pkg/db/queries/key_update_credits.sql
go/pkg/db/queries/key_update_credits_refill.sql
Added new SQL queries for updating credits and refill settings.
go/pkg/db/key_update_credits.sql_generated.go
go/pkg/db/key_update_credits_refill.sql_generated.go
Added sqlc-generated Go code for new update queries.
go/pkg/db/querier_generated.go Added new methods to the Querier interface for credits/refill updates.
go/internal/services/ratelimit/replay.go Removed extra blank lines (no functional change).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant API_Server
    participant Auth
    participant DB
    participant AuditLog

    Client->>API_Server: POST /v2/keys.updateCredits (keyId, operation, value)
    API_Server->>Auth: Verify root key & permissions
    Auth-->>API_Server: Auth result
    API_Server->>DB: Fetch key by keyId
    DB-->>API_Server: Key data
    API_Server->>DB: Update credits (set/increment/decrement)
    DB-->>API_Server: Update result
    API_Server->>DB: (If needed) Update refill fields
    DB-->>API_Server: Update result
    API_Server->>AuditLog: Record update event
    API_Server-->>Client: 200 OK (updated credits data)
Loading

Suggested labels

🕹️ oss.gg

Suggested reviewers

  • perkinsjr
  • mcstepp
  • MichaelUnkey
  • ogzhanolguncu

📜 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 30835c9 and ab2e17b.

📒 Files selected for processing (11)
  • go/apps/api/openapi/openapi.yaml (5 hunks)
  • go/apps/api/routes/v2_keys_update_credits/200_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/400_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/403_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/404_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/handler.go (1 hunks)
  • go/pkg/db/key_update_credits.sql_generated.go (1 hunks)
  • go/pkg/db/key_update_credits_refill.sql_generated.go (1 hunks)
  • go/pkg/db/querier_generated.go (1 hunks)
  • go/pkg/db/queries/key_update_credits.sql (1 hunks)
  • go/pkg/db/queries/key_update_credits_refill.sql (1 hunks)
🧰 Additional context used
🧠 Learnings (11)
📓 Common learnings
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_update_credits_refill.sql (2)
Learnt from: chronark
PR: unkeyed/unkey#2294
File: apps/api/src/pkg/keys/service.ts:268-271
Timestamp: 2024-10-20T07:05:55.471Z
Learning: In `apps/api/src/pkg/keys/service.ts`, `ratelimitAsync` is a table relation, not a column selection. When querying, ensure that table relations are included appropriately, not as columns.
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/queries/key_update_credits.sql (1)
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.
go/apps/api/routes/v2_keys_update_credits/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/apps/api/routes/v2_keys_update_credits/200_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/key_update_credits_refill.sql_generated.go (1)
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.
go/apps/api/routes/v2_keys_update_credits/403_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/key_update_credits.sql_generated.go (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: chronark
PR: unkeyed/unkey#2294
File: apps/api/src/pkg/keys/service.ts:268-271
Timestamp: 2024-10-20T07:05:55.471Z
Learning: In `apps/api/src/pkg/keys/service.ts`, `ratelimitAsync` is a table relation, not a column selection. When querying, ensure that table relations are included appropriately, not as columns.
go/apps/api/routes/v2_keys_update_credits/handler.go (2)
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.
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/apps/api/routes/v2_keys_update_credits/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/apps/api/openapi/openapi.yaml (7)

undefined

<retrieved_learning>
Learnt from: Flo4604
PR: #3421
File: go/apps/api/openapi/openapi.yaml:196-200
Timestamp: 2025-07-03T05:58:10.669Z
Learning: In the Unkey codebase, OpenAPI 3.1 is used, which allows sibling keys (such as description) alongside $ref in schema objects. Do not flag this as an error in future reviews.
</retrieved_learning>

<retrieved_learning>
Learnt from: chronark
PR: #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.
</retrieved_learning>

<retrieved_learning>
Learnt from: chronark
PR: #2146
File: apps/dashboard/lib/trpc/routers/api/setDefaultPrefix.ts:80-80
Timestamp: 2024-10-04T17:27:08.666Z
Learning: Ensure that audit log descriptions accurately reflect the action being performed, such as updating the defaultPrefix, and avoid incorrect references like 'name' when not applicable.
</retrieved_learning>

<retrieved_learning>
Learnt from: MichaelUnkey
PR: #3173
File: apps/docs/security/delete-protection.mdx:32-36
Timestamp: 2025-04-22T17:33:28.162Z
Learning: In the Unkey dashboard UI for delete protection, the button/link to initiate the process is labeled "Disable Delete Protection" while the confirmation button is labeled "Disable API Delete Protection". The documentation should maintain these different labels to match the actual UI.
</retrieved_learning>

<retrieved_learning>
Learnt from: MichaelUnkey
PR: #3173
File: apps/docs/security/delete-protection.mdx:21-24
Timestamp: 2025-04-22T17:34:04.438Z
Learning: In the Unkey dashboard UI for enabling delete protection, the button/link to initiate the process is labeled "Enable Delete Protection" while the confirmation button is labeled "Enable API Delete Protection". The documentation should maintain these different labels to match the actual UI.
</retrieved_learning>

<retrieved_learning>
Learnt from: Flo4604
PR: #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.
</retrieved_learning>

<retrieved_learning>
Learnt from: MichaelUnkey
PR: #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.
</retrieved_learning>

🧬 Code Graph Analysis (1)
go/pkg/db/querier_generated.go (2)
go/pkg/db/key_update_credits.sql_generated.go (1)
  • UpdateKeyCreditsParams (24-28)
go/pkg/db/key_update_credits_refill.sql_generated.go (1)
  • UpdateKeyCreditsRefillParams (17-21)
🪛 YAMLlint (1.37.1)
go/apps/api/openapi/openapi.yaml

[warning] 1018-1018: too few spaces before comment: expected 2

(comments)

⏰ Context from checks skipped due to timeout of 90000ms (19)
  • 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 7/8)
  • GitHub Check: Test Go API Local / Test (Shard 5/8)
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Go API Local / Test (Shard 4/8)
  • GitHub Check: Test Go API Local / Test (Shard 3/8)
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Build / Build
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./internal/id
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./internal/resend
  • GitHub Check: Test Packages / Test ./internal/keys
  • GitHub Check: Test Packages / Test ./internal/billing
  • GitHub Check: autofix
🔇 Additional comments (4)
go/pkg/db/querier_generated.go (1)

862-876: LGTM - Generated database interface methods.

The new UpdateKeyCredits and UpdateKeyCreditsRefill methods follow the established patterns for the querier interface and correctly expose the underlying SQL operations for the new credits update functionality.

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

1-29: LGTM - Well-generated database code.

The sqlc-generated code follows proper patterns with appropriate nullable types for the refill parameters and standard error handling.

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

16-45: LGTM - Comprehensive 404 test coverage.

The test correctly verifies the handler's behavior when a non-existent key ID is provided. The test setup, request structure, and assertions properly validate the 404 response scenario.

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

4763-4776: Nice – increment/decrement examples added

The extra examples make the interactive docs and code-gen helpers far clearer. 💯

✨ 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
Copy link

vercel bot commented Jul 3, 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 4, 2025 8:00am
engineering ✅ Ready (Inspect) Visit Preview 💬 Add feedback Jul 4, 2025 8:00am

@github-actions
Copy link
Contributor

github-actions bot commented Jul 4, 2025

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

@chronark
Copy link
Collaborator

chronark commented Jul 4, 2025

I'm puzzled why vercel doesn't like you... you're in the team

Copy link
Member Author

Flo4604 commented Jul 4, 2025

Same here, especially since I just approved the vercel workflow myself 😅

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

📜 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 30835c9.

📒 Files selected for processing (18)
  • go/apps/api/openapi/gen.go (4 hunks)
  • go/apps/api/openapi/openapi.yaml (6 hunks)
  • go/apps/api/routes/register.go (2 hunks)
  • go/apps/api/routes/v2_apis_list_keys/handler.go (1 hunks)
  • go/apps/api/routes/v2_keys_create_key/handler.go (1 hunks)
  • go/apps/api/routes/v2_keys_get_key/handler.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/200_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/400_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/401_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/403_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/404_test.go (1 hunks)
  • go/apps/api/routes/v2_keys_update_credits/handler.go (1 hunks)
  • go/internal/services/ratelimit/replay.go (0 hunks)
  • go/pkg/db/key_update_credits.sql_generated.go (1 hunks)
  • go/pkg/db/key_update_credits_refill.sql_generated.go (1 hunks)
  • go/pkg/db/querier_generated.go (1 hunks)
  • go/pkg/db/queries/key_update_credits.sql (1 hunks)
  • go/pkg/db/queries/key_update_credits_refill.sql (1 hunks)
💤 Files with no reviewable changes (1)
  • go/internal/services/ratelimit/replay.go
🧰 Additional context used
🧠 Learnings (15)
📓 Common learnings
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_update_credits_refill.sql (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/apps/api/routes/v2_keys_create_key/handler.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/apps/api/routes/v2_keys_get_key/handler.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/apps/api/routes/v2_keys_update_credits/401_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_update_credits.sql (1)
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.
go/apps/api/routes/v2_keys_update_credits/200_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/apps/api/routes/v2_keys_update_credits/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/apps/api/routes/v2_keys_update_credits/403_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/apps/api/routes/v2_keys_update_credits/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/key_update_credits.sql_generated.go (1)
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.
go/apps/api/routes/v2_keys_update_credits/handler.go (1)
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/key_update_credits_refill.sql_generated.go (1)
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.
go/apps/api/openapi/gen.go (1)

undefined

<retrieved_learning>
Learnt from: MichaelUnkey
PR: #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.
</retrieved_learning>

go/apps/api/openapi/openapi.yaml (4)

undefined

<retrieved_learning>
Learnt from: Flo4604
PR: #3421
File: go/apps/api/openapi/openapi.yaml:196-200
Timestamp: 2025-07-03T05:58:10.669Z
Learning: In the Unkey codebase, OpenAPI 3.1 is used, which allows sibling keys (such as description) alongside $ref in schema objects. Do not flag this as an error in future reviews.
</retrieved_learning>

<retrieved_learning>
Learnt from: chronark
PR: #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.
</retrieved_learning>

<retrieved_learning>
Learnt from: MichaelUnkey
PR: #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.
</retrieved_learning>

<retrieved_learning>
Learnt from: Flo4604
PR: #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.
</retrieved_learning>

🧬 Code Graph Analysis (4)
go/apps/api/routes/v2_apis_list_keys/handler.go (2)
go/apps/api/openapi/gen.go (2)
  • Daily (20-20)
  • Monthly (21-21)
go/pkg/db/models_generated.go (1)
  • Key (300-324)
go/apps/api/routes/v2_keys_create_key/handler.go (1)
go/apps/api/openapi/gen.go (1)
  • Monthly (21-21)
go/apps/api/routes/v2_keys_get_key/handler.go (1)
go/apps/api/openapi/gen.go (2)
  • Daily (20-20)
  • Monthly (21-21)
go/pkg/db/querier_generated.go (2)
go/pkg/db/key_update_credits.sql_generated.go (1)
  • UpdateKeyCreditsParams (24-28)
go/pkg/db/key_update_credits_refill.sql_generated.go (1)
  • UpdateKeyCreditsRefillParams (17-21)
🪛 YAMLlint (1.37.1)
go/apps/api/openapi/openapi.yaml

[warning] 1018-1018: too few spaces before comment: expected 2

(comments)

🔇 Additional comments (16)
go/apps/api/routes/v2_apis_list_keys/handler.go (1)

382-384: LGTM: Refill interval constant updates are correct.

The updates from the old enum constants to the simplified openapi.Daily and openapi.Monthly constants are consistent with the broader refactoring and align with the new definitions in go/apps/api/openapi/gen.go.

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

292-292: LGTM: Refill interval constant update is correct.

The update to use openapi.Monthly instead of the previous enum constant is consistent with the refactoring and aligns with the new constant definitions.

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

42-42: LGTM: Import for new handler added correctly.

The import for v2KeysUpdateCredits follows the established naming pattern and is placed appropriately with other v2/keys imports.


367-377: LGTM: Route registration is well-structured.

The registration for the new v2/keys.updateCredits endpoint follows the established pattern with:

  • Proper middleware usage (defaultMiddlewares)
  • All required dependencies injected (Logger, DB, Keys, Permissions, Auditlogs)
  • Logical placement within the v2/keys section
go/apps/api/routes/v2_keys_get_key/handler.go (1)

241-243: LGTM: Refill interval constant updates are correct.

The updates to use openapi.Daily and openapi.Monthly instead of the previous enum constants are consistent with the refactoring and maintain consistency across route handlers.

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

1-9: LGTM! Solid approach to credit operations with safety measures.

The CASE-based approach correctly handles all three operations (set, increment, decrement) and includes proper safeguards to prevent negative credit values during decrement operations.

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

19-147: Excellent comprehensive authorization test coverage.

The test suite properly covers all critical authorization failure scenarios:

  • Missing authorization header
  • Empty authorization header
  • Malformed headers (no Bearer prefix, Bearer only)
  • Invalid/nonexistent tokens

The test setup is thorough and the status code expectations are correct (400 for malformed requests, 401 for invalid credentials).

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

862-876: Generated interface methods follow established patterns correctly.

The new UpdateKeyCredits and UpdateKeyCreditsRefill methods are properly generated and consistent with the existing codebase patterns. Method signatures, documentation, and parameter handling all align with the established conventions.

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

1-29: Standard generated code follows established patterns.

The generated code for UpdateKeyCreditsRefill is consistent with the codebase standards. The SQL query, parameter struct, and method implementation all follow the established patterns correctly.

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

35-45: Correct 404 test implementation.

The test properly verifies that a non-existent key ID returns a 404 status with an appropriate error message. The setup and assertions are correct for this scenario.

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

15-20: Good implementation of preventing negative credits

The CASE statement properly handles decrement operations to prevent negative balances by setting to 0 when the result would be negative.

go/apps/api/routes/v2_keys_update_credits/403_test.go (1)

21-193: Comprehensive permission and access control testing

Excellent coverage of various authorization scenarios including no permissions, wrong permissions, cross-workspace, and cross-API access. The test properly validates that the endpoint enforces strict permission boundaries.

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

147-149: Verify integer overflow safety

The conversion from int64 to int32 uses nolint:gosec. Ensure this is safe by validating the input range.

Consider adding validation to ensure the value fits in int32:

 if !req.Value.IsNull() && req.Value.IsSpecified() {
+    if reqVal > math.MaxInt32 || reqVal < math.MinInt32 {
+        return fault.New("value out of range",
+            fault.Code(codes.App.Validation.InvalidInput.URN()),
+            fault.Internal("value exceeds int32 range"),
+            fault.Public("The provided value is out of the acceptable range."),
+        )
+    }
     credits = sql.NullInt32{Int32: int32(reqVal), Valid: true} // nolint:gosec
 }

124-130: Good validation for operation requirements

The validation properly ensures that increment/decrement operations must include a value, preventing undefined behavior.


151-242: Well-structured transaction handling

The use of TxWithResult ensures atomic updates for both credits and refill data, with proper error handling and rollback on failure. The audit logging is comprehensive and captures all relevant information.

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

19-22: LGTM! Well-structured implementation of the new credit update system.

The changes introduce a clean, operation-based API for updating credits with:

  • Clear operation types (set, increment, decrement)
  • Comprehensive documentation explaining edge cases
  • Proper use of nullable types for the optional value field
  • Consistent naming patterns with the rest of the codebase

The transition from the previous updateRemaining model to this more flexible updateCredits approach provides better control over credit operations.

Also applies to: 37-42, 1566-1605, 2243-2244

Copy link
Collaborator

chronark commented Jul 4, 2025

did you add your github account in vercel? I think the email doesn’t match your github and that’s why

Copy link
Collaborator

chronark commented Jul 4, 2025

Copy link
Member Author

Flo4604 commented Jul 4, 2025

whoops

Copy link
Member Author

Flo4604 commented Jul 4, 2025

now I did

@chronark chronark enabled auto-merge July 4, 2025 09:43
@chronark chronark disabled auto-merge July 4, 2025 10:01
@chronark chronark merged commit 22899d5 into unkeyed:main Jul 4, 2025
102 of 134 checks passed
@Flo4604 Flo4604 deleted the feat/v2/keys.updateCredits branch July 4, 2025 10:24
@coderabbitai coderabbitai bot mentioned this pull request Sep 12, 2025
18 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants