Conversation
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
1 Skipped Deployment
|
|
Caution Review failedThe pull request is closed. 📝 WalkthroughWalkthroughThis pull request introduces a comprehensive update to Unkey’s error handling and documentation for the v2 API. New documentation pages have been added detailing structured JSON error responses for various error types and categorizing them with URN-like error codes. In parallel, the Go codebase has been refactored to replace generic fault tags with structured error codes using a new Changes
Sequence Diagram(s)sequenceDiagram
participant C as Client
participant A as API Gateway/Route
participant H as Handler
participant DB as Database
participant EH as Error Handler (fault & codes)
C->>A: Sends API request
A->>H: Forwards request to handler
H->>DB: Performs operations (e.g., DB query)
DB-->>H: Returns error (e.g., not found)
H->>EH: Wraps error using fault.WithCode(codes.XXX)
EH-->>H: Returns structured error with URN and documentation URL
H-->>A: Sends error response
A-->>C: Returns JSON error response with code and DocsURL
Possibly related PRs
Suggested reviewers
Tip ⚡💬 Agentic Chat (Pro Plan, General Availability)
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
|
Thank you for following the naming conventions for pull request titles! 🙏 |
|
There was a problem hiding this comment.
Actionable comments posted: 7
🔭 Outside diff range comments (4)
go/apps/api/routes/v2_ratelimit_get_override/400_test.go (1)
35-111: 💡 Verification agent🧩 Analysis chain
Consider updating remaining error URLs.
While one error URL has been updated to the new format (
invalid_input), there are still several other assertions in this test file that use the old URL format (https://unkey.com/docs/errors/bad_request). For consistency, consider updating all error URLs to the new format.
🏁 Script executed:
#!/bin/bash # Search for other tests that still use the old error URL format rg "https://unkey.com/docs/errors/bad_request" --type go -A 1 -B 1Length of output: 7857
Update Legacy Error URLs for Consistency
Several tests—both in this file and across others—still reference the old error URL (
https://unkey.com/docs/errors/bad_request). While you've updated one instance to the new format (e.g., using/errors-v2/unkey/data/invalid_input), the following files still use the legacy URL:
- go/apps/api/routes/v2_ratelimit_get_override/400_test.go (in three out of four test cases)
- go/apps/api/routes/v2_ratelimit_set_override/400_test.go
- go/apps/api/routes/v2_ratelimit_limit/400_test.go
- go/apps/api/routes/v2_ratelimit_delete_override/400_test.go
- go/apps/api/routes/v2_identities_create_identity/400_test.go
- go/apps/api/routes/v2_apis_create_api/400_test.go
For uniformity and clarity, please update all assertions to use the new error URL format consistently.
apps/www/content/blog/zen.mdx (1)
174-220: 🛠️ Refactor suggestionUpdate error handling middleware to use new code-based approach.
While the code examples have been updated to use the new
WithCodemethod, the error handling middleware example still uses the old tag-based approach withswitch fault.GetTag(err). This should be updated to maintain consistency with the new error code system.func WithErrorHandling(logger logging.Logger) Middleware { return func(next HandleFunc) HandleFunc { return func(ctx context.Context, s *Session) error { err := next(ctx, s) if err == nil { return nil } // Convert domain errors to HTTP responses - switch fault.GetTag(err) { - case fault.NOT_FOUND: + code, ok := fault.GetCode(err) + if !ok { + // Default to 500 Internal Server Error + // [... default error handling ...] + return s.JSON(http.StatusInternalServerError, api.InternalServerError{ + // ... fields ... + }) + } + + switch code { + case codes.Data.NotFound.URN(): return s.JSON(http.StatusNotFound, api.NotFoundError{ Title: "Not Found", Type: "https://unkey.com/docs/errors/not_found", Detail: fault.UserFacingMessage(err), RequestId: s.requestID, Status: http.StatusNotFound, Instance: nil, }) - case fault.BAD_REQUEST: + case codes.Validation.BadRequest.URN(): return s.JSON(http.StatusBadRequest, api.BadRequestError{ // ... fields ... }) // Additional cases... }go/apps/api/routes/v2_ratelimit_delete_override/handler.go (1)
42-49: 🛠️ Refactor suggestionAdd specific error code for invalid request body.
While you've updated most error codes to use the new structured URN system, the invalid request body error is missing a specific error code. Consider adding it for consistency with the rest of the error handling in this file.
return fault.Wrap(err, + fault.WithCode(codes.App.Validation.InvalidInput.URN()), fault.WithDesc("invalid request body", "The request body is invalid."), )go/pkg/zen/middleware_errors.go (1)
181-203: 🛠️ Refactor suggestionDefaulting “internal” and “service_unavailable” to 500.
Consider returning 503 forservice_unavailableerrors instead of 500. It gives clients a clearer signal that a subsequent retry might succeed when the service recovers.- case codes.UnkeyAppErrorsInternalServiceUnavailable, - ... - // Fall through to default 500 error + case codes.UnkeyAppErrorsInternalServiceUnavailable: + return s.JSON(http.StatusServiceUnavailable, ...)
🧹 Nitpick comments (64)
go/apps/api/routes/reference/handler.go (2)
11-39: Enhance security and performance of the reference pageThe implementation looks good, but consider these improvements:
- Add Subresource Integrity (SRI) to the external script to prevent security issues:
- <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script> + <script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference" + integrity="sha384-INTEGRITY_HASH_HERE" + crossorigin="anonymous"></script>
- Add cache headers to improve performance for returning visitors:
return zen.NewRoute("GET", "/reference", func(ctx context.Context, s *zen.Session) error { s.AddHeader("Content-Type", "text/html") + s.AddHeader("Cache-Control", "public, max-age=3600") return s.Send(200, []byte(html)) })You can generate the SRI hash for the script using:
How to generate SRI hash for CDN scripts
29-32: Consider loading the API spec asynchronouslyFor large API specs, embedding the entire specification directly in the HTML can lead to large page sizes and slower initial loading.
Consider loading the API spec asynchronously or providing it as a separate endpoint that the reference page can fetch. This would improve the initial page load time, especially for large API specifications.
go/pkg/zen/auth.go (2)
10-14: Update the function documentation to match the new error handling approach.The current comment mentions "BAD_REQUEST tag" but the implementation now uses specific authentication error codes from the new structured system.
- // If the header is missing, malformed, or contains an empty token, - // an appropriate error is returned with the BAD_REQUEST tag. + // If the header is missing, malformed, or contains an empty token, + // an appropriate error is returned with Authentication.Missing or Authentication.Malformed error codes.
39-39: Good use of error codes, but consider adding descriptive message.While the error code is properly implemented, consider adding a descriptive message with
WithDescsimilar to line 33 to provide more guidance to API users.- return "", fault.New("invalid token", fault.WithCode(codes.Auth.Authentication.Malformed.URN())) + return "", fault.New("invalid token", fault.WithCode(codes.Auth.Authentication.Malformed.URN()), + fault.WithDesc("empty token", "Your authorization header contains an empty token after the 'Bearer ' prefix."))apps/docs/api-reference/errors/code/METHOD_NOT_ALLOWED.mdx (1)
38-40: Consider adding more specific API documentation links.The related resources section could be expanded to include direct links to HTTP method-specific documentation for key endpoints, which would help users quickly find the correct method for their intended operation.
## Related Resources - [API Reference Overview](/api-reference/authentication) - [REST API Best Practices](https://docs.unkey.dev/best-practices/api-usage) +- [Creating Keys (POST)](/api-reference/keys/create) +- [Retrieving Keys (GET)](/api-reference/keys/get) +- [HTTP Methods Explained](https://docs.unkey.dev/api-concepts/http-methods)go/pkg/codes/doc.go (1)
6-15: Consider adding example usage.The documentation could be enhanced by including a concrete example of how to define and use error codes with this package. This would further improve developer onboarding.
This package is used across all Unkey services to ensure consistency in error reporting and handling. It also provides utilities for parsing error codes from strings and generating documentation URLs. + +Example usage: + + // Defining an error code + var MySystem = struct { + MyCategory struct { + SpecificError struct { + URN func() string + } + } + }{} + + // Using an error code + fault.New("operation failed", fault.WithCode(MySystem.MyCategory.SpecificError.URN())) */apps/docs/api-reference/errors-v2/unkey/application/invalid_input.mdx (2)
60-60: Consider using a more formal verb.For documentation consistency, consider rephrasing this line to use more formal language.
-3. Look at the `fix` field (if available) for guidance on how to correct the issue +3. Look at the `fix` field (if available) for guidance on how to resolve the issue🧰 Tools
🪛 LanguageTool
[style] ~60-~60: Consider using a different verb for a more formal wording.
Context: ...d (if available) for guidance on how to correct the issue 4. Modify your request to com...(FIX_RESOLVE)
81-81: Remove redundant phrasing.The phrase "outside of" is redundant. Consider using just "outside".
-- **Range violations**: Providing values outside of allowed ranges (too small, too large) +- **Range violations**: Providing values outside allowed ranges (too small, too large)🧰 Tools
🪛 LanguageTool
[style] ~81-~81: This phrase is redundant. Consider using “outside”.
Context: ... Range violations: Providing values outside of allowed ranges (too small, too large) -...(OUTSIDE_OF)
go/pkg/assert/assert.go (1)
12-12: Update function documentation to reflect the new error system.The function documentation still mentions errors being "tagged with ASSERTION_FAILED" but the implementation now uses the URN-based codes. Consider updating the documentation to reflect this change.
For example, for the
Equalfunction:// Equal asserts that two values of the same comparable type are equal. -// If the values are not equal, it returns an error tagged with ASSERTION_FAILED. +// If the values are not equal, it returns an error with the AssertionFailed error code.This change should be applied to all assertion function documentation for consistency.
Also applies to: 32-32, 51-51, 70-70, 90-90, 110-110, 130-130, 150-150, 170-170, 194-194, 219-219, 244-244, 267-267
go/pkg/fault/code.go (1)
1-35: Solid implementation of GetCode function.The
GetCodefunction correctly traverses the error chain to find the first associated code, handling nil errors appropriately. The function is well-documented with an example, though the example still references the old tag-based system (Tag(DATABASE_ERROR)) while the implementation uses the new code-based system.Update the example in the function documentation to reflect the new code-based approach:
// err := errors.New("base error") -// withTag := Tag(DATABASE_ERROR)(err) +// withCode := WithCode(codes.Data.Database.Error.URN())(err) // wrapped := fmt.Errorf("wrapped: %w", withTag) // code, ok := GetCode(wrapped) -// Output: DATABASE_ERROR, true +// Output: codes.Data.Database.Error.URN(), trueapps/docs/api-reference/errors-v2/unkey/data/key_not_found.mdx (2)
1-74: Well-structured error documentation with clear examples and resolution steps.This new documentation for the
err:unkey:data:key_not_founderror is comprehensive and user-friendly. It clearly explains what triggers the error, provides practical examples, and offers concrete resolution steps.One suggestion to enhance the documentation:
Consider adding a link to the API reference for the
keys.createKeyendpoint mentioned in line 50, similar to how you've linked to other resources.🧰 Tools
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
35-41: Ensure example curl commands use placeholders consistentlyThe curl examples use placeholder values for API keys which is good practice, but there's an inconsistency in the format:
- First example uses
unkey_YOUR_API_KEY- Second example uses
unkey_YOUR_API_KEYThis is consistent within this file, but I noticed other documentation files might use different formats like
your_api_key.Consider standardizing the placeholder format across all documentation files for consistency.
Also applies to: 55-61
🧰 Tools
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
apps/docs/api-reference/errors/code/USAGE_EXCEEDED.mdx (1)
21-28: Inconsistent API URL in exampleThe curl example uses
https://api.unkey.devwhile the other documentation file useshttps://api.unkey.com.- curl -X PUT "https://api.unkey.dev/v1/keys.updateRemaining" \ + curl -X PUT "https://api.unkey.com/v1/keys.updateRemaining" \go/apps/api/routes/v2_ratelimit_limit/401_test.go (1)
62-62: Error type URL uses hardcoded domainThe test is checking for a specific error type URL that includes the domain 'unkey.com'.
Consider using a constant for the base URL part of the error documentation to make it easier to change if needed:
- require.Equal(t, "https://unkey.com/docs/api-reference/errors-v2/unkey/authentication/malformed", res.Body.Error.Type) + require.Equal(t, constants.ErrorDocsBaseURL + "/unkey/authentication/malformed", res.Body.Error.Type)apps/docs/api-reference/errors-v2/overview.mdx (1)
1-81: Well-structured documentation for the new error system.This new documentation clearly explains the structured approach to error handling with URN-like format, breaking down the components and providing examples. The JSON response format example is also helpful.
The categorization by system and error type provides a good foundation for organizing errors across the platform.
Minor improvement suggestions:
- In line 46, consider using a hyphen for "quota-related" to be consistent with other hyphenated adjectives.
- In line 70, there appears to be a redundant word "type" that could be removed.
-the error type +the error🧰 Tools
🪛 LanguageTool
[uncategorized] ~46-~46: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ... operations and resources - limits: Rate limiting or quota-related errors ## Error Respo...(EN_COMPOUND_ADJECTIVE_INTERNAL)
[duplication] ~70-~70: Possible typo: you repeated a word.
Context: ...- title: Short summary of the error type - type: URL to detailed documentation about ...(ENGLISH_WORD_REPEAT_RULE)
apps/docs/api-reference/errors-v2/unkey/authentication/malformed.mdx (1)
81-82: Consider expanding on copying errors explanation.The "Extra characters" and "Copying errors" bullet points could benefit from more specific examples, particularly for invisible characters that might be hard to detect.
- - **Copying errors**: Check for invisible characters or line breaks that might have been copied - - **Extra characters**: Including quotes or other characters around the API key + - **Copying errors**: Check for invisible characters (like zero-width spaces) or line breaks that might have been copied from rich text editors or documentation + - **Extra characters**: Including quotes, brackets, or other characters around the API key (e.g., "unkey_YOUR_API_KEY" or 'unkey_YOUR_API_KEY')apps/docs/api-reference/errors-v2/unkey/authentication/key_not_found.mdx (1)
49-54: Consider adding dashboard screenshot or linking to specific dashboard sections.The steps to check and use the correct Unkey API key could be enhanced with a visual reference or more specific navigation paths within the dashboard.
1. Log in to your Unkey dashboard -2. Navigate to the API keys section +2. Navigate to the API keys section (under "Settings" > "API Keys") 3. Copy the appropriate API key for your environment 4. Use the key in your request as shown belowapps/docs/api-reference/errors-v2/unkey/data/invalid_input.mdx (2)
80-84: Minor wording improvements in common mistakes section.There are a couple of minor style issues that could be addressed for better readability.
- - **Range violations**: Providing values outside of allowed ranges (too small, too large) + - **Range violations**: Providing values outside allowed ranges (too small, too large)🧰 Tools
🪛 LanguageTool
[style] ~81-~81: This phrase is redundant. Consider using “outside”.
Context: ... Range violations: Providing values outside of allowed ranges (too small, too large) -...(OUTSIDE_OF)
56-61: Consider adding a note about programmatic handling of validation errors.For developers building automated systems or SDKs, some guidance on programmatically handling the
errorsarray would be beneficial.To fix this error, carefully review the error details provided in the response. The `errors` array contains specific information about what failed validation: 1. Check the `location` field to identify which part of your request is problematic 2. Read the `message` field for details about why validation failed 3. Look at the `fix` field (if available) for guidance on how to correct the issue 4. Modify your request to comply with the validation requirements + +For automated systems, you can programmatically handle these errors by parsing the `errors` array and applying fixes based on the `location` and `message` fields. This is especially useful when building SDKs or client libraries.🧰 Tools
🪛 LanguageTool
[style] ~60-~60: Consider using a different verb for a more formal wording.
Context: ...d (if available) for guidance on how to correct the issue 4. Modify your request to com...(FIX_RESOLVE)
apps/docs/api-reference/errors/code/FORBIDDEN.mdx (1)
21-23: Remove potentially sensitive authentication headerThe curl example includes an authentication header that could be flagged as a potential security issue by static analysis tools. Consider using a placeholder or noting that this is just an example.
- curl -X GET "https://api.unkey.dev/v1/keys/{keyId}" \ - -H "Authorization: Bearer your_api_key" + curl -X GET "https://api.unkey.dev/v1/keys/{keyId}" \ + -H "Authorization: Bearer {your_api_key}"apps/docs/api-reference/errors/code/NOT_FOUND.mdx (2)
9-16: Common Causes Section
The list of common causes is comprehensive and effectively covers realistic scenarios that lead to a NOT_FOUND error. Consider reviewing the punctuation and consistency of the list items to ensure a uniform style.
17-26: Resolution Steps Enhancement
The step-by-step guidance is clear and actionable. As a minor refinement, consider rephrasing “before trying to modify it:” to “before attempting to modify it:” for a slightly more formal tone.🧰 Tools
🪛 LanguageTool
[style] ~20-~20: You have already used ‘trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ... to check if the resource exists before trying to modify it: ```bash # Example: Che...(REP_TRY)
🪛 Gitleaks (8.21.2)
21-22:
(curl-auth-header)
apps/docs/api-reference/errors/code/CONFLICT.mdx (1)
9-16: Common Causes Section
The bullet list covers several realistic scenarios leading to a conflict error. One suggestion is to double-check phrasing (e.g. “Creating a permission with an identifier that's already in use”) for absolute clarity.🧰 Tools
🪛 LanguageTool
[grammar] ~12-~12: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...ace slug that already exists - Creating a permission with an identifier that's already in us...(A_UNCOUNTABLE_NOUN)
apps/docs/api-reference/errors/code/DELETE_PROTECTED.mdx (1)
24-28: Resolution Step 2 - Remove Protection Guidance
The dashboard-based guidance is practical. It might be helpful to include a brief note on the potential risks associated with disabling deletion protection before proceeding.apps/docs/api-reference/errors-v2/unkey/application/protected_resource.mdx (3)
21-24: What Happened Section
The explanation outlines when the error is triggered in a clear manner. As a minor note, consider adding an article for enhanced readability (e.g., “in the Unkey system”).🧰 Tools
🪛 LanguageTool
[uncategorized] ~23-~23: Possible missing article found.
Context: ... Unkey system. Protected resources have special status that prevents them from being ch...(AI_HYDRA_LEO_MISSING_A)
31-41: Example Request Section
The provided cURL command helps users visualize a problematic request. Double-check the endpoint (/v1/apis.deleteApi) to ensure consistency with established naming conventions.
43-51: How To Fix Section
The instructions are clear; however, consider rephrasing “rather than trying to change them:” to “rather than modifying them:” for a more formal tone.🧰 Tools
🪛 LanguageTool
[style] ~45-~45: You have already used ‘trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ...to work with or around them rather than trying to change them: 1. **Work with the protec...(REP_TRY)
apps/docs/api-reference/errors-v2/unkey/data/assertion_failed.mdx (1)
23-23: Fix missing comma in sentence structure.There's a missing comma in this sentence between "errors" and "which".
-This error occurs when Unkey's internal system detects an inconsistency or violation of its expected invariants during the processing of your request. Unlike validation errors which occur when your input is invalid, assertion failures happen when the system's internal state doesn't match what was expected. +This error occurs when Unkey's internal system detects an inconsistency or violation of its expected invariants during the processing of your request. Unlike validation errors, which occur when your input is invalid, assertion failures happen when the system's internal state doesn't match what was expected.🧰 Tools
🪛 LanguageTool
[uncategorized] ~23-~23: Possible missing comma found.
Context: ...sing of your request. Unlike validation errors which occur when your input is invalid,...(AI_HYDRA_LEO_MISSING_COMMA)
apps/docs/api-reference/errors-v2/unkey/authorization/workspace_disabled.mdx (1)
48-48: Missing article in textAdd "the" before "workspace administrator" for better readability.
- 2. **Contact workspace administrator**: If you're not the workspace administrator, contact them to determine why the workspace was disabled + 2. **Contact the workspace administrator**: If you're not the workspace administrator, contact them to determine why the workspace was disabled🧰 Tools
🪛 LanguageTool
[uncategorized] ~48-~48: You might be missing the article “the” here.
Context: ...key.com/settings/billing) 2. Contact workspace administrator: If you're not the work...(AI_EN_LECTOR_MISSING_DETERMINER_THE)
apps/docs/api-reference/errors-v2/unkey/data/role_not_found.mdx (1)
34-42: Consider sanitizing example authorization valuesWhile these are just example API calls, it would be a good practice to clearly indicate placeholder values in authorization headers to prevent any confusion.
- curl -X POST https://api.unkey.com/v1/roles.addPermission \ - -H "Content-Type: application/json" \ - -H "Authorization: Bearer unkey_YOUR_API_KEY" \ + curl -X POST https://api.unkey.com/v1/roles.addPermission \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer unkey_<YOUR_API_KEY>" \🧰 Tools
🪛 Gitleaks (8.21.2)
36-37:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/authorization/forbidden.mdx (1)
1-74: Comprehensive documentation with clear examples and actionable guidance.The documentation provides excellent context about when this error occurs, along with practical examples and resolution steps. The structured format with sections for "What Happened?", "How To Fix", and "Common Mistakes" creates a consistent learning experience.
Consider varying the phrasing in these sections to avoid repetition of "trying to":
- The operation you're trying to perform may be: + The operation you're attempting to perform may be: - **Resource state issues**: Trying to modify resources that are in a state th... + **Resource state issues**: Attempting to modify resources that are in a state th... - **Testing security boundaries**: Deliberately trying to access protected resources + **Testing security boundaries**: Deliberately attempting to access protected resources🧰 Tools
🪛 LanguageTool
[style] ~45-~45: You have already used ‘trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ... permission issue. The operation you're trying to perform may be: 1. **Not supported by ...(REP_TRY)
[style] ~65-~65: You have already used ‘Trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ...rrent plan - Resource state issues: Trying to modify resources that are in a state th...(REP_TRY)
[style] ~67-~67: You have already used ‘trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ...ing security boundaries**: Deliberately trying to access protected resources - **Outdated...(REP_TRY)
apps/docs/api-reference/errors/code/EXPIRED.mdx (2)
6-53: Greatly improved documentation with actionable resolution steps.The restructuring of this document with expanded sections provides much clearer guidance for users. The detailed resolution steps with example code make troubleshooting more straightforward.
Consider adding a human-readable date comment next to the timestamp for better clarity:
- "expires": 1672531200000 # Set to a future timestamp (milliseconds since epoch) + "expires": 1672531200000 # Set to a future timestamp (milliseconds since epoch, e.g., Jan 1, 2023)🧰 Tools
🪛 Gitleaks (8.21.2)
23-24:
(curl-auth-header)
19-22: Secure your authentication examples.The curl example includes an authentication header with a placeholder value that could be mistaken for an actual token.
Consider making it clearer this is a placeholder with a more explicit placeholder name:
- -H "Authorization: Bearer your_api_key" + -H "Authorization: Bearer YOUR_UNKEY_API_KEY"apps/docs/api-reference/errors-v2/unkey/data/key_auth_not_found.mdx (2)
7-19: JSON Example: Correct Structure
The JSON example correctly illustrates the expected error response. One suggestion is to ensure consistent indentation and spacing for improved readability.
21-30: Error Explanation & Common Scenarios
The "What Happened?" section and the bullet list of common scenarios are well written. Consider rephrasing the bullet “Typos in identifiers” to “Typographical errors in identifiers” for clarity.🧰 Tools
🪛 LanguageTool
[grammar] ~28-~28: The plural noun “Typos” cannot be used with the article “a”. Did you mean “a non-existent record typo” or “non-existent record Typos”?
Context: ...g to update authentication settings for a non-existent record - Typos in identifiers Here's an example of a ...(A_NNS)
apps/docs/api-reference/errors/code/TOO_MANY_REQUESTS.mdx (1)
17-35: Backoff and Retry Implementation in JavaScript
The provided JavaScript snippet for implementing exponential backoff is clear. One minor suggestion: consider explicitly converting the value returned byresponse.headers.get('Retry-After')to a number (if it exists) to prevent any unexpected behavior. For example:- const retryAfter = response.headers.get('Retry-After') || Math.pow(2, attempt); + const retryAfter = Number(response.headers.get('Retry-After')) || Math.pow(2, attempt);🧰 Tools
🪛 Gitleaks (8.21.2)
21-22:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/permission_not_found.mdx (1)
21-30: Error Description and Scenario Listing
The explanation under "What Happened?" and the subsequent bullet list clearly outline when this error occurs.
Note: Several bullets (e.g., “Using an incorrect permission ID or name”, “Referencing a permission that has been deleted”, “Trying to assign a permission that doesn't exist in the current workspace”) may benefit from removing the article "a" for improved grammatical consistency (e.g., "Using an incorrect permission ID or name" → "Using incorrect permission ID or name").🧰 Tools
🪛 LanguageTool
[grammar] ~23-~23: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...ou're trying to perform an operation on a permission that doesn't exist in the Unkey system....(A_UNCOUNTABLE_NOUN)
[grammar] ~27-~27: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...ect permission ID or name - Referencing a permission that has been deleted - Trying to assig...(A_UNCOUNTABLE_NOUN)
[grammar] ~28-~28: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...hat has been deleted - Trying to assign a permission that doesn't exist in the current works...(A_UNCOUNTABLE_NOUN)
apps/docs/api-reference/errors-v2/unkey/data/audit_log_not_found.mdx (1)
42-50: How To Fix: Clear Troubleshooting Steps
The troubleshooting steps are comprehensive.
Note: Consider adding a comma after "automatically deleted" to improve readability. For instance:-4. Consider that audit logs might have a retention period after which they're automatically deleted +4. Consider that audit logs might have a retention period, after which they're automatically deleted🧰 Tools
🪛 LanguageTool
[uncategorized] ~49-~49: Possible missing comma found.
Context: ... that audit logs might have a retention period after which they're automatically delet...(AI_HYDRA_LEO_MISSING_COMMA)
apps/docs/api-reference/errors-v2/unkey/data/workspace_not_found.mdx (1)
33-41: Consider adding a note about the API key placeholder.While the example is clear, it's good practice to explicitly mention that
unkey_YOUR_API_KEYis a placeholder that should be replaced with the user's actual API key.curl -X POST https://api.unkey.com/v1/keys.listKeys \ -H "Content-Type: application/json" \ - -H "Authorization: Bearer unkey_YOUR_API_KEY" \ + -H "Authorization: Bearer unkey_YOUR_API_KEY" \ # Replace with your actual API key -d '{ "workspaceId": "ws_nonexistent" }'🧰 Tools
🪛 Gitleaks (8.21.2)
36-37:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/application/service_unavailable.mdx (1)
32-42: Consider adding a note about the API key placeholder.Similar to the previous file, it would be good to explicitly mention that
unkey_YOUR_API_KEYis a placeholder.curl -X POST https://api.unkey.com/v1/keys.createKey \ -H "Content-Type: application/json" \ - -H "Authorization: Bearer unkey_YOUR_API_KEY" \ + -H "Authorization: Bearer unkey_YOUR_API_KEY" \ # Replace with your actual API key -d '{ "apiId": "api_123abc", "name": "My API Key" }'apps/docs/api-reference/errors/code/DISABLED.mdx (3)
18-27: Remove the API key placeholder from example code.The example code currently includes a placeholder that could be mistaken for a real API key. Replace "Bearer your_api_key" with something more obvious like "Bearer YOUR_API_KEY" to avoid potential confusion or security issues.
- -H "Authorization: Bearer your_api_key" \ + -H "Authorization: Bearer YOUR_API_KEY" \🧰 Tools
🪛 Gitleaks (8.21.2)
23-24:
(curl-auth-header)
36-38: Use consistent API key placeholder format.For consistency with other examples in the documentation, use the same placeholder format for API keys.
- -H "Authorization: Bearer your_api_key" \ + -H "Authorization: Bearer YOUR_API_KEY" \
47-50: Make related resources links more specific.The links to related resources are helpful, but consider adding brief descriptions about what users will find at each link to help users decide which resource is most relevant to their needs.
-## Related Resources -- [Updating Keys](/api-reference/keys/update) -- [Creating New Keys](/api-reference/keys/create) -- [Workspace Management](/workspaces/overview) +## Related Resources +- [Updating Keys](/api-reference/keys/update) - Learn how to enable or modify existing keys +- [Creating New Keys](/api-reference/keys/create) - Instructions for creating replacement keys +- [Workspace Management](/workspaces/overview) - Manage workspace settings and statusapps/docs/api-reference/errors-v2/unkey/authorization/insufficient_permissions.mdx (1)
33-42: Add comments about the expected response.The example shows how to trigger the error but doesn't show what the response would look like. Consider adding a comment showing the expected error response to help users recognize when they hit this error.
# Using a read-only key to create a new API key curl -X POST https://api.unkey.com/v1/keys.createKey \ -H "Content-Type: application/json" \ -H "Authorization: Bearer unkey_READ_ONLY_KEY" \ -d '{ "apiId": "api_123", "name": "New API Key" }' + +# Expected response: +# { +# "meta": { "requestId": "req_abc123" }, +# "error": { +# "detail": "The authenticated API key does not have permission to perform this operation", +# "status": 403, +# "title": "Forbidden", +# "type": "https://unkey.com/docs/api-reference/errors-v2/unkey/authorization/insufficient_permissions" +# } +# }apps/docs/api-reference/errors-v2/unkey/data/ratelimit_override_not_found.mdx (1)
54-61: Consider adding pagination parameters.If the namespace might contain many overrides, it would be helpful to mention pagination parameters in the example for listing overrides. This would help users efficiently handle large collections.
curl -X POST https://api.unkey.com/v2/ratelimit.listOverrides \ -H "Content-Type: application/json" \ -H "Authorization: Bearer unkey_YOUR_API_KEY" \ -d '{ "namespaceId": "ns_123abc" + "limit": 100, + "cursor": "optional_pagination_cursor" }'go/pkg/codes/unkey_application.go (1)
28-40: Validate struct grouping for maintainability.
UnkeyAppErrorsaggregates multiple error categories in a single struct. This approach is convenient but can grow unwieldy as more error categories emerge. Consider extracting each category into its own package or sub-struct if significant expansions are anticipated.apps/engineering/content/rfcs/0011-unkey-resource-names.mdx (1)
30-30: Address grammar and compound-adjective issues.• Line 30: In “this is a Unkey resource identifier,” consider using “an Unkey resource identifier.”
• Lines 64 & 242: “Rate Limiting Service” used as a compound adjective might be hyphenated (e.g., “rate-limiting service”) for clarity and consistency.Also applies to: 64-64, 242-242
🧰 Tools
🪛 LanguageTool
[misspelling] ~30-~30: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ...nkey- Fixed prefix indicating this is a Unkey resource identifier *service` -...(EN_A_VS_AN)
go/pkg/codes/generate.go (2)
31-37: Verify error handling for output file creation.If file creation fails, the code correctly exits. However, consider providing more context in the error message (e.g., desired write location), especially when running automated scripts in CI/CD pipelines.
124-145: Maintain reflection logic for future expansions.The reflection-based approach in
processErrorDomaineases code generation but might become brittle if custom tags or additional fields are introduced incodes. Documenting these expectations or adding checks for unexpected fields will improve reliability.go/apps/api/routes/v2_ratelimit_limit/handler.go (1)
153-158: Duplicate error handling logicThis block duplicates the error handling from lines 87-92. Consider extracting this common logic into a helper function to avoid duplication and ensure consistent error handling.
You could create a helper function to handle namespace not found errors:
+ func handleNamespaceNotFoundError() error { + return fault.New("namespace was deleted", + fault.WithCode(codes.Data.RatelimitNamespace.NotFound.URN()), + fault.WithDesc("namespace not found", "This namespace does not exist."), + ) + } // Then in both locations: - if db.IsNotFound(err) { - return fault.New("namespace was deleted", - fault.WithCode(codes.Data.RatelimitNamespace.NotFound.URN()), - fault.WithDesc("namespace not found", "This namespace does not exist."), - ) - } + if db.IsNotFound(err) { + return handleNamespaceNotFoundError() + }apps/docs/api-reference/errors-v2/unkey/application/assertion_failed.mdx (1)
21-33: Clear explanation with minor grammatical issueThe explanation effectively distinguishes assertion failures from validation errors and clarifies the internal nature of the issue.
There appears to be a missing comma in line 23:
- This error occurs when Unkey's internal system detects an inconsistency or violation of its expected invariants during the processing of your request. Unlike validation errors which occur when your input is invalid, assertion failures happen when the system's internal state doesn't match what was expected. + This error occurs when Unkey's internal system detects an inconsistency or violation of its expected invariants during the processing of your request. Unlike validation errors, which occur when your input is invalid, assertion failures happen when the system's internal state doesn't match what was expected.🧰 Tools
🪛 LanguageTool
[uncategorized] ~23-~23: Possible missing comma found.
Context: ...sing of your request. Unlike validation errors which occur when your input is invalid,...(AI_HYDRA_LEO_MISSING_COMMA)
go/pkg/urn/resource.go (1)
23-39: Consider using constants for map keysThe validation map hard-codes service names as keys. Consider creating named constants for these map indices to improve code maintainability and ensure consistency with any future service additions.
validResourceTypes := map[Service]map[ResourceType]bool{ - ServiceAuth: { + ServiceAuth: { // Auth service resources ResourceTypeKey: true, ResourceTypeAPI: true, }, - ServiceRateLimit: { + ServiceRateLimit: { // Rate limit service resources ResourceTypeNamespace: true, }, // Continue with other services... }go/pkg/zen/middleware_errors.go (2)
151-165: Key disabled mapped to 403.
This approach is valid. Just ensure the user-facing message highlights the reason for the key’s disablement (e.g., billing issues, policy violations, etc.) if known.
166-180: Workspace disabled also mapped to 403.
Similar to the "key disabled" scenario, adding context about the cause of the workspace disablement can help users quickly resolve issues.apps/docs/api-reference/errors-v2/unkey/application/unexpected_error.mdx (2)
36-38: Prevent potential token exposure.
In production or logs, avoid displaying real bearer tokens even in examples. Document carefully that “unkey_YOUR_API_KEY” is a placeholder, or consider redaction to mitigate confusion.
80-80: Repetitive wording.
"Always include therequestIdwhen contacting support about this error. This error..."
Consider removing the duplicate phrase to improve readability.- Always include the `requestId` when contacting support about this error - This error may indicate a bug... + Always include the `requestId` when contacting support about this error. It may indicate a bug...🧰 Tools
🪛 LanguageTool
[grammar] ~80-~80: This phrase is duplicated. You should probably use “this error” only once.
Context: ...equestId` when contacting support about this error - This error may indicate a bug in Unkey's systems t...(PHRASE_REPETITION)
go/pkg/fault/code_test.go (1)
15-15: Consider a dedicated constant for the “empty code” scenario.
Currently, returning an empty string on nil or untagged errors might be ambiguous. A named constant (e.g.,codes.Nil) could improve readability.Also applies to: 18-18, 20-20
go/apps/api/routes/v2_ratelimit_set_override/handler.go (1)
49-49: Consider using a validation-related code instead ofUnexpectedError.
For invalid request bodies,codes.App.Validation.InvalidInputmight better represent the error context.go/pkg/codes/codes.go (3)
17-36: System Enumeration Appears Consistent
TheSystemtype and its constants are straightforward and logically grouped. You might consider documenting when each system is typically triggered to help future maintainers quickly pinpoint the error origin.
78-83: URN() Method Implementation
Constructing the URN viastrings.Joinis succinct. Consider trimming or sanitizingc.Specificif there's any risk of user-provided input containing separators, although this may not be necessary if all call sites are controlled.
102-115: ParseCode String Splitting & Validation
Use ofstrings.Splitis clear and the error message is sufficiently informative if the format is invalid. Consider trimming whitespace aroundsbefore splitting, to handle unexpected leading or trailing spaces.go/pkg/urn/urn.go (1)
86-138: Parse Function
The mechanism of splitting on “:” and re-splitting the last component with “/” is well-delineated. Error reporting and component validation are robust. One minor suggestion is to trimurnStrto remove leading/trailing whitespace before splitting.go/pkg/codes/unkey_data.go (1)
17-21: Naming Consistency fordataApi
All other struct names (e.g.,dataKey,dataRole) use the same pattern except fordataApiwhich could bedataAPIfor consistency with typical Go naming conventions (e.g.,API).-type dataApi struct { +type dataAPI struct {go/pkg/codes/constants_gen.go (1)
103-109: Validation Error Constants
The constants for validation errors (UnkeyAppErrorsValidationInvalidInputandUnkeyAppErrorsValidationAssertionFailed) are well-defined. As a consideration for future improvements, review if additional, more granular validation error codes might be beneficial as the API evolves.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (2)
go/go.sumis excluded by!**/*.sumpnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (100)
apps/docs/api-reference/errors-v2/overview.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/application/assertion_failed.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/application/invalid_input.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/application/protected_resource.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/application/service_unavailable.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/application/unexpected_error.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/authentication/key_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/authentication/malformed.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/authentication/missing.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/authorization/forbidden.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/authorization/insufficient_permissions.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/authorization/key_disabled.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/authorization/workspace_disabled.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/api_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/assertion_failed.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/audit_log_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/identity_already_exists.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/identity_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/invalid_input.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/key_auth_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/key_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/permission_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/ratelimit_namespace_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/ratelimit_override_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/role_not_found.mdx(1 hunks)apps/docs/api-reference/errors-v2/unkey/data/workspace_not_found.mdx(1 hunks)apps/docs/api-reference/errors/code/BAD_REQUEST.mdx(1 hunks)apps/docs/api-reference/errors/code/CONFLICT.mdx(1 hunks)apps/docs/api-reference/errors/code/DELETE_PROTECTED.mdx(1 hunks)apps/docs/api-reference/errors/code/DISABLED.mdx(1 hunks)apps/docs/api-reference/errors/code/EXPIRED.mdx(1 hunks)apps/docs/api-reference/errors/code/FORBIDDEN.mdx(1 hunks)apps/docs/api-reference/errors/code/INSUFFICIENT_PERMISSIONS.mdx(1 hunks)apps/docs/api-reference/errors/code/INTERNAL_SERVER_ERROR.mdx(1 hunks)apps/docs/api-reference/errors/code/METHOD_NOT_ALLOWED.mdx(1 hunks)apps/docs/api-reference/errors/code/NOT_FOUND.mdx(1 hunks)apps/docs/api-reference/errors/code/PRECONDITION_FAILED.mdx(1 hunks)apps/docs/api-reference/errors/code/TOO_MANY_REQUESTS.mdx(1 hunks)apps/docs/api-reference/errors/code/UNAUTHORIZED.mdx(1 hunks)apps/docs/api-reference/errors/code/USAGE_EXCEEDED.mdx(1 hunks)apps/docs/docs.json(1 hunks)apps/docs/mint.json(0 hunks)apps/docs/package.json(1 hunks)apps/engineering/content/rfcs/0011-unkey-resource-names.mdx(1 hunks)apps/workflows/wrangler.toml(1 hunks)apps/www/content/blog/zen.mdx(2 hunks)go/apps/api/integration/multi_node_ratelimiting/generate_tests/main.go(1 hunks)go/apps/api/openapi/generate.go(1 hunks)go/apps/api/routes/reference/handler.go(1 hunks)go/apps/api/routes/register.go(2 hunks)go/apps/api/routes/v2_apis_create_api/401_test.go(1 hunks)go/apps/api/routes/v2_apis_create_api/handler.go(5 hunks)go/apps/api/routes/v2_identities_create_identity/400_test.go(1 hunks)go/apps/api/routes/v2_identities_create_identity/401_test.go(1 hunks)go/apps/api/routes/v2_identities_create_identity/409_test.go(1 hunks)go/apps/api/routes/v2_identities_create_identity/handler.go(6 hunks)go/apps/api/routes/v2_ratelimit_delete_override/400_test.go(2 hunks)go/apps/api/routes/v2_ratelimit_delete_override/404_test.go(3 hunks)go/apps/api/routes/v2_ratelimit_delete_override/handler.go(7 hunks)go/apps/api/routes/v2_ratelimit_get_override/400_test.go(1 hunks)go/apps/api/routes/v2_ratelimit_get_override/401_test.go(1 hunks)go/apps/api/routes/v2_ratelimit_get_override/404_test.go(3 hunks)go/apps/api/routes/v2_ratelimit_get_override/handler.go(5 hunks)go/apps/api/routes/v2_ratelimit_limit/400_test.go(0 hunks)go/apps/api/routes/v2_ratelimit_limit/401_test.go(2 hunks)go/apps/api/routes/v2_ratelimit_limit/404_test.go(1 hunks)go/apps/api/routes/v2_ratelimit_limit/handler.go(4 hunks)go/apps/api/routes/v2_ratelimit_set_override/400_test.go(1 hunks)go/apps/api/routes/v2_ratelimit_set_override/401_test.go(1 hunks)go/apps/api/routes/v2_ratelimit_set_override/404_test.go(2 hunks)go/apps/api/routes/v2_ratelimit_set_override/handler.go(8 hunks)go/go.mod(1 hunks)go/internal/services/keys/verify.go(4 hunks)go/internal/services/keys/verify_root_key.go(0 hunks)go/pkg/assert/assert.go(14 hunks)go/pkg/codes/codes.go(1 hunks)go/pkg/codes/constants_gen.go(1 hunks)go/pkg/codes/doc.go(1 hunks)go/pkg/codes/generate.go(1 hunks)go/pkg/codes/generate_run.go(1 hunks)go/pkg/codes/nil.go(1 hunks)go/pkg/codes/unkey_application.go(1 hunks)go/pkg/codes/unkey_auth.go(1 hunks)go/pkg/codes/unkey_data.go(1 hunks)go/pkg/db/generate.go(1 hunks)go/pkg/db/handle_err_no_rows.go(1 hunks)go/pkg/fault/code.go(1 hunks)go/pkg/fault/code_test.go(1 hunks)go/pkg/fault/dst_test.go(8 hunks)go/pkg/fault/tag.go(0 hunks)go/pkg/fault/wrap.go(2 hunks)go/pkg/fault/wrap_test.go(5 hunks)go/pkg/fault/wrapped.go(3 hunks)go/pkg/fault/wrapped_test.go(2 hunks)go/pkg/urn/resource.go(1 hunks)go/pkg/urn/service.go(1 hunks)go/pkg/urn/urn.go(1 hunks)go/pkg/zen/auth.go(2 hunks)go/pkg/zen/auth_test.go(6 hunks)go/pkg/zen/middleware_errors.go(3 hunks)
💤 Files with no reviewable changes (4)
- go/apps/api/routes/v2_ratelimit_limit/400_test.go
- go/internal/services/keys/verify_root_key.go
- apps/docs/mint.json
- go/pkg/fault/tag.go
🧰 Additional context used
🧬 Code Graph Analysis (20)
go/pkg/zen/auth.go (1)
go/pkg/fault/wrap.go (1)
WithDesc(75-91)
go/apps/api/routes/v2_ratelimit_set_override/404_test.go (2)
go/pkg/assert/assert.go (1)
Equal(20-29)go/pkg/system_errors/errors.go (1)
Error(36-40)
go/apps/api/routes/v2_ratelimit_set_override/401_test.go (5)
go/apps/api/routes/v2_ratelimit_delete_override/handler.go (3)
New(35-194)Request(24-24)Response(25-25)go/apps/api/routes/v2_ratelimit_get_override/handler.go (3)
New(28-122)Request(18-18)Response(19-19)go/apps/api/routes/v2_ratelimit_limit/handler.go (3)
New(43-238)Request(27-27)Response(28-28)go/apps/api/routes/v2_ratelimit_set_override/handler.go (3)
New(36-180)Request(25-25)Response(26-26)go/pkg/testutil/http.go (1)
CallRoute(180-214)
go/pkg/assert/assert.go (1)
go/pkg/fault/wrapped.go (1)
New(52-66)
go/apps/api/routes/v2_identities_create_identity/401_test.go (2)
go/pkg/testutil/http.go (1)
CallRoute(180-214)go/apps/api/openapi/gen.go (1)
BadRequestErrorResponse(46-49)
go/apps/api/routes/register.go (3)
go/internal/services/ratelimit/service.go (1)
New(126-150)go/pkg/zen/server.go (1)
New(64-113)go/apps/api/routes/v2_liveness/handler.go (1)
New(13-27)
go/apps/api/routes/v2_ratelimit_get_override/handler.go (4)
go/pkg/db/handle_err_no_rows.go (1)
IsNotFound(8-10)go/pkg/fault/wrapped.go (1)
New(52-66)go/pkg/otel/logging/slog.go (1)
New(59-66)go/pkg/fault/wrap.go (1)
WithDesc(75-91)
go/apps/api/routes/v2_ratelimit_delete_override/400_test.go (2)
go/pkg/assert/assert.go (1)
Equal(20-29)go/pkg/system_errors/errors.go (1)
Error(36-40)
go/pkg/zen/middleware_errors.go (2)
go/apps/api/openapi/gen.go (9)
NotFoundErrorResponse(107-110)Meta(100-104)BaseError(52-67)BadRequestErrorResponse(46-49)BadRequestErrorDetails(25-43)UnauthorizedErrorResponse(192-195)ForbiddenErrorResponse(76-79)ConflictErrorResponse(70-73)PreconditionFailedErrorResponse(123-126)go/pkg/fault/wrapped.go (1)
UserFacingMessage(161-195)
go/pkg/fault/wrap_test.go (8)
go/apps/api/routes/v2_identities_create_identity/handler.go (1)
New(44-240)go/apps/api/routes/v2_ratelimit_delete_override/handler.go (1)
New(35-194)go/apps/api/routes/v2_ratelimit_get_override/handler.go (1)
New(28-122)go/apps/api/routes/v2_ratelimit_limit/handler.go (1)
New(43-238)go/apps/api/routes/v2_ratelimit_set_override/handler.go (1)
New(36-180)go/pkg/fault/wrapped.go (1)
New(52-66)go/pkg/clickhouse/client.go (1)
New(59-161)go/pkg/assert/assert.go (1)
Equal(20-29)
go/apps/api/routes/v2_apis_create_api/401_test.go (1)
go/pkg/assert/assert.go (1)
Equal(20-29)
go/apps/api/routes/v2_ratelimit_delete_override/handler.go (3)
go/pkg/db/handle_err_no_rows.go (1)
IsNotFound(8-10)go/pkg/fault/wrapped.go (1)
New(52-66)go/pkg/fault/wrap.go (2)
WithDesc(75-91)Wrap(20-37)
go/apps/api/routes/v2_ratelimit_get_override/400_test.go (2)
go/pkg/assert/assert.go (1)
Equal(20-29)go/pkg/system_errors/errors.go (1)
Error(36-40)
go/apps/api/routes/v2_ratelimit_set_override/handler.go (1)
go/pkg/fault/wrap.go (2)
WithDesc(75-91)Wrap(20-37)
go/apps/api/routes/v2_ratelimit_set_override/400_test.go (2)
go/pkg/assert/assert.go (1)
Equal(20-29)go/pkg/system_errors/errors.go (1)
Error(36-40)
go/internal/services/keys/verify.go (4)
go/pkg/db/handle_err_no_rows.go (1)
IsNotFound(8-10)go/internal/services/keys/interface.go (1)
VerifyResponse(14-17)go/pkg/fault/wrap.go (2)
Wrap(20-37)WithDesc(75-91)go/pkg/fault/wrapped.go (1)
New(52-66)
go/pkg/fault/dst_test.go (2)
go/pkg/assert/assert.go (1)
True(79-88)go/pkg/system_errors/errors.go (1)
Error(36-40)
go/apps/api/routes/v2_identities_create_identity/handler.go (2)
go/pkg/fault/wrap.go (2)
WithDesc(75-91)Wrap(20-37)go/pkg/fault/wrapped.go (1)
New(52-66)
go/apps/api/routes/v2_ratelimit_limit/handler.go (4)
go/pkg/db/handle_err_no_rows.go (1)
IsNotFound(8-10)go/internal/services/permissions/service.go (1)
New(29-37)go/internal/services/keys/service.go (1)
New(26-33)go/pkg/fault/wrap.go (1)
WithDesc(75-91)
go/pkg/zen/auth_test.go (1)
go/pkg/assert/assert.go (3)
True(79-88)Equal(20-29)False(99-108)
🪛 LanguageTool
apps/docs/api-reference/errors-v2/unkey/application/invalid_input.mdx
[style] ~60-~60: Consider using a different verb for a more formal wording.
Context: ...d (if available) for guidance on how to correct the issue 4. Modify your request to com...
(FIX_RESOLVE)
[style] ~81-~81: This phrase is redundant. Consider using “outside”.
Context: ... Range violations: Providing values outside of allowed ranges (too small, too large) -...
(OUTSIDE_OF)
apps/docs/api-reference/errors-v2/unkey/authorization/workspace_disabled.mdx
[uncategorized] ~48-~48: You might be missing the article “the” here.
Context: ...key.com/settings/billing) 2. Contact workspace administrator: If you're not the work...
(AI_EN_LECTOR_MISSING_DETERMINER_THE)
apps/docs/api-reference/errors-v2/unkey/application/unexpected_error.mdx
[grammar] ~80-~80: This phrase is duplicated. You should probably use “this error” only once.
Context: ...equestId` when contacting support about this error - This error may indicate a bug in Unkey's systems t...
(PHRASE_REPETITION)
apps/docs/api-reference/errors-v2/unkey/data/permission_not_found.mdx
[grammar] ~23-~23: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...ou're trying to perform an operation on a permission that doesn't exist in the Unkey system....
(A_UNCOUNTABLE_NOUN)
[grammar] ~27-~27: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...ect permission ID or name - Referencing a permission that has been deleted - Trying to assig...
(A_UNCOUNTABLE_NOUN)
[grammar] ~28-~28: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...hat has been deleted - Trying to assign a permission that doesn't exist in the current works...
(A_UNCOUNTABLE_NOUN)
apps/docs/api-reference/errors/code/CONFLICT.mdx
[grammar] ~12-~12: ‘a’ may be redundant when used with the uncountable noun ‘permission’.
Context: ...ace slug that already exists - Creating a permission with an identifier that's already in us...
(A_UNCOUNTABLE_NOUN)
apps/docs/api-reference/errors-v2/unkey/data/key_auth_not_found.mdx
[grammar] ~28-~28: The plural noun “Typos” cannot be used with the article “a”. Did you mean “a non-existent record typo” or “non-existent record Typos”?
Context: ...g to update authentication settings for a non-existent record - Typos in identifiers Here's an example of a ...
(A_NNS)
apps/docs/api-reference/errors-v2/unkey/authorization/forbidden.mdx
[style] ~45-~45: You have already used ‘trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ... permission issue. The operation you're trying to perform may be: 1. **Not supported by ...
(REP_TRY)
[style] ~65-~65: You have already used ‘Trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ...rrent plan - Resource state issues: Trying to modify resources that are in a state th...
(REP_TRY)
[style] ~67-~67: You have already used ‘trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ...ing security boundaries**: Deliberately trying to access protected resources - **Outdated...
(REP_TRY)
apps/docs/api-reference/errors-v2/unkey/application/assertion_failed.mdx
[uncategorized] ~23-~23: Possible missing comma found.
Context: ...sing of your request. Unlike validation errors which occur when your input is invalid,...
(AI_HYDRA_LEO_MISSING_COMMA)
apps/docs/api-reference/errors-v2/unkey/data/audit_log_not_found.mdx
[uncategorized] ~49-~49: Possible missing comma found.
Context: ... that audit logs might have a retention period after which they're automatically delet...
(AI_HYDRA_LEO_MISSING_COMMA)
apps/engineering/content/rfcs/0011-unkey-resource-names.mdx
[misspelling] ~30-~30: Use “an” instead of ‘a’ if the following word starts with a vowel sound, e.g. ‘an article’, ‘an hour’.
Context: ...nkey- Fixed prefix indicating this is a Unkey resource identifier *service` -...
(EN_A_VS_AN)
[uncategorized] ~64-~64: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...ation and authorization * ratelimit - Rate limiting service * identity - Identity managem...
(EN_COMPOUND_ADJECTIVE_INTERNAL)
[uncategorized] ~242-~242: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ...Resource already exists (conflict) ### Rate Limiting Service (ratelimit) - `err:ratelimit:...
(EN_COMPOUND_ADJECTIVE_INTERNAL)
apps/docs/api-reference/errors-v2/unkey/data/assertion_failed.mdx
[uncategorized] ~23-~23: Possible missing comma found.
Context: ...sing of your request. Unlike validation errors which occur when your input is invalid,...
(AI_HYDRA_LEO_MISSING_COMMA)
apps/docs/api-reference/errors/code/NOT_FOUND.mdx
[style] ~20-~20: You have already used ‘trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ... to check if the resource exists before trying to modify it: ```bash # Example: Che...
(REP_TRY)
apps/docs/api-reference/errors-v2/overview.mdx
[uncategorized] ~46-~46: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ... operations and resources - limits: Rate limiting or quota-related errors ## Error Respo...
(EN_COMPOUND_ADJECTIVE_INTERNAL)
[duplication] ~70-~70: Possible typo: you repeated a word.
Context: ...- title: Short summary of the error type - type: URL to detailed documentation about ...
(ENGLISH_WORD_REPEAT_RULE)
apps/docs/api-reference/errors-v2/unkey/data/invalid_input.mdx
[style] ~60-~60: Consider using a different verb for a more formal wording.
Context: ...d (if available) for guidance on how to correct the issue 4. Modify your request to com...
(FIX_RESOLVE)
[style] ~81-~81: This phrase is redundant. Consider using “outside”.
Context: ... Range violations: Providing values outside of allowed ranges (too small, too large) -...
(OUTSIDE_OF)
apps/docs/api-reference/errors/code/TOO_MANY_REQUESTS.mdx
[misspelling] ~7-~7: Did you mean “two” or “tool”?
Context: ...ErrTooManyRequests --- ## Overview The TOO_MANY_REQUESTS error (HTTP 429) occurs w...
(TOO_TOOL)
[uncategorized] ~60-~60: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ... queue system. ## Related Resources - Rate Limiting Guide - [H...
(EN_COMPOUND_ADJECTIVE_INTERNAL)
apps/docs/api-reference/errors-v2/unkey/application/protected_resource.mdx
[uncategorized] ~23-~23: Possible missing article found.
Context: ... Unkey system. Protected resources have special status that prevents them from being ch...
(AI_HYDRA_LEO_MISSING_A)
[style] ~45-~45: You have already used ‘trying to’ in nearby sentences. Consider using one of the replacements to let your writing stand out.
Context: ...to work with or around them rather than trying to change them: 1. **Work with the protec...
(REP_TRY)
🪛 Gitleaks (8.21.2)
apps/docs/api-reference/errors/code/FORBIDDEN.mdx
23-24:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/identity_not_found.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors/code/EXPIRED.mdx
23-24:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/workspace_not_found.mdx
21-22:
(curl-auth-header)
36-37:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/application/unexpected_error.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/permission_not_found.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors/code/DISABLED.mdx
23-24:
(curl-auth-header)
apps/docs/api-reference/errors/code/CONFLICT.mdx
23-24:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/role_not_found.mdx
21-22:
(curl-auth-header)
36-37:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/key_auth_not_found.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/identity_already_exists.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/key_not_found.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/audit_log_not_found.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/authentication/malformed.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/authentication/key_not_found.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors/code/PRECONDITION_FAILED.mdx
21-22:
(curl-auth-header)
apps/docs/api-reference/errors/code/DELETE_PROTECTED.mdx
23-24:
(curl-auth-header)
apps/docs/api-reference/errors/code/NOT_FOUND.mdx
21-22:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/data/invalid_input.mdx
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors/code/TOO_MANY_REQUESTS.mdx
21-22:
(curl-auth-header)
⏰ Context from checks skipped due to timeout of 90000ms (11)
- GitHub Check: Test Go API Local / Test (Shard 2/8)
- GitHub Check: Test Packages / Test ./packages/cache
- GitHub Check: Test Go API Local / Test (Shard 1/8)
- GitHub Check: Test Packages / Test ./internal/clickhouse
- GitHub Check: Test Packages / Test ./packages/api
- GitHub Check: Test Packages / Test ./internal/id
- GitHub Check: Test Packages / Test ./internal/encryption
- GitHub Check: Test Packages / Test ./internal/billing
- GitHub Check: Test Packages / Test ./internal/hash
- GitHub Check: Build / Build
- GitHub Check: Test API / API Test Local
🔇 Additional comments (296)
apps/docs/package.json (1)
11-11: Dependency Version Upgrade for MintlifyThe
mintlifyversion indevDependencieshas been updated from the old version to^4.0.482. Please verify that this version is fully compatible with our existing documentation build and development workflows. Additionally, consider running the documentation preview to confirm that no unintended visual or functional regressions have been introduced.apps/workflows/wrangler.toml (1)
7-8: Confirm Compatibility Flag InclusionThe new configuration parameter
compatibility_flags = ["nodejs_compat"]has been correctly added. This entry appears to facilitate compatibility adjustments (likely impacting error handling and API behavior as per the PR objectives). Ensure that downstream tooling or runtime environment processes this flag to activate Node.js‐compatible behavior, and verify that the accompanying documentation or schema (node_modules/wrangler/config-schema.json) is updated accordingly if needed.go/apps/api/routes/v2_ratelimit_delete_override/400_test.go (3)
102-102: Properly updated error type URL to match new error schemaThe change from
"https://unkey.com/docs/errors/bad_request"to"https://unkey.com/docs/api-reference/errors-v2/unkey/data/invalid_input"aligns with the new structured error system using URNs. This provides a more specific error categorization for the "neither namespace ID nor name provided" case.
141-141: Correct status code change for authentication issuesChanging from
http.StatusBadRequest(400) tohttp.StatusUnauthorized(401) for malformed authorization headers is semantically correct. Authentication issues should return 401 rather than 400.
123-125:Details
❓ Verification inconclusive
Consider consistent status codes for authentication issues
While the "malformed authorization header" test now correctly expects
http.StatusUnauthorized(401), this "missing authorization header" test still expectshttp.StatusBadRequest(400). For consistency in error handling, consider updating this to also expect 401, as both cases are authentication issues.
🏁 Script executed:
#!/bin/bash # Check if missing authorization headers return 401 in other parts of the codebase rg -A 3 "missing.+authorization.+header" --glob "*.go" | grep -i "statusunauthorized"Length of output: 83
Action: Ensure uniform authentication error status codes
The test in
go/apps/api/routes/v2_ratelimit_delete_override/400_test.gofor a missing authorization header currently expectshttp.StatusBadRequest(400), whereas the test for a malformed header correctly expectshttp.StatusUnauthorized(401). For consistency in error handling, please verify that missing authorization headers across the codebase should indeed yield a 401. If so, update the missing header test to expect 401 rather than 400.
- Location: File
go/apps/api/routes/v2_ratelimit_delete_override/400_test.go, lines 123–125.- Action: Change the expected status code from 400 to 401 in the missing header test case.
Please manually verify this behavior across the authorization-related tests to ensure consistency.
go/apps/api/routes/v2_ratelimit_limit/404_test.go (1)
92-92: Updated error type URL to follow the new structured error format.The error type URL has been updated from a generic path to a more specific one that follows the new error categorization structure. This is part of the overall "errors v2" feature enhancement mentioned in the PR objectives.
go/pkg/db/generate.go (1)
3-3:Details
❓ Verification inconclusive
Using error codes for generate directives is unusual.
Prefixing the go:generate directives with
//codes.App.Internal.ServiceUnavailable.URN()is an unusual pattern. This appears to be mixing error handling with code generation directives, which could cause confusion about the purpose of these lines.Also applies to: 6-6
🏁 Script executed:
#!/bin/bash # Search for similar patterns in other generate directives echo "Searching for similar code generation patterns across the codebase..." rg --type go "//codes.*URN\\(\\).*generate" -A 1Length of output: 378
Clarify the Error Code Prefix in Generate Directives
In file go/pkg/db/generate.go (lines 3 and 6), the generate directive is written as:
//codes.App.Internal.ServiceUnavailable.URN() sqlc generateThis usage—prefixing the generate directive with an error code pattern—is non-standard and may lead to confusion by mixing error handling semantics with code generation commands. Please clarify if this pattern is intentional and, if so, consider updating the documentation to explain its purpose. Otherwise, switching to a conventional
//go:generatedirective might prevent potential misunderstandings.go/apps/api/routes/v2_ratelimit_set_override/401_test.go (2)
41-41: Improved error message with response body information.Adding the response body to the error message helps with debugging by providing more context when the test fails.
45-62: Added test case for malformed authorization header.This new test case improves test coverage by verifying that the API correctly handles malformed authorization headers (not just invalid tokens). This aligns with the PR objective of enhancing error handling.
go/apps/api/routes/v2_ratelimit_set_override/400_test.go (1)
173-173: Updated error type URL to use the new structured error format.Similar to other files in this PR, the error type URL has been updated from a generic path to a more specific one (
https://unkey.com/docs/api-reference/errors-v2/unkey/data/invalid_input). This is part of the larger effort to improve error handling with a more structured approach.go/internal/services/keys/verify.go (7)
8-8: Good addition of codes importAdding the codes package import enables the structured error handling approach being implemented in this PR.
29-35: Improved error handling for key not found caseThe refactoring from a direct SQL error check to using the abstracted
db.IsNotFound(err)helper is a good improvement. It encapsulates the implementation details of error checking and makes the code more maintainable.The addition of the specific error code through
WithCode(codes.Auth.Authentication.KeyNotFound.URN())provides more structured error information, enhancing error clarity and consistency throughout the system.
58-58: Enhanced error specificity for deleted keyAdding a specific error code for deleted keys improves error reporting granularity and allows consumers to more precisely handle this case.
66-67: Better error handling for disabled keyUsing a specific URN-based error code with a clearer description improves error handling and makes it easier for API consumers to understand and handle this specific case.
80-86: Consistent error handling for workspace not foundThis follows the same pattern as the key not found error handling, providing consistency in the codebase. Using the abstracted
db.IsNotFound(err)helper and adding a specific error code improves error clarity.
92-92: Appropriate service unavailable error codeAdding the specific error code for service unavailable provides better context when workspace loading fails, improving error reporting.
100-100: Consistent error code for disabled workspaceAdding the specific error code maintains the pattern of using URN-based error codes throughout the service, ensuring consistency in error reporting.
go/pkg/codes/generate_run.go (1)
1-3: Good setup for code generationThe file correctly sets up code generation for the
codespackage using the Go generate directive. This approach will help maintain consistency in the error code system by automating the generation of code.go/pkg/codes/nil.go (1)
1-10: Well-documented fallback error codeThe implementation of a
Nilerror code as a fallback is a good practice. The documentation clearly explains its purpose for maintaining consistency in error handling when specific error codes aren't available.go/go.mod (1)
40-40:Details
✅ Verification successful
Review dependency version and usage
A new dependency has been added:
github.com/MarceloPetrucio/go-scalar-api-reference. Since this appears to be related to API error reference documentation, we should verify this dependency's stability and usage in the project.
🏁 Script executed:
#!/bin/bash # Check if any code imports this package echo "Checking for direct imports:" rg -l "github.com/MarceloPetrucio/go-scalar-api-reference" --type go # Check GitHub for the repository details echo "Checking GitHub repo info:" gh api repos/MarceloPetrucio/go-scalar-api-reference --jq '.description, .created_at, .updated_at, .stargazers_count, .open_issues_count, .forks'Length of output: 477
Dependency Verified:
github.com/MarceloPetrucio/go-scalar-api-reference
- Verified that there are no direct imports within our code, indicating it’s included as an indirect dependency.
- The GitHub repository details confirm it’s actively maintained (latest update on 2025-04-13 with 78 stars, 4 open issues, and 8 forks) and aligns with its role in generating API reference documentation.
- Please ensure that this indirect dependency is intentionally required as part of our API reference tooling. If it isn’t needed, consider cleaning it up from the module file.
go/apps/api/routes/v2_identities_create_identity/409_test.go (1)
45-45: LGTM! Error URL updated to use the new v2 error reference formatThe error URL has been properly updated to use the new v2 error reference format, providing a more specific error type for identity already exists conflicts.
This change aligns with the overall project goal of improving error handling with more specific error types and documentation.
go/apps/api/routes/v2_ratelimit_set_override/404_test.go (1)
47-47: LGTM! Error URLs updated to use the new v2 error reference formatBoth error URL assertions have been properly updated to use the new v2 error reference format, providing a more specific error type for rate limit namespace not found errors.
These changes are consistent with the errors v2 feature implementation across the codebase.
Also applies to: 63-63
go/apps/api/routes/v2_identities_create_identity/401_test.go (1)
39-49:Details
❓ Verification inconclusive
Inconsistency between response type and status code
The test is using
openapi.BadRequestErrorResponseas the expected response type, but asserting a status code ofhttp.StatusUnauthorized(401). This seems inconsistent since a Bad Request typically corresponds to a 400 status code, not 401.Please verify if this is intentional. If the API is designed to return the same error response structure for both 400 and 401 errors, this might be correct. Otherwise, the expected response type should be updated to match the 401 status code, likely using
openapi.UnauthorizedErrorResponseinstead.
🏁 Script executed:
#!/bin/bash # Check how the route handles different authorization errors # Look for the handler implementation to see the error response types rg -A 5 "func \(h \*Handler\) Handle" go/apps/api/routes/v2_identities_create_identity/Length of output: 89
Action Required: Verify Error Response Consistency in Authorization Handling
The test in
go/apps/api/routes/v2_identities_create_identity/401_test.gousesopenapi.BadRequestErrorResponsefor a request that receives a 401 (Unauthorized) status. This appears inconsistent because a 400 (Bad Request) would normally be associated with that error response type. It’s unclear if this is an intentional design decision—perhaps the API uses a unified error response schema for both client errors—or if the expected type should indeed be changed to something likeopenapi.UnauthorizedErrorResponse.Please verify manually:
- Whether the handler implementation (not found via initial automated search) intentionally maps 401 errors to the bad-request response type.
- If other routes consistently use distinct error responses for 400 and 401 statuses.
- If changing the expected response type in the test to
openapi.UnauthorizedErrorResponseis necessary to align with the API’s intended behavior.go/pkg/fault/wrap.go (1)
84-85: Update code documentation to reflect the tag to code changeThe
WithDescfunction has been updated to usecodeinstead oftagin the wrapped struct, consistent with the changes to theWrapfunction.go/apps/api/routes/v2_ratelimit_get_override/401_test.go (1)
42-57:Details
❓ Verification inconclusive
Inconsistent response type for malformed authorization header test
This test expects
handler.Responsefor a malformed authorization header, while the similar test inv2_identities_create_identity/401_test.goexpectsopenapi.BadRequestErrorResponse.Please verify if this difference is intentional. If both endpoints should handle malformed authorization headers in the same way, the expected response types should be consistent.
🏁 Script executed:
#!/bin/bash # Compare how different routes handle malformed authorization headers # Search for similar tests in other route handlers rg -A 3 "malformed authorization header" --glob "**/*_test.go" # Check how this route handler processes authorization rg -A 5 "Authorization" go/apps/api/routes/v2_ratelimit_get_override/Length of output: 6307
🏁 Script executed:
#!/bin/bash # Display snippet from the identities create identity test for malformed authorization header. rg -A 10 "t.Run(\"malformed authorization header" go/apps/api/routes/v2_identities_create_identity/401_test.goLength of output: 327
Inconsistent Response Types for Malformed Authorization Header Test
The ratelimit GET override test (in
go/apps/api/routes/v2_ratelimit_get_override/401_test.go) validates a response of typehandler.Responsefor a malformed authorization header, whereas the identities creation test (ingo/apps/api/routes/v2_identities_create_identity/401_test.go) expects anopenapi.BadRequestErrorResponse. Please verify manually if this divergence in expected response types is intentional. If both endpoints need to handle malformed authorization headers the same way, update the expected response type in one of the tests for consistency.go/pkg/fault/wrapped_test.go (2)
11-11: Good addition of the new codes package import.This import facilitates the transition from tag-based error handling to the new structured URN-based system, which will provide better type safety and consistency in error reporting.
173-173: Successfully updated to use the new URN-based error code.The change from
WithTag("ERROR_TAG")toWithCode(codes.Auth.Authentication.KeyNotFound.URN())properly implements the new error handling approach. This structured approach will make error handling more consistent and provide better context for debugging.go/pkg/zen/auth.go (3)
6-6: Appropriate addition of codes package import.This import is necessary for implementing the new URN-based error code system.
27-27: Good implementation of specific error codes.Using
codes.Auth.Authentication.Missing.URN()provides more specific context about the error compared to the previous tag-based approach. This will help with troubleshooting and error handling.
32-33: Properly implemented error with both code and descriptive message.The combination of
WithCodeandWithDescprovides both machine-readable error categorization and human-readable guidance, which is an excellent practice.apps/docs/api-reference/errors/code/METHOD_NOT_ALLOWED.mdx (1)
1-40: Well-structured error documentation.This documentation is comprehensive and follows good practices by including:
- Clear overview of the error
- Common causes with specific examples
- Step-by-step resolution guidance
- Concrete examples of correct HTTP methods for different operations
- Links to related resources
This will significantly improve the developer experience when encountering this error.
go/pkg/codes/doc.go (1)
1-16: Excellent package documentation.The documentation clearly explains:
- The purpose of the new codes package
- The structured URN-like format for error codes
- The hierarchical organization approach
- How this promotes consistency across services
This sets a solid foundation for the new error handling system and will help developers understand how to use it correctly.
apps/docs/api-reference/errors-v2/unkey/application/invalid_input.mdx (1)
1-88: Documentation looks good and follows a clear structure.The documentation provides comprehensive information about the
invalid_inputerror, including:
- A clear explanation of what the error means
- A well-formatted JSON example
- Common validation issues
- Example requests that trigger the error
- Step-by-step instructions for fixing the issue
- Common mistakes to avoid
- Related errors for further context
This will be valuable for API users when troubleshooting validation errors.
🧰 Tools
🪛 LanguageTool
[style] ~60-~60: Consider using a different verb for a more formal wording.
Context: ...d (if available) for guidance on how to correct the issue 4. Modify your request to com...(FIX_RESOLVE)
[style] ~81-~81: This phrase is redundant. Consider using “outside”.
Context: ... Range violations: Providing values outside of allowed ranges (too small, too large) -...(OUTSIDE_OF)
go/apps/api/routes/v2_ratelimit_delete_override/404_test.go (1)
61-61: Error URLs updated to match new URN-based error system.The test has been properly updated to use the new, more specific error URLs that reflect the URN-based error system. This should make the error messages more precise and helpful when debugging.
Also applies to: 76-76, 91-91
go/pkg/assert/assert.go (2)
7-7: Added import for the codes package.The codes package is now imported to support the URN-based error system.
26-26: Code updated to use the new URN-based error system.The assert package has been updated to use
fault.WithCode(codes.App.Validation.AssertionFailed.URN())instead of tags. This aligns with the broader migration to a structured URN-based error system.Also applies to: 46-46, 65-65, 85-85, 105-105, 125-125, 145-145, 165-165, 191-191, 215-215, 240-240, 264-264, 285-285
go/apps/api/routes/v2_ratelimit_get_override/400_test.go (1)
104-104: Error URL updated to use the new error documentation structure.The test has been properly updated to use the more specific error URL for invalid input validation. This aligns with the broader migration to the URN-based error system.
apps/www/content/blog/zen.mdx (2)
157-164: Good migration to structured error codes!The transition from using
fault.WithTag(fault.INSUFFICIENT_PERMISSIONS)tofault.WithCode(codes.Auth.Authorization.InsufficientPermissions.URN())reflects a move to a more structured error code system, which is a positive improvement. This hierarchical organization of error codes will likely make error handling more consistent and maintainable.
368-373: Consistent application of new error code pattern.The change to use
fault.WithCode(codes.Auth.Authorization.InsufficientPermissions.URN())is consistent with the previous instance, ensuring uniform error handling throughout the codebase.go/pkg/fault/code.go (1)
37-51: Well-structured WithCode implementation.The
WithCodefunction follows the same pattern as other wrapper functions, handling the nil error case appropriately and creating a wrapped error with the specified code. This provides a consistent interface for the error handling system.go/pkg/fault/wrapped.go (3)
3-9: Appropriate import of the codes package.Good job adding the import for the
codespackage which is needed for the newcodes.URNtype. The import is organized correctly with standard library imports first, followed by third-party imports.
27-28: Successful migration from tag to code field.The change from
tag Tagtocode codes.URNin thewrappedstruct is a key part of the migration to the new error code system. This change allows for a more structured and hierarchical representation of error types.
56-57: Updated initialization in New function.The
Newfunction has been properly updated to initialize thecodefield with an empty string instead of the previoustagfield. This is consistent with the changes to thewrappedstruct.apps/docs/api-reference/errors-v2/unkey/data/identity_not_found.mdx (2)
1-84: Well-structured error documentation.This documentation file provides comprehensive information about the
identity_not_founderror, including:
- A clear JSON example of the error response
- Explanation of what triggers the error
- Steps to fix the error with practical examples
- Common mistakes to avoid
- Related errors for further exploration
The structure follows best practices for API documentation and will be helpful for developers encountering this error.
🧰 Tools
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
34-41: Secure example with placeholder API key.The curl example correctly uses a placeholder for the API key (
unkey_YOUR_API_KEY) rather than including a real API key, which is a good security practice in documentation.🧰 Tools
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
go/pkg/db/handle_err_no_rows.go (1)
8-10: Good simplification of error handlingThe change from the previous comprehensive
HandleErrfunction to this focusedIsNotFoundfunction aligns well with the move toward a more structured error handling system using URN-based error codes.This simpler function has a clear, single responsibility and follows good separation of concerns principles. The error checking itself remains correct and will be more easily maintainable.
go/apps/api/routes/v2_ratelimit_limit/401_test.go (1)
45-66: Well-structured test for malformed authorization headerThe added test case properly verifies how the system handles malformed authorization headers, checking both the status code and the specific error details returned.
This test case enhances the coverage of authorization handling and aligns with the improved error system implemented in this PR.
go/apps/api/routes/register.go (2)
4-4: New import for reference package added correctly.The import for the
referencepackage is properly added to support the new route registration below.
109-114:Details
❓ Verification inconclusive
New route registered with different middleware configuration.
This new route for the
referencepackage uses a subset of the default middlewares (tracing, metrics, logging, error handling) but omits the validation middleware that other routes use. Is this intentional?The pattern differs from other route registrations that use
defaultMiddlewares. Consider whether validation is required for this route or document why it's excluded.
🏁 Script executed:
#!/bin/bash # Check if the reference package's New() function requires validation grep -r "func New" --include="*.go" go/apps/api/routes/reference/Length of output: 130
Confirm Exclusion of Validation Middleware for the
referenceRoute
Ingo/apps/api/routes/register.go(lines 109–114), the newreferenceroute is registered using a middleware list that omits the usual validation middleware found indefaultMiddlewares. Our investigation ofgo/apps/api/routes/reference/handler.go(which definesfunc New() zen.Route) shows no built‐in requirement for validation. If this omission is intentional—for example, because thereferenceroute does not process inputs needing validation—please add an inline comment or documentation clarifying the rationale. Otherwise, consider aligning this route’s middleware configuration with the other routes by including the validation middleware.apps/docs/api-reference/errors/code/BAD_REQUEST.mdx (4)
6-7: Improved section title and introduction.The change from "Problem" to "Overview" with a clear description of BAD_REQUEST errors improves the documentation structure and provides better context for users.
9-15: Comprehensive list of common causes.The enumerated list of common causes for BAD_REQUEST errors is very helpful and covers the most frequent issues users might encounter. This will assist developers in troubleshooting their API calls more effectively.
17-35: Detailed resolution steps with code example.The step-by-step resolution guide with a practical code example provides excellent guidance for developers. The progression from checking error messages to testing with minimal data follows a logical debugging workflow.
36-38: Added related resources section.The addition of links to related documentation enhances the usefulness of this page by connecting users to additional relevant information.
apps/docs/api-reference/errors-v2/unkey/authentication/malformed.mdx (1)
1-87: Well-structured error documentation that improves developer experience.This documentation for
err:unkey:authentication:malformedprovides clear, comprehensive guidance on a common authentication issue. The structure follows best practices with:
- Example error response in JSON format
- Clear explanation of what triggers the error
- Common causes in an easy-to-scan list
- Practical examples of both incorrect and correct implementations
- Common mistakes section that addresses edge cases
The examples using curl demonstrate both the problematic request and correct implementation, which is valuable for troubleshooting.
🧰 Tools
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors-v2/unkey/authentication/key_not_found.mdx (1)
1-73: Comprehensive error documentation with clear resolution steps.This documentation for
err:unkey:authentication:key_not_foundis well-structured and provides developers with all the information needed to understand and resolve the error. The content follows a logical flow from error description to resolution steps, and includes practical examples.🧰 Tools
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
apps/docs/api-reference/errors/code/UNAUTHORIZED.mdx (4)
6-7: Improved error overview with clearer explanation.The renamed section and expanded description provide better context about what causes an UNAUTHORIZED error, making it easier for developers to understand the nature of the issue.
9-15: Well-organized common causes with specific examples.The bullet points clearly enumerate the various scenarios that can lead to an UNAUTHORIZED error, helping developers quickly identify potential issues in their implementation.
17-31: Detailed resolution steps with helpful code example.The step-by-step resolution guide provides clear, actionable advice for fixing authentication issues. The inclusion of the code example for the correct header format is particularly helpful.
32-35: Useful related resources section.The addition of links to related documentation enhances the developer experience by providing easy access to more detailed information on authentication, API keys, and permissions.
apps/docs/api-reference/errors-v2/unkey/data/invalid_input.mdx (1)
1-89: Well-structured validation error documentation with practical examples.This documentation for
err:unkey:data:invalid_inputprovides clear guidance on handling validation errors. The structure follows best practices with a clear example, explanation, resolution steps, and related errors.🧰 Tools
🪛 LanguageTool
[style] ~60-~60: Consider using a different verb for a more formal wording.
Context: ...d (if available) for guidance on how to correct the issue 4. Modify your request to com...(FIX_RESOLVE)
[style] ~81-~81: This phrase is redundant. Consider using “outside”.
Context: ... Range violations: Providing values outside of allowed ranges (too small, too large) -...(OUTSIDE_OF)
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
55-57:
(curl-auth-header)
go/apps/api/routes/v2_apis_create_api/401_test.go (2)
37-37: Improved test assertion message with helpful context.The enhanced error message now includes the request payload and raw response body, which will make debugging test failures much easier. This is a good practice for test assertions.
12-40:Details
❓ Verification inconclusive
Test coverage seems to be reduced.
According to the AI summary, a test case for the "wrong workspace" scenario has been removed. Consider whether this scenario should still be tested to maintain comprehensive test coverage.
🏁 Script executed:
#!/bin/bash # Check the git history to see what test case was removed git log -p -- go/apps/api/routes/v2_apis_create_api/401_test.go | grep -A 20 "wrong workspace"Length of output: 0
Below is a new script to search the entire repository for any references to “wrong workspace” to help verify if that scenario is tested elsewhere:
#!/bin/bash # Search for any occurrence of "wrong workspace" in the repository (case-insensitive) rg -i "wrong workspace" .
If no output is produced, it would indicate that the “wrong workspace” scenario isn’t referenced anywhere in the codebase. Please run this script to confirm whether the test case was fully removed or if it exists in another form.
Review Action:
- It appears that no reference to a "wrong workspace" scenario exists, which aligns with the removal noted in the original diff.
- Please verify if this test case was intentionally removed:
- If the use case is still relevant, consider reintroducing a dedicated test.
- Otherwise, confirm that its removal is supported by equivalent test coverage elsewhere.
go/apps/api/routes/v2_apis_create_api/handler.go (7)
16-16: Good addition of the codes packageThe import of the codes package aligns with the PR's goal of improving error handling with structured error codes rather than generic tags.
71-71: Well-structured error code for insufficient permissionsThe change from a tag-based error to a URN-based error code using
codes.Auth.Authorization.InsufficientPermissions.URN()provides more specific error categorization, making errors more consistent and easier to document.
79-80: Consistent use of service unavailable error codeGood replacement of the database error tag with a more specific service unavailable code, which will help with standardizing error responses across database-related failures.
102-104: Consistent error code pattern for key auth creationThe error handling is properly updated to use URN-based codes, maintaining a clear pattern throughout the codebase for database-related errors.
118-120: Appropriate error code for API creation failureThe error handling maintains consistency with the new error coding system, providing clear context about the nature of the failure.
148-150: Consistent error handling for audit log insertionThe error code utilizes the same pattern as other database operations, maintaining uniformity across the error handling approach.
156-158: Proper error code for transaction commit failuresThe error handling for commit failures follows the same pattern as other database operations, ensuring a consistent approach to database errors.
go/pkg/fault/wrap_test.go (5)
8-8: Good addition of codes package importThe import of the codes package is necessary for the transition from tag-based to code-based error handling.
32-32: Appropriate rename of test fieldThe change from
expectedTagtoexpectedCodecorrectly reflects the shift in error handling approach from tags to URN-based codes.
41-42: Well-updated test case for code-based error handlingThe test case has been properly updated to use the new
codes.URNtype andWithCodewrapper instead of the previous tag-based approach. The expected values are correctly updated to reflect this change.Also applies to: 48-51
70-70: Correct assertion updateThe assertion is properly updated to check for
wrapped.codeinstead ofwrapped.tag, ensuring the tests validate the new code-based error handling mechanism.
82-82: Consistent update to multi-wrapper testThe test case for multiple wrappers is properly updated to use the new code-based approach, ensuring comprehensive test coverage of the refactored error handling system.
go/apps/api/routes/v2_ratelimit_get_override/404_test.go (3)
58-58: More specific error URL for override not foundThe change from a generic "not_found" URL to a specific "ratelimit_override_not_found" URL improves error documentation by providing more context-specific guidance to developers.
73-73: More specific error URL for namespace not foundThe update to a more specific URL for namespace not found errors provides better guidance to developers on how to resolve this particular error scenario.
87-87: Consistent error URL update for namespace name not foundThe error URL is consistently updated to the same namespace not found error as the previous test case, ensuring uniform error reporting for similar error conditions.
apps/docs/api-reference/errors/code/FORBIDDEN.mdx (4)
6-7: Improved error overview sectionThe renaming from "Problem" to "Overview" and the enhanced description provide clearer context about when FORBIDDEN errors occur, specifically highlighting that they happen post-authentication when permissions are insufficient.
9-16: Comprehensive list of common causesThe new "Common Causes" section provides developers with specific scenarios that might trigger this error, which is valuable for troubleshooting and prevention.
17-31: Detailed resolution steps with exampleThe expanded resolution steps provide clear, actionable guidance with a practical example command, greatly improving the developer experience when encountering this error.
🧰 Tools
🪛 Gitleaks (8.21.2)
23-24:
(curl-auth-header)
33-36: Helpful related resources sectionThe addition of related documentation links provides developers with pathways to learn more about permissions, API keys, and workspace controls, enhancing the overall documentation experience.
apps/docs/api-reference/errors/code/NOT_FOUND.mdx (2)
6-8: Overview Section Clarity and Context
The "Overview" section clearly explains the error, its HTTP status, and the potential reasons behind its occurrence. This addition provides immediate context for users encountering this error.
27-37: Final Steps and Related Resources
The subsequent steps and the "Related Resources" section are well-documented and provide users with useful pointers for further investigation.apps/docs/api-reference/errors/code/CONFLICT.mdx (5)
6-8: Overview Section Clarity
The "Overview" section succinctly describes the conditions under which a CONFLICT error occurs, providing clear context on resource identifier issues.
17-26: Resolution Steps - Initial Guidance
The initial steps, including listing existing resources to check for conflicts, are clear and supported by a useful cURL example. Ensure that the provided authorization pattern aligns with real-world usage.🧰 Tools
🪛 Gitleaks (8.21.2)
23-24:
(curl-auth-header)
27-30: Resolution Steps - Update and ID Generation
The instructions for using the update endpoint and leveraging Unkey's automatic ID generation are effective alternatives.
31-37: Resolution Steps - Uniqueness Check
The recommendation to check for the existence of a resource before creation is practical, and the associated example illustrates this well.
38-42: Related Resources Section
The related resource links are appropriately selected, guiding users to additional documentation that can assist them in resolving conflicts.apps/docs/api-reference/errors/code/DELETE_PROTECTED.mdx (6)
6-8: Overview Section Clarity
The "Overview" section accurately explains the DELETE_PROTECTED error and its purpose in safeguarding important resources from accidental deletion.
9-15: Common Causes Section
The common causes are clearly stated, covering various scenarios where deletion of protected resources is attempted.
16-23: Resolution Step 1 - Check Protection Status
The instructions to verify the resource’s protection status, including the provided cURL example, are clear and useful for troubleshooting.
29-38: Resolution Step 3 - Update via API
The API-based method is well-documented with a clear example. Ensure that header formats and endpoints remain consistent with other examples across the documentation.
39-43: Resolution Steps - Administrator Contact and Alternatives
Steps 4 and 5 are clearly outlined to handle situations where changes cannot be made directly. These provide a good fallback strategy for users.
44-48: Related Resources Section
The links to further documentation, such as API management and workspace security, add significant value for users seeking additional guidance.apps/docs/api-reference/errors-v2/unkey/authentication/missing.mdx (10)
1-4: Front Matter Setup
The front matter is well-organized with a clear title and description, setting the stage for the detailed error explanation.
7-19: JSON Example Clarity
The JSON example clearly illustrates the error response structure. Verify that the example values (like the requestId) are sufficiently generic for documentation purposes.
21-24: What Happened Section
The explanation succinctly states why the error occurs, emphasizing the missing authentication credentials.
25-32: Example Request Triggering Error
The example request effectively demonstrates a scenario that triggers the error by omitting the API key.
33-38: Authentication Requirement Details
This section lists the critical reasons for requiring authentication. The bullet points are clear and informative.
39-45: How To Fix Section
The steps to resolve the error are precise and actionable, guiding users on how to properly include their API key in requests.
46-52: Corrected Request Example
The revised cURL command demonstrates the correct usage with the proper Authorization header. This example effectively clarifies the fix.
54-70: Successful Response Example
The JSON example for a successful response is detailed and provides a clear contrast with the error response, reinforcing correct behavior.
72-78: Common Mistakes Section
The section on common mistakes is comprehensive. It successfully highlights potential pitfalls such as missing prefixes or header issues.
79-82: Related Errors Links
The links provided under "Related Errors" facilitate easy navigation to documentation on adjacent issues, adding substantial value to the guide.apps/docs/api-reference/errors-v2/unkey/application/protected_resource.mdx (6)
1-4: Front Matter Setup
The front matter is clearly defined with an appropriate title and description. This setup helps users identify the error context immediately.
7-19: JSON Example Clarity
The JSON example accurately depicts the error response structure, making it easier for developers to understand the expected output when this error occurs.
25-30: Common Scenarios Section
The list of common scenarios is comprehensive and clearly enumerates the conditions that lead to the protected resource error.
52-61: Alternative Example
The alternative example using a POST request to create a new API is helpful. It demonstrates a pragmatic approach when direct modification is not permitted. Verify that the version change (v2 vs. v1) is intentional and documented elsewhere if needed.
63-69: Important Notes Section
The list of important notes is succinct and emphasizes the rationale behind resource protection. This helps reinforce why such errors occur.
70-72: Related Errors Section
The related error links are clearly stated and encourage further exploration of connected topics, enhancing the overall documentation quality.apps/docs/api-reference/errors-v2/unkey/data/assertion_failed.mdx (1)
1-58: Well-structured error documentation with comprehensive guidance!The documentation for this internal server error is clear, informative, and provides excellent guidance for users. The separation between explanation, possible causes, and resolution steps makes it easy to understand and act upon.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~23-~23: Possible missing comma found.
Context: ...sing of your request. Unlike validation errors which occur when your input is invalid,...(AI_HYDRA_LEO_MISSING_COMMA)
go/pkg/zen/auth_test.go (5)
10-10: Good addition of the codes package import.The addition of the codes package aligns with the overall refactoring to use structured error codes.
20-20: Well-structured migration from error tags to specific error codes.Replacing the generic
errTagfield with the more specificcodefield usingcodes.URNimproves error handling clarity and specificity.
32-32: Good use of specific authentication error codes.The implementation now uses detailed error codes from the
codes.Auth.Authenticationnamespace, making error reporting more precise and contextual.Also applies to: 38-38, 50-50, 56-56
79-88: Enhanced error validation logic.The updated error checking correctly validates the presence and value of the error code using
fault.GetCode(err). The conditions properly handle both cases where a code is expected and where no code should be present.
94-94: Improved test assertions with require.Equal.Changing from
assert.Equaltorequire.Equalis a good practice as it causes tests to fail immediately when assertions don't pass, preventing potentially misleading follow-up errors.Also applies to: 111-111
apps/docs/api-reference/errors/code/INSUFFICIENT_PERMISSIONS.mdx (4)
6-7: Clear and informative overview section.The overview effectively distinguishes this specific permissions error from the broader FORBIDDEN error, providing users with precise context.
9-14: Helpful addition of common causes.This section adds significant value by helping users quickly identify potential reasons for the error, facilitating faster troubleshooting.
16-40: Excellent enhancement of resolution steps.The expanded resolution guidance with practical curl examples provides concrete, actionable steps for users to resolve permission issues. The structured, step-by-step approach is particularly helpful.
42-45: Valuable related resources section.The addition of links to related documentation helps users find more comprehensive information about permissions and access control.
apps/docs/api-reference/errors-v2/unkey/authorization/key_disabled.mdx (4)
1-77: Comprehensive and well-structured error documentation.This documentation for the key_disabled error is excellent. It clearly explains the error, provides context with JSON examples, and offers practical resolution steps.
27-32: Helpful practical example with curl command.Including a concrete example of how this error might be triggered helps users better understand the context and identify if they're experiencing this specific issue.
58-62: Great implementation example for the solution.The curl example showing how to use a reactivated key provides immediate, actionable guidance that users can directly apply to their code.
64-72: Valuable "Common Mistakes" section.This section anticipates potential issues users might face and provides preemptive guidance, which significantly enhances the documentation's usefulness.
apps/docs/docs.json (1)
1-508: Documentation structure is comprehensive and well-organizedThis configuration file provides an extensive and well-structured documentation layout for Unkey. The error handling section under "Errors v2" (lines 174-222) is particularly relevant to the PR objectives, providing a properly categorized and comprehensive documentation structure for the new error handling system.
The organization into Application, Authentication, Authorization, and Data categories creates a logical structure that will help users quickly find the specific error information they need.
apps/docs/api-reference/errors-v2/unkey/authorization/workspace_disabled.mdx (1)
1-69: Error documentation is clear and follows a consistent formatThe documentation for this error provides a complete picture with example JSON, clear explanation, and actionable steps to resolve the issue. This structured approach to error documentation will significantly improve developer experience.
🧰 Tools
🪛 LanguageTool
[uncategorized] ~48-~48: You might be missing the article “the” here.
Context: ...key.com/settings/billing) 2. Contact workspace administrator: If you're not the work...(AI_EN_LECTOR_MISSING_DETERMINER_THE)
apps/docs/api-reference/errors-v2/unkey/data/role_not_found.mdx (1)
1-82: Comprehensive error documentation with practical examplesThis error documentation follows the same consistent format as other error pages, providing clear explanations and practical examples. The structure with "What Happened?", "How To Fix", and "Common Mistakes" sections gives developers a complete understanding of the error and resolution paths.
🧰 Tools
🪛 Gitleaks (8.21.2)
21-22:
(curl-auth-header)
36-37:
(curl-auth-header)
go/apps/api/routes/v2_ratelimit_get_override/handler.go (3)
47-52: Improved error handling with standardized error codesThe refactoring from ad-hoc error handling to using the new structured error code system with URNs is a significant improvement. Using
db.IsNotFound(err)is a good abstraction that simplifies the code and makes it more maintainable.
99-104: Consistent error handling pattern appliedThe same improved error handling pattern is applied here for override not found errors, providing consistency in error reporting throughout the codebase.
141-144: Validation error code correctly appliedThe use of
codes.App.Validation.InvalidInput.URN()is appropriate for this validation error. This change aligns with the overall error handling improvements in the PR.go/pkg/codes/unkey_auth.go (1)
1-57: Well-structured error code system with clear hierarchical organization.This file establishes a comprehensive structure for authentication and authorization errors, which enhances maintainability and consistency. The hierarchical organization of error codes makes them easily referenceable throughout the codebase.
I particularly like the detailed documentation for each error type and the consistent naming pattern using URN-like structures (
SystemUnkey,CategoryUnkeyAuthentication, etc.). This approach will make error handling more systematic across the application.apps/docs/api-reference/errors-v2/unkey/data/api_not_found.mdx (2)
1-82: Clear and structured error documentation with helpful examples.This document provides comprehensive guidance on the API not found error, following the same consistent structure as other error documentation. The examples for listing and creating APIs are particularly useful for troubleshooting.
78-82:Details
✅ Verification successful
Verify link paths for related errors.
The relative paths used in the "Related Errors" section may depend on the documentation structure.
🏁 Script executed:
#!/bin/bash # Verify that the linked error documentation files exist at the specified paths # Check for the workspace_not_found file echo "Checking for workspace_not_found documentation..." if [ -f "apps/docs/api-reference/errors-v2/unkey/data/workspace_not_found.mdx" ]; then echo "✅ workspace_not_found.mdx exists" else echo "❌ workspace_not_found.mdx does not exist" fi # Check for the key_not_found file echo "Checking for key_not_found documentation..." if [ -f "apps/docs/api-reference/errors-v2/unkey/data/key_not_found.mdx" ]; then echo "✅ key_not_found.mdx exists" else echo "❌ key_not_found.mdx does not exist" fi # Check for the insufficient_permissions file echo "Checking for insufficient_permissions documentation..." if [ -f "apps/docs/api-reference/errors-v2/unkey/authorization/insufficient_permissions.mdx" ]; then echo "✅ insufficient_permissions.mdx exists" else echo "❌ insufficient_permissions.mdx does not exist" fiLength of output: 801
Relative links verified – no changes required.
After checking, all the linked documentation files exist at the specified paths:
- apps/docs/api-reference/errors-v2/unkey/data/workspace_not_found.mdx
- apps/docs/api-reference/errors-v2/unkey/data/key_not_found.mdx
- apps/docs/api-reference/errors-v2/unkey/authorization/insufficient_permissions.mdx
The relative paths in the "Related Errors" section are correct. No modifications are required at this time.
apps/docs/api-reference/errors-v2/unkey/data/key_auth_not_found.mdx (4)
1-4: Front Matter: Clear and Concise
The YAML front matter is correctly formatted and clearly identifies the error with an appropriate title and description.
33-42: Example Request: Secure and Informative
The provided cURL command clearly demonstrates how the error can be triggered. Ensure that the example API key (unkey_YOUR_API_KEY) remains a placeholder and that no sensitive information is exposed.🧰 Tools
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
44-61: Resolution Guidance: Actionable and Clear
The "How To Fix" section offers actionable steps along with another illustrative cURL command. The instructions are clear and help direct users on troubleshooting steps.🧰 Tools
🪛 Gitleaks (8.21.2)
55-57:
(curl-auth-header)
63-73: Additional Context: Related Errors
The "Common Mistakes" and "Related Errors" sections provide valuable context and cross-references. No changes are needed.apps/docs/api-reference/errors/code/TOO_MANY_REQUESTS.mdx (5)
6-8: Overview Section: Concise Error Definition
The Overview section succinctly defines the TOO_MANY_REQUESTS error and its impact. The content is clear and helpful.🧰 Tools
🪛 LanguageTool
[misspelling] ~7-~7: Did you mean “two” or “tool”?
Context: ...ErrTooManyRequests --- ## Overview The TOO_MANY_REQUESTS error (HTTP 429) occurs w...(TOO_TOOL)
9-16: Common Causes: Comprehensive Coverage
The bullet points under "Common Causes" effectively cover the various scenarios triggering this error.
37-51: Increasing Rate Limits via cURL Command
The cURL command illustrates how to update rate limit settings effectively. Verify that the API endpoint and header formats adhere to security best practices.
53-57: Additional Recommendations
The suggestions regarding optimizing request patterns, monitoring usage, and distributing load are concise. They provide valuable best practices to users experiencing rate limit issues.
59-62: Related Resources Section
The links under "Related Resources" are correctly formatted and point users to additional helpful resources.🧰 Tools
🪛 LanguageTool
[uncategorized] ~60-~60: If this is a compound adjective that modifies the following noun, use a hyphen.
Context: ... queue system. ## Related Resources - Rate Limiting Guide - [H...(EN_COMPOUND_ADJECTIVE_INTERNAL)
apps/docs/api-reference/errors-v2/unkey/data/permission_not_found.mdx (6)
1-4: Front Matter: Clear Documentation
The YAML header clearly documents the error "permission not found" with an appropriate title and description.
7-19: JSON Example: Accurate and Informative
The JSON example is well structured and conveys the error details correctly. No issues noted.
31-42: Example Request: Clear Usage Illustration
The cURL command example neatly demonstrates a scenario that would trigger the error. Ensure that the placeholder API key remains generic.🧰 Tools
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
44-51: How To Fix: Practical Troubleshooting Steps
The resolution instructions are clear and provide concrete steps to verify and correct the issue.
53-69: Additional cURL Examples for Permissions Management
Both the commands for listing and creating permissions are well documented. They provide the user with actionable endpoint examples.🧰 Tools
🪛 Gitleaks (8.21.2)
55-57:
(curl-auth-header)
71-81: Common Mistakes and Related Errors: Informative Links
The sections on common mistakes and related errors are comprehensive and properly linked.apps/docs/api-reference/errors/code/PRECONDITION_FAILED.mdx (4)
6-8: Overview Section: Clear Error Description
The Overview section clearly states the cause of the PRECONDITION_FAILED error with precise language.
9-16: Common Causes: Detailed and Relevant
The bullet list under "Common Causes" covers multiple scenarios accurately. No issues noted.
17-24: Resolution Steps: Step-by-Step Troubleshooting
The Resolution Steps provide a methodical troubleshooting guide with examples. The cURL command in Step 1 is particularly helpful.🧰 Tools
🪛 Gitleaks (8.21.2)
21-22:
(curl-auth-header)
38-42: Related Resources: Useful Cross-References
The links provided under "Related Resources" are relevant and augment the documentation nicely.apps/docs/api-reference/errors-v2/unkey/data/audit_log_not_found.mdx (7)
1-4: Front Matter: Correct and Informative
The YAML header properly identifies the audit log error with a clear title and description.
7-19: JSON Example: Well-Formatted Error Response
The JSON sample clearly illustrates the structure of the error response. Ensure the formatting is consistent for readability.
21-30: Error Context and Common Scenarios Explained
The "What Happened?" section and the list of common scenarios are well explained and provide sufficient context about audit logs.
31-40: Example Request: Demonstrative cURL Command
The provided cURL command for attempting to get a non-existent audit log entry is clear and effectively demonstrates the error scenario.🧰 Tools
🪛 Gitleaks (8.21.2)
35-37:
(curl-auth-header)
51-59: Listing Audit Logs: Clear Example
The cURL command provided for listing recent audit logs is well formatted and offers a practical solution for the user.🧰 Tools
🪛 Gitleaks (8.21.2)
55-57:
(curl-auth-header)
61-67: Common Mistakes: Well-Documented Pitfalls
The section on common mistakes clearly outlines potential issues and helps users avoid common errors.
68-70: Related Errors: Appropriate Cross-Referencing
The related errors section effectively guides users to additional documentation for further context on access issues and workspace mismatches.apps/docs/api-reference/errors/code/INTERNAL_SERVER_ERROR.mdx (4)
6-7: Great update to the error documentation structure and content!Renaming "Problem" to "Overview" and adding a clear explanation of what an HTTP 500 error means provides better context for users encountering this error.
9-15: Excellent addition of common causes section!This comprehensive list of potential causes helps users understand the various reasons why they might encounter this error, which is crucial for effective troubleshooting.
17-30: Well-structured resolution steps with actionable guidance.The step-by-step format with numbered instructions and specific details (like what to include when reporting an issue) makes this section much more useful than a generic "contact support" message.
32-34: Helpful addition of related resources.Including direct links to the status page and support contact information makes it easier for users to find help when needed.
apps/docs/api-reference/errors-v2/unkey/data/workspace_not_found.mdx (5)
7-19: Well-structured error response example.The JSON example clearly illustrates the error response format with all essential fields, helping developers understand what to expect when handling this error programmatically.
21-30: Clear explanation of error causes and scenarios.This section effectively communicates when this error occurs and provides a comprehensive list of common scenarios that might trigger it, which helps with troubleshooting.
🧰 Tools
🪛 Gitleaks (8.21.2)
21-22:
(curl-auth-header)
43-58: Comprehensive troubleshooting steps.The "How To Fix" section provides clear, actionable guidance including verification steps and example commands, which is very helpful for developers encountering this error.
60-65: Great addition of common mistakes section.Highlighting common mistakes like permission issues and copy-paste errors helps users quickly identify and resolve the root cause of their issue.
67-70: Good cross-referencing to related errors.Linking to related errors creates a cohesive documentation experience and helps users navigate to relevant information if their issue is actually related to one of these other error types.
go/apps/api/routes/v2_identities_create_identity/handler.go (8)
18-18: Good addition of the codes package import.This import is necessary for the transition from tag-based to code-based error handling.
79-81: Correct implementation of the new error code approach for authorization errors.Using
fault.WithCode(codes.Auth.Authorization.InsufficientPermissions.URN())provides more specific information about the error type compared to the previous tag-based approach.
89-91: Proper use of validation error codes.Replacing generic error tags with specific validation error codes improves error clarity and consistency.
97-99: Appropriate error code for metadata size validation.Using the
codes.App.Validation.InvalidInput.URN()code for metadata size validation provides a clear indication of the error type.
107-110: Good replacement of database error tag with service unavailable code.This change improves error specificity, clearly indicating that the database service is unavailable rather than using a generic database error tag.
131-134: Appropriate use of duplicate error code for identity conflicts.Using
codes.Data.Identity.Duplicate.URN()provides a more descriptive error type for duplicate identity scenarios.
217-220: Consistent approach to service unavailability errors for audit logs.Using the same service unavailable code for audit log insertion errors maintains consistency in error handling throughout the codebase.
225-228: Consistent error handling for transaction commit failures.Applying the same pattern of using service unavailable codes for database transaction errors ensures a unified approach to error handling.
apps/docs/api-reference/errors-v2/unkey/application/service_unavailable.mdx (6)
7-19: Well-structured error response example.The JSON example clearly illustrates how this error will be presented to clients, making it easier for developers to recognize and handle it appropriately.
21-31: Clear explanation of service unavailability causes.This section effectively distinguishes between unexpected errors and known service unavailability states, and lists common causes which aids in troubleshooting.
44-52: Excellent guidance on handling temporary service issues.Providing multiple strategies for handling this error, including retry logic, checking service status, and trying alternate regions, gives developers comprehensive options for dealing with service unavailability.
53-89: Exceptional example of retry implementation.The detailed Bash script example with exponential backoff is extremely valuable as it demonstrates a best practice for handling temporary service disruptions. This goes beyond simple documentation to provide actionable code that developers can adapt.
91-97: Important operational notes enhance the documentation.Including notes about the temporary nature of the error, recommending circuit breakers for critical applications, and providing guidance on contacting support adds significant value to this documentation.
98-100: Good cross-referencing to related errors.Linking to related error types helps create a cohesive documentation experience and directs users to relevant information if they're dealing with similar but distinct errors.
go/apps/api/routes/v2_ratelimit_delete_override/handler.go (3)
52-57: Good addition of structured error codes.The updated error handling with specific URN-based error codes provides better clarity and consistency across the application. The error messages are clear and informative.
120-125: Consistent error handling for resource not found.The implementation of structured error handling for the "override not found" case is consistent with the namespace not found case. This improves the API's error reporting consistency.
211-214: Appropriate validation error code.The use of the
InvalidInputerror code for missing namespace parameters is appropriate and clearly communicates the issue to API consumers.apps/docs/api-reference/errors-v2/unkey/authorization/insufficient_permissions.mdx (2)
7-19: Well-structured error example.The JSON error example is clear and follows a consistent format. It provides all necessary fields an API consumer would need to understand and handle the error.
64-72: Comprehensive list of common mistakes.The "Common Mistakes" section is thorough and covers the most likely scenarios users might encounter. This is very helpful for troubleshooting and prevention.
apps/docs/api-reference/errors-v2/unkey/data/ratelimit_override_not_found.mdx (3)
7-19: Well-structured error example.The JSON error example is clear, well-formatted, and follows the standard error response structure used throughout the API. This consistency helps developers easily recognize and handle errors.
25-30: Comprehensive scenarios list.The list of common scenarios that trigger this error is thorough and covers the most likely cases. This helps users quickly identify the root cause of their issue.
84-87:Details
✅ Verification successful
Check links to other error documents.
Ensure that all the linked error documents exist or will be created as part of this PR. Missing links in documentation can be frustrating for users.
🏁 Script executed:
#!/bin/bash # Check that the linked error documents exist echo "Checking if linked error documents exist:" echo "- err:unkey:data:ratelimit_namespace_not_found" fd --type file "ratelimit_namespace_not_found.mdx" apps/docs/ echo "- err:unkey:authorization:insufficient_permissions" fd --type file "insufficient_permissions.mdx" apps/docs/ echo "- err:unkey:data:workspace_not_found" fd --type file "workspace_not_found.mdx" apps/docs/Length of output: 856
Linked error documents verified: No changes required.
- The file linked as err:unkey:data:ratelimit_namespace_not_found exists at
apps/docs/api-reference/errors-v2/unkey/data/ratelimit_namespace_not_found.mdx- The document for err:unkey:authorization:insufficient_permissions is present both at
apps/docs/api-reference/errors/code/INSUFFICIENT_PERMISSIONS.mdxandapps/docs/api-reference/errors-v2/unkey/authorization/insufficient_permissions.mdx- The file for err:unkey:data:workspace_not_found is located at
apps/docs/api-reference/errors-v2/unkey/data/workspace_not_found.mdxAll linked documentation is in place as expected.
go/pkg/codes/unkey_application.go (2)
5-11: Consider clarifying usage for unexpected internal errors.The
appInternalstruct provides baseline error fields, but it’s not immediately clear how these fields are consumed and logged. Consider adding usage examples or references to ensure developers understand when and how to returnUnexpectedErrorvs.ServiceUnavailable.
45-59: Double-check global usage ofApp.
var App = UnkeyAppErrors{...}is a global variable providing quick references to error codes. While convenient, ensure that modifying it in the future does not break existing references. For large codebases, a functional constructor or constants-based approach can prevent accidental reassignments.go/pkg/codes/generate.go (1)
65-81: Confirm that skipping generated files covers all relevant patterns.Currently,
_gen.goandgenerate.goare excluded. If other naming conventions are used for generated files (e.g.,.generated.go), these may be inadvertently included. Confirm that this pattern captures all generated artifacts to prevent comment extraction from the wrong files.apps/docs/api-reference/errors-v2/unkey/data/ratelimit_namespace_not_found.mdx (7)
1-5: Excellent metadata structure!The frontmatter is clear and descriptive, making it easy for documentation systems to render and index this page appropriately.
7-19: Well-structured error example!The JSON example provides a clear template of what developers can expect when encountering this error. The inclusion of a
requestIdin the metadata is particularly useful for support and debugging purposes.
21-32: Clear explanation of the error scenarioThe explanation effectively communicates what causes this error and provides common scenarios that might trigger it, which is very helpful for developers trying to troubleshoot.
33-41: Good example of problematic requestProviding a concrete example of a request that would trigger this error helps developers recognize similar patterns in their own code.
43-64: Comprehensive troubleshooting stepsThe "How To Fix" section provides actionable steps and includes a practical example of the correct approach, making it easy for developers to resolve the issue quickly.
66-72: Useful common mistakes sectionHighlighting common mistakes related to this error helps developers avoid them in the first place or quickly identify them when troubleshooting.
73-77: Helpful related errors sectionCross-linking to related errors creates a web of knowledge that helps developers navigate through potential issues they might encounter while troubleshooting.
go/apps/api/routes/v2_ratelimit_limit/handler.go (4)
18-18: Good addition of codes package importThis import enables the transition to the new URN-based error code system, aligning with the PR objective of improving error handling.
87-92: Improved error handling for namespace not foundThe error handling has been enhanced to use the new URN-based error code system instead of generic tags, providing more specific and structured error responses. This will make debugging and error handling more consistent.
98-99: Consistent error code usage for deleted namespaceUsing the same error code (codes.Data.RatelimitNamespace.NotFound.URN()) for both the not-found case and the deleted case maintains consistency in the API's error reporting, which is a good practice.
127-129: Enhanced authorization error handlingThe transition from tag-based to code-based error handling for authorization errors improves consistency and specificity in the API's error responses.
apps/docs/api-reference/errors-v2/unkey/application/assertion_failed.mdx (4)
1-19: Well-structured error documentationThe metadata and JSON example are clear and provide a good template for what developers can expect when encountering this error. Including the HTTP status code (500) in the response is particularly helpful.
34-47: Comprehensive troubleshooting guidanceExcellent section on how to respond to this error. The guidance for contacting support with specific information is particularly valuable for resolving internal system issues.
48-54: Helpful important notes sectionThese notes clearly set expectations that this error indicates internal issues rather than user mistakes, which helps prevent users from wasting time trying to fix their requests when the issue is on the system side.
55-57: Good related errors cross-referencesLinking to related errors helps users navigate to relevant information if they're experiencing similar issues, enhancing the overall documentation experience.
go/pkg/urn/resource.go (3)
9-18: Well-defined resource type constantsThe
ResourceTypetype and its constants are clearly defined with descriptive names. The comment "Add more as needed" indicates good forward thinking for extensibility.
20-45: Good service validation implementationThe
ValidateForServicemethod correctly validates the service first before proceeding with resource type validation, which follows a good pattern of failing fast and clearly.
46-55: Robust validation logic with clear error messagesThe validation logic handles edge cases well, including checking if a service has defined resource types at all. The error message from
assert.Trueis descriptive and will help with debugging.go/pkg/zen/middleware_errors.go (9)
14-14: Doc comment enhancement.
It’s good to mention that error URNs enhance traceability and consistency across the system. Consider adding a brief example of how an URN maps to documentation.
24-34: Fallback to unexpected error is appropriate.
When no URN is found or parsing fails, defaulting to an unexpected error code is a sensible approach to avoid returning ambiguous or empty error responses. Ensure you log these fallback occurrences for better diagnostics.
36-48: Granular "Not Found" error mapping is clear.
Using distinct URNs for different "Not Found" scenarios greatly improves debugging.
61-75: Bad Request response creation.
The structuredBadRequestErrorResponsewithBadRequestErrorDetailsaligns well with explicit feedback to users about invalid inputs. Great job.
77-93: Unauthorized error coverage.
The additional cases (e.g., missing or malformed authentication) give end-users clearer explanations about why their requests are rejected.
94-108: Forbidden error usage is consistent.
Mapping forbidden scenarios to theForbiddenErrorResponsefosters uniform user feedback.
109-122: Insufficient Permissions.
Separating this from a generic "Forbidden" message clarifies the root cause (lack of necessary permissions) vs. a more general prohibition.
123-136: Conflict for duplicate identity.
Returning a conflict status code precisely indicates a resource or data conflict. Looks good.
137-150: Precondition Failed for protected resource.
Using HTTP 412 is a neat approach here; it conveys the resource constraints succinctly.apps/docs/api-reference/errors-v2/unkey/application/unexpected_error.mdx (2)
1-4: Front matter looks good.
No issues found with the title and description metadata.
45-75: Comprehensive retry logic.
The exponential backoff pattern with jitter is well-explained. This helps users implement resilience in their code.🧰 Tools
🪛 Gitleaks (8.21.2)
55-57:
(curl-auth-header)
go/pkg/urn/service.go (5)
1-5: Imports and package structure.
Importingassertis appropriate for simple checks. Great approach for clean error messages.
7-8: Service type definition.
Introducing a typed string clarifies usage across the codebase for service names.
10-19: Service constants for known namespaces.
This enumerated approach benefits maintainability and consistency if new services are added later.
21-31: validServices map.
A quick lookup map is efficient for membership checks.
33-37: Validate method usage.
The error message correctly spells out valid options. This helps catch mistakes early.go/pkg/fault/code_test.go (10)
8-8: Importing the newcodespackage looks good.
No issues with the import statement; it aligns well with the refactoredcodes.URNusage.
11-11: Renaming test function toTestGetCodeaccurately reflects new logic.
No functional issues found.
23-23: Untagged error returning empty code is consistent with the chosen design.
Implementation logic appears correct for untagged errors.Also applies to: 25-25
29-30: UsingWithCode(codes.URN("CUSTOM_TAG"))is correctly tested.
The test ensures that custom codes are recognized properly.
34-35: Nested error tags: functionality correctly verifies the outer code is returned.
This confirms the unwrapping logic returns the first encountered code.Also applies to: 37-37
43-44: Double-check the ignored boolean return fromGetCode.
You might verify whether you need to assert onokto ensure correctness, especially if future logic depends on it.
49-49:TestWithCodename andtag codes.URNusage align with the new approach.
No concerns; the refactor is consistent with thecodes.URNdesign.Also applies to: 52-52
58-58:codes.URN("TEST")usage is fine.
It’s a clear, static test value matching expected usage.
66-66: Verifying wrapped error code matchesTEST_TAG.
Confirms correct application ofWithCode.Also applies to: 71-71
78-78:result := WithCode(tt.tag)(tt.err)is logically consistent.
Implementation properly demonstrates the wrapper logic.go/apps/api/routes/v2_ratelimit_set_override/handler.go (9)
16-16: New import forcodesis consistent with the refactored error handling.
58-58: Appropriately returnscodes.Data.RatelimitNamespace.NotFoundon missing namespace.
Checks out forsql.ErrNoRows.
67-67: UsingNotFoundcode for workspace mismatch could mask a permission issue.
Confirm this is intentional or consider returning a more appropriate code (e.g., 403).
96-96:codes.Auth.Authorization.InsufficientPermissionsis correct.
It clearly communicates insufficient privileges.
104-104: RaisingServiceUnavailablefor failing to create transaction is acceptable.
However, a 500-level “Internal” code could also fit this scenario.
127-127: UsingServiceUnavailablefor DB insert failures is consistent with prior usage.
No issues found.
158-158: Continuing theServiceUnavailablecode pattern for audit log insert errors.
Maintains consistency; no immediate concerns.
166-166: ReturningServiceUnavailablefor transaction commit errors.
Consistent with the preceding code, though a general internal error might also apply.
199-199:InvalidInputcode for missing namespace ID or name is appropriate.
Matches a user input error scenario.go/pkg/fault/dst_test.go (13)
17-18: Added imports forrequireandcodesare correct.
They align with the new refactored tests relying oncodes.URN.
40-40:code []codes.URNfield replaces tags with URNs.
This maintains consistency with the updated error representation.
91-91: Renamed function to clarify random code generation.
Enhances code clarity by expressing the shift from tags to URNs.
92-92:generateRandomTagnow returningcodes.URN.
Implementation properly constructs a random code string.Also applies to: 97-97
103-103: Switch tocode: make([]codes.URN, numTags)inErrorComponents.
Correctly aligns with the new approach of storing URNs.
109-109: Accurate comment update ("Generate code") to reflect new URN usage.
Minor doc improvement aligns with the new naming.
111-111: Populatingcomponents.code[i]with generated URNs is valid.
Implementation is straightforward.
146-146: Updated function signature to return([]codes.URN, []string, error).
Clear shift from tag slices tocodes.URNslices.
148-148:usedTags := make([]codes.URN, 0, depth)correctly initializes URNs.
No fields or logic errors found.
159-161: Appending codes withfault.WithCodeand tracking them inusedTags.
Demonstrates correct usage of the new URN-based error codes.
187-187: Logging sample tags for debug is convenient.
No performance or security concerns here.
200-203: Comparing final code to the last code inexpectedTags.
Ensures the test scenario matches the outermost code logic in multi-wrapped errors.
225-226: Verifying reproducibility with the same seed for code generation.
Ensures deterministic test outcomes and correct randomization logic.Also applies to: 231-231
go/pkg/codes/codes.go (6)
1-6: Package and Imports Look Good
All imports are minimal and context-appropriate. There are no concurrency or security issues visible in these lines.
8-15: Well-Defined Prefix and Separator Constants
DefiningPrefixandSeparatorat the top is a clean, centralized approach that helps ensure consistent formatting across the codebase.
38-63: Category Typing is Clear
TheCategorytype is well-named, providing a second-level domain for errors. No immediate issues are detected.
65-77: Struct-Based Error Metadata
Using a struct to incorporateSystem,Category, andSpecificeffectively conveys the unique identity of an error. This pattern fosters clarity and extensibility.
85-91: DocsURL() Correctly References an External Docs Page
Linking directly to the documentation is helpful for debugging and user support. Be sure thatunkey.comremains stable as the product grows.
93-101: ParseURN Relies on ParseCode
Delegating toParseCodekeeps parsing logic centralized. No issues detected here.go/pkg/urn/urn.go (7)
1-10: Package Declaration and Imports
No extraneous imports, and references toassertandfaultare consistent with the rest of the codebase. Looks good.
11-19: URN Struct Is Clearly Documented
The field-level comments make it easy to understand each component’s significance. No concurrency or memory management issues.
21-26: String() Method
String-building logic is straightforward. A minor improvement could be to ensure that any future changes to the format are well tested, but there's no direct issue here.
38-41: validateNamespace
Requires the namespace to be “unkey,” which aligns with your domain requirements. No security pitfalls here.
43-50: validateWorkspaceID
Enforcing the prefix “ws_” is a clear requirement. No suggestions; it’s well done.
60-84: validateResourceID
Switch-based prefix checks for eachResourceTypekeep the code organized. It’s flexible enough to accommodate new resource types in the future.
140-165: New Function
Centralizing validation inNewis a good pattern, ensuring any URN constructed in code meets the same constraints as those parsed from a string.go/pkg/codes/unkey_data.go (3)
1-4: File Introduction
File naming and block-level comments are clear about its purpose: data-related errors.
53-60:dataIdentityDuplicate Error
Defining a specific Code for “Duplicate” is helpful. This approach standardizes responses for resource collisions and improves user messaging.
84-128: Initialization ofData
Providing all resource-specificNotFoundcodes (andDuplicatefor identities) in a single location is consistent with your approach incodes.go. It simplifies referencing these codes across the codebase.go/pkg/codes/constants_gen.go (21)
1-3: Auto-generated File Header Notice
The header clearly indicates that the file is auto-generated and should not be manually edited, including a generation timestamp. This is ideal for maintaining consistency with generated artifacts.
4-8: Package Declaration and URN Type Definition
The package declaration and the customURNtype are clearly defined. This establishes a solid foundation for the subsequent error code constants.
9-10: Constant Block Setup
The opening comment for the constant block explains its purpose for exhaustive error checking via switch statements, which is informative and aligns well with the intended use.
11-14: UnkeyAuthErrors Section Header
The section header forUnkeyAuthErrors(lines 11–14) is well-formatted and uses clear separators. This aids readability and future maintenance.
15-16: Authentication Category Label
The "Authentication" label (lines 15–16) succinctly introduces the related error constants. Good use of in-line documentation.
17-22: Authentication Error Constants
The authentication error constants (Missing,Malformed, andKeyNotFound) are documented clearly with descriptive comments, ensuring that their error contexts are immediately understandable.
24-34: Authorization Error Constants
The authorization errors (InsufficientPermissions,Forbidden,KeyDisabled, andWorkspaceDisabled) are defined with detailed comments that clarify their purpose. This clear delineation is vital for consistent error handling.
36-39: UnkeyDataErrors Section Header
The section header forUnkeyDataErrorsis clearly marked with separators, which makes the file structure easy to follow.
40-44: Key Error Constant
The error constant for a missing key (UnkeyDataErrorsKeyNotFound) is defined appropriately with an explanatory comment.
45-48: Workspace Error Constant
TheUnkeyDataErrorsWorkspaceNotFoundconstant is well-named and clearly documented, ensuring its purpose is unambiguous.
50-54: API Error Constant
The API-related error (UnkeyDataErrorsApiNotFound) is defined with a clear, concise comment, facilitating easy error identification in API-related operations.
55-59: Permission Error Constant
The permission error (UnkeyDataErrorsPermissionNotFound) is explained clearly through the comment, aligning with the overall consistency seen in the other error code definitions.
60-64: Role Error Constant
The error constant indicating a missing role (UnkeyDataErrorsRoleNotFound) is defined consistently with its counterparts and uses straightforward language.
65-69: KeyAuth Error Constant
The constantUnkeyDataErrorsKeyAuthNotFoundis well-documented, ensuring that key authentication related errors are unambiguous to developers.
70-74: RatelimitNamespace Error Constant
The error constant for a missing rate limit namespace (UnkeyDataErrorsRatelimitNamespaceNotFound) is defined correctly, maintaining consistency in naming and documentation.
75-79: RatelimitOverride Error Constant
The constantUnkeyDataErrorsRatelimitOverrideNotFoundis accurately defined, with its naming and documentation clearly indicating its purpose within rate limiting error scenarios.
80-86: Identity Error Constants
Both identity-related constants (UnkeyDataErrorsIdentityNotFoundandUnkeyDataErrorsIdentityDuplicate) are clearly defined with descriptive comments. Their naming effectively communicates the error conditions.
87-91: AuditLog Error Constant
The error constant for a missing audit log (UnkeyDataErrorsAuditLogNotFound) is succinctly described, ensuring that error reporting in audit log operations remains clear.
92-94: UnkeyAppErrors Section Header
The section header forUnkeyAppErrorsis distinctive and well-organized, effectively separating application-level errors from authentication and data errors.
96-102: Internal Error Constants
The internal error constants (UnkeyAppErrorsInternalUnexpectedErrorandUnkeyAppErrorsInternalServiceUnavailable) clearly describe critical failure scenarios in the application, adhering to a consistent naming convention.
110-114: Protection Error Constant
TheUnkeyAppErrorsProtectionProtectedResourceconstant is concise and well-documented, clearly signaling that modifications to protected resources are flagged appropriately.
go/apps/api/integration/multi_node_ratelimiting/generate_tests/main.go
Outdated
Show resolved
Hide resolved
apps/docs/api-reference/errors-v2/unkey/data/identity_already_exists.mdx
Show resolved
Hide resolved
* refactor: remove request_id from cursors (#3093) * refactor: remove requestid from logs cursor * fix: cursor object * refactor: remove request_id from ratelimit overview cursor * refactor: remove request_id from ratelimit logs * refactor: remove request id from api cursor * fix: type issue and make query shorter --------- Co-authored-by: Andreas Thomas <dev@chronark.com> * feat: errors v2 (#3110) * feat: /v2/apis/createApi endpoint * ci: install api dependencies * feat: errors * [autofix.ci] apply automated fixes * revert: breaking changes * revert: bad copypaste * fix: bad copypaste --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> * feat: use axiom * fix: don't hide the cool dots --------- Co-authored-by: Oğuzhan Olguncu <21091016+ogzhanolguncu@users.noreply.github.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
* add: initial layout * feat: add new api keys page * feat: add color to expires badge * [autofix.ci] apply automated fixes * feat: add chart * feat: finalize usage chart * fix: expires component * fix: timestamps and chart colors * fix: build issues * feat: add draft of status popover * fix: status cleanup * feat: finalize status design * fix: Style issues * feat: add configurable skeletons to table * fix: identitiy * fix: total count * chore: remove unused component * feat: add two new operator to key id filter * fix: type issues * fix: identity filter * feat: add ai saerch to keys * fix: add status condition for disabled * fix: some styling issues * refactor: improve schema structure * chore: remove unused types * fix: navbar * feat: add dynamic key to popover menu * fix: coderabbit issues * fix: number formatting and filtering logic for outcome explainer * fix: empty state message * refactor: refinements * chore: remove old keys * fix: import paths * fix: header wording * fix: secret hover (#3111) * refactor: remove request_id from cursors (#3093) * refactor: remove requestid from logs cursor * fix: cursor object * refactor: remove request_id from ratelimit overview cursor * refactor: remove request_id from ratelimit logs * refactor: remove request id from api cursor * fix: type issue and make query shorter --------- Co-authored-by: Andreas Thomas <dev@chronark.com> * feat: errors v2 (#3110) * feat: /v2/apis/createApi endpoint * ci: install api dependencies * feat: errors * [autofix.ci] apply automated fixes * revert: breaking changes * revert: bad copypaste * fix: bad copypaste --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> * feat: use axiom * fix: don't hide the cool dots --------- Co-authored-by: Oğuzhan Olguncu <21091016+ogzhanolguncu@users.noreply.github.com> Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> * revert: bad commits * fix: merge errors * [autofix.ci] apply automated fixes --------- Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com> Co-authored-by: chronark <dev@chronark.com>
Summary by CodeRabbit
Documentation
New Features
Chores