Repository navigation
docs: add OpenAPI 3.1 spec and Swagger UI - #22
Conversation
|
Caution Review failedThe pull request is closed. 📝 WalkthroughWalkthroughServes a static OpenAPI spec at /openapi.yaml and a Swagger UI page at /docs; adds Changes
Sequence Diagram(s)sequenceDiagram
participant Dev as Developer/Browser
participant UI as Swagger UI (static HTML/JS)
participant GW as Gateway (server)
rect rgb(235, 245, 255)
Dev->>GW: GET /docs
GW-->>Dev: Swagger UI HTML (serves UI)
end
rect rgb(255, 250, 235)
UI->>GW: GET /openapi.yaml
GW-->>UI: openapi.yaml (spec)
UI-->>Dev: Render interactive docs
end
note over UI,GW: Dev may invoke API via UI (e.g., POST /api/ai/summarize)
Dev->>GW: POST /api/ai/summarize (via UI)
GW-->>Dev: API response (200 / 402 / 403 / 500)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
📜 Recent review detailsConfiguration used: defaults Review profile: CHILL Plan: Pro 📒 Files selected for processing (3)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Additional Comments (3)
-
gateway/main.go, line 50 (link)syntax: Indentation is inconsistent - line uses space instead of tab
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
-
gateway/openapi.yaml, line 75-94 (link)logic: The
/verifyendpoint is served by the separate verifier service (Rust, port 3002), not by this gateway. This endpoint shouldn't be in the gateway's OpenAPI spec - it creates confusion about which service handles verification. -
gateway/openapi.yaml, line 68-73 (link)style: Missing detailed schemas for error responses. The 402 response should document the
paymentContextobject structure (recipient, token, amount, nonce, chainId), 403 should show the error details format, and 500 should document the error structure.Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
3 files reviewed, 3 comments
|
@greptile review the pr and suggest the improvements |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (2)
gateway/openapi_test.go (1)
8-12: LGTM - test correctly verifies file existence.The test appropriately checks that
openapi.yamlexists. This provides a basic safety net during development.For enhanced validation, consider optionally parsing the YAML to verify it's well-formed:
Optional enhancement: Validate YAML structure
import ( "os" "testing" "gopkg.in/yaml.v3" ) func TestOpenAPISpecExists(t *testing.T) { data, err := os.ReadFile("openapi.yaml") if err != nil { t.Fatalf("openapi.yaml not found: %v", err) } var spec map[string]interface{} if err := yaml.Unmarshal(data, &spec); err != nil { t.Fatalf("openapi.yaml is not valid YAML: %v", err) } if spec["openapi"] == nil { t.Fatal("openapi.yaml missing 'openapi' field") } }Note: This would require adding
gopkg.in/yaml.v3dependency.gateway/openapi.yaml (1)
1-94: Consider adding security schemes for documentation completeness.Static analysis flags missing security definitions. While not strictly required for public endpoints, documenting the X-402 payment headers as a security scheme would improve API clarity for consumers.
Optional: Define security schemes
Add at the top level of the spec:
components: securitySchemes: X402Payment: type: apiKey in: header name: X-402-Signature description: EIP-712 signature for payment authorization (paired with X-402-Nonce) security: [] # No global security requirements; applied per-operationThen reference it in the
/api/ai/summarizeoperation:/api/ai/summarize: post: summary: Summarize text security: - X402Payment: [] - {} # Allow requests without payment (will receive 402) # ... rest of endpoint definitionThis clarifies that the endpoint supports optional payment authentication via headers.
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
gateway/main.gogateway/openapi.yamlgateway/openapi_test.go
🧰 Additional context used
🪛 Checkov (3.2.334)
gateway/openapi.yaml
[high] 1-96: Ensure that the global security field has rules defined
(CKV_OPENAPI_4)
[high] 1-96: Ensure that security operations is not empty.
(CKV_OPENAPI_5)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: Greptile Review
There was a problem hiding this comment.
Looking at this PR, I can see it adds OpenAPI documentation and Swagger UI to the gateway service. Overall it's a good addition for developer experience, but there are several improvements needed:
Major Issues
1. Incorrect /verify endpoint documentation
The OpenAPI spec includes a /verify endpoint, but this is actually served by the separate Rust verifier service on port 3002, not the Go gateway. This creates architectural confusion and will mislead API consumers.
2. Missing error response schemas
The error responses (402, 403, 500) lack proper schema definitions, especially the critical 402 response which should include the paymentContext structure that clients need for payment.
Specific Suggestions
Fix the OpenAPI spec (gateway/openapi.yaml)
openapi: 3.1.0
info:
title: MicroAI Paygate Gateway API
version: "1.0.0"
description: Gateway API for MicroAI Paygate - handles x402 payment protocol and AI request proxying
servers:
- url: http://localhost:3000
description: Local development server
paths:
/healthz:
get:
summary: Health check
description: Returns gateway health status
responses:
"200":
description: Gateway is healthy
content:
application/json:
schema:
type: object
properties:
service:
type: string
example: gateway
status:
type: string
example: ok
/api/ai/summarize:
post:
summary: Summarize text with x402 payment
description: Summarizes text using AI. Requires payment via x402 protocol on first request.
parameters:
- name: X-402-Signature
in: header
required: false
description: EIP-712 signature authorizing payment (required after receiving 402 response)
schema:
type: string
example: "0x1234567890abcdef..."
- name: X-402-Nonce
in: header
required: false
description: Nonce from 402 response (required with signature)
schema:
type: string
format: uuid
example: "550e8400-e29b-41d4-a716-446655440000"
requestBody:
required: true
content:
application/json:
schema:
type: object
required:
- text
properties:
text:
type: string
description: Text to summarize
example: "Artificial intelligence is transforming software development by automating code generation, testing, and deployment processes."
responses:
"200":
description: Summary generated successfully
content:
application/json:
schema:
type: object
properties:
result:
type: string
description: Generated summary
example: "AI is automating software development workflows."
"402":
description: Payment required - client must sign payment context and retry
headers:
X-402-Payment-Context:
description: Base64-encoded payment context for EIP-712 signing
schema:
type: string
content:
application/json:
schema:
type: object
properties:
error:
type: string
example: "Payment required"
paymentContext:
type: object
properties:
nonce:
type: string
format: uuid
recipient:
type: string
example: "0x742d35Cc6e00F8f7f4e7A9f4F1f4E7c3c1f1f1f1"
amount:
type: string
example: "1000000"
token:
type: string
example: "0xA0b86a33E6C6a4b2f4D8c5f1E2F0c0B8D4F3E2A1"
chainId:
type: integer
example: 1
"403":
description: Invalid or expired signature
content:
application/json:
schema:
type: object
properties:
error:
type: string
example: "Invalid signature"
"500":
description: Internal server error
content:
application/json:
schema:
type: object
properties:
error:
type: string
example: "AI service unavailable"
components:
schemas:
PaymentContext:
type: object
description: EIP-712 payment context for x402 protocol
required:
- nonce
- recipient
- amount
- token
- chainId
properties:
nonce:
type: string
format: uuid
description: Unique payment nonce
recipient:
type: string
description: Payment recipient address
pattern: "^0x[a-fA-F0-9]{40}$"
amount:
type: string
description: Payment amount in token base units
token:
type: string
description: Token contract address
pattern: "^0x[a-fA-F0-9]{40}$"
chainId:
type: integer
description: Blockchain network ID
Fix indentation in main.go
The new code has inconsistent indentation. Here's the corrected version:
r := gin.Default()
r.StaticFile("/openapi.yaml", "openapi.yaml")
r.GET("/docs", func(c *gin.Context) {
c.Header("Content-Type", "text/html")
c.String(200, `
<!DOCTYPE html>
<html>
<head>
<title>MicroAI Paygate Gateway API</title>
<link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist/swagger-ui.css" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="https://unpkg.com/swagger-ui-dist/swagger-ui-bundle.js"></script>
<script>
SwaggerUIBundle({
url: '/openapi.yaml',
dom_id: '#swagger-ui',
deepLinking: true,
presets: [
SwaggerUIBundle.presets.apis,
SwaggerUIBundle.presets.standalone
]
});
</script>
</body>
</html>
`)
})
Additional Recommendations
- Consider adding request validation - You could use the OpenAPI spec to validate incoming requests
- Add rate limiting documentation - Document any rate limits in the OpenAPI spec
- Security schemes - Add security scheme documentation for the x402 protocol
- Add examples for error responses - Include example error payloads to help developers understand the format
The PR is a great start for improving the developer experience, but these changes will make the documentation much more accurate and useful.
|
@Vaishnavi-Iyer67 PTAL at the issues |
There was a problem hiding this comment.
1. Remove /verify endpoint from OpenAPI spec
The /verify endpoint is served by the separate Rust verifier service (port 3002), not the Go gateway. Including it here creates architectural confusion for API consumers.
2. Add openapi.yaml to Dockerfile
The Dockerfile only copies the gateway binary but not openapi.yaml. The /docs and /openapi.yaml endpoints will fail at runtime.
3. Complete the error response schemas
The 402/403/500 responses are missing the actual JSON structures returned by the implementation. See main.go lines 100-105, 142, 130, 137, 155 for the actual response formats.
402 response should include:
"402":
description: Payment required
content:
application/json:
schema:
type: object
properties:
error:
type: string
example: "Payment Required"
message:
type: string
example: "Please sign the payment context"
paymentContext:
type: object
properties:
recipient:
type: string
token:
type: string
amount:
type: string
nonce:
type: string
chainId:
type: integer403 response should include:
"403":
description: Invalid signature
content:
application/json:
schema:
type: object
properties:
error:
type: string
details:
type: string500 response should include:
"500":
description: Server error
content:
application/json:
schema:
type: object
properties:
error:
type: string
details:
type: string4. Pin CDN versions (Security)
Loading Swagger UI from unpkg without version pins is a security risk. If the CDN is compromised or serves a breaking update, the /docs page could break or serve malicious content.
5. Fix indentation in main.go
Lines 50-70 have inconsistent indentation - the handler body uses spaces instead of tabs. Please align with the rest of the codebase.
6. Improve the test
The current test only checks if the file exists, but the issue acceptance criteria asks to "verify spec matches endpoints." For now the basic test is fine, but consider adding validation that parses the YAML and checks documented paths exist in the codebase.
Changes Requested
- Remove
/verifyendpoint fromopenapi.yaml - Add
openapi.yamltoDockerfileruntime stage - Add complete error response schemas for 402/403/500 in
openapi.yaml - Pin CDN versions for Swagger UI in
main.go - Fix indentation in
main.golines 50-70 - Improve test to validate spec syntax and endpoint paths
|
Thanks for the detailed review |
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (4)
gateway/Dockerfile (1)
17-17: Remove or professionalize the comment.The emoji and informal tone ("🔴 THIS IS THE IMPORTANT LINE") are not appropriate for production Dockerfile comments. Consider either removing the comment or replacing it with a professional explanation of why this COPY is necessary.
🔎 Suggested improvement
-# 🔴 THIS IS THE IMPORTANT LINE +# Copy OpenAPI spec for runtime serving at /openapi.yaml and /docsgateway/openapi_test.go (1)
10-13: Consider a more robust file path approach.The relative path
"openapi.yaml"will fail if tests are run from a directory other thangateway/. This could cause issues in CI/CD pipelines that run tests from the repository root.🔎 Suggested improvement using filepath.Join
func TestOpenAPISpecMatchesRoutes(t *testing.T) { - data, err := os.ReadFile("openapi.yaml") + data, err := os.ReadFile(filepath.Join(".", "openapi.yaml")) if err != nil { t.Fatalf("failed to read openapi.yaml: %v", err) }Or use build-time embedding for more reliability:
+import _ "embed" + +//go:embed openapi.yaml +var openapiSpec string + func TestOpenAPISpecMatchesRoutes(t *testing.T) { - data, err := os.ReadFile("openapi.yaml") - if err != nil { - t.Fatalf("failed to read openapi.yaml: %v", err) - } - - spec := string(data) + spec := openapiSpecgateway/openapi.yaml (2)
1-7: Consider defining x402 payment as an OpenAPI security scheme.The static analysis tools flag that security definitions are missing. Currently,
X-402-SignatureandX-402-Nonceare defined as operation-level header parameters (lines 33-45). OpenAPI best practice is to model authentication/authorization using security schemes, which makes the security model more discoverable and enables better tooling support.Based on learnings from static analysis hints.
🔎 Suggested improvement: Define x402 as a security scheme
Add a global
componentssection with a security scheme definition:info: title: MicroAI Paygate API version: "1.0.0" description: API documentation for MicroAI Paygate +components: + securitySchemes: + x402Payment: + type: apiKey + in: header + name: X-402-Signature + description: EIP-712 signature authorizing payment, paired with X-402-Nonce header + paths:Then reference it in the
/api/ai/summarizeoperation and remove the duplicate parameter definitions:/api/ai/summarize: post: summary: Summarize text description: Proxies a text summarization request and enforces x402 payment - parameters: - - name: X-402-Signature - in: header - required: false - description: EIP-712 signature authorizing payment - schema: - type: string - - - name: X-402-Nonce - in: header - required: false - description: Nonce from 402 response - schema: - type: string - + security: + - x402Payment: [] + - {} # Allow unauthenticated requests (returns 402) + requestBody:Note: The nonce header (
X-402-Nonce) would need to be kept as a parameter since OpenAPI security schemes don't support multiple related headers cleanly. This is a limitation of OpenAPI but the signature header as the primary security mechanism should be insecuritySchemes.Also applies to: 33-45
85-97: Add descriptions and examples to paymentContext properties.The
paymentContextobject properties (lines 88-97) lack descriptions and examples, which would help API consumers understand the expected formats (e.g., Ethereum addresses forrecipient/token, numeric string foramount, hex string fornonce).🔎 Suggested improvement
paymentContext: type: object properties: recipient: type: string + description: Ethereum address of payment recipient + example: "0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb" token: type: string + description: Ethereum address of ERC-20 token contract + example: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48" amount: type: string + description: Token amount in base units (e.g., wei) + example: "1000000" nonce: type: string + description: Unique nonce for replay protection + example: "0x1a2b3c4d" chainId: type: integer + description: Ethereum chain ID + example: 1
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
web/bun.lockis excluded by!**/*.lock
📒 Files selected for processing (5)
gateway/Dockerfilegateway/main.gogateway/openapi.yamlgateway/openapi_test.goweb/public/.gitkeep
🚧 Files skipped from review as they are similar to previous changes (1)
- gateway/main.go
🧰 Additional context used
🪛 Checkov (3.2.334)
gateway/openapi.yaml
[high] 1-123: Ensure that the global security field has rules defined
(CKV_OPENAPI_4)
[high] 1-123: Ensure that security operations is not empty.
(CKV_OPENAPI_5)
🔇 Additional comments (3)
gateway/openapi_test.go (1)
9-27: Test validates basic requirements.The test successfully verifies that the OpenAPI spec file exists and contains the documented endpoints
/healthzand/api/ai/summarize. This meets the immediate documentation requirements.As noted in previous comments, future enhancements could include parsing the YAML and validating against actual registered routes, but the current implementation is sufficient for this PR's scope.
gateway/openapi.yaml (1)
1-121: OpenAPI specification is functionally complete.The spec correctly documents the Gateway's public endpoints (
/healthzand/api/ai/summarize) with comprehensive request/response schemas. Previous review concerns about missingpaymentContextfields and error response structures have been addressed—the 402 response now includes all payment context fields (recipient, token, amount, nonce, chainId), and the 403/500 responses include error and details fields.The spec aligns with the PR objectives and will enable interactive testing via Swagger UI and future SDK generation.
gateway/Dockerfile (1)
18-18: The Docker build context assumption is already correct—no changes needed.The build is configured with context
./gatewayin docker-compose.yml, andopenapi.yamlexists atgateway/openapi.yaml. The builder stage copies everything from the gateway/ directory into/app, making/app/openapi.yamlthe correct source path for the COPY instruction. The file will be found and copied successfully.Likely an incorrect or invalid review comment.
|
@greptile review the pr new changes |
There was a problem hiding this comment.
Additional Comments (3)
-
gateway/main.go, line 58 (link)style: Loading Swagger UI from unpkg.com CDN creates a dependency on external infrastructure and poses security risks (CDN compromise, availability). Consider self-hosting Swagger UI assets or using subresource integrity (SRI) hashes.
-
gateway/openapi_test.go, line 17-26 (link)style: Test uses basic string matching which could pass even if the YAML structure is invalid. Consider using a proper OpenAPI parser to validate schema structure and completeness.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
-
gateway/main.go, line 51-72 (link)style: Swagger UI endpoint serves documentation without authentication or rate limiting. Consider restricting access or adding authentication to prevent abuse in production environments.
5 files reviewed, 3 comments
|
Hi @AnkanMisra
|
AnkanMisra
left a comment
There was a problem hiding this comment.
LGTM
Thanks for the contribution 🙏 !!
|
Thank you! 🙏 |
closes #20
Add OpenAPI 3.1 specification and Swagger UI
This PR introduces a complete OpenAPI 3.1 specification for the MicroAI Paygate Gateway and serves an interactive Swagger UI for easier API exploration.
What’s included
openapi.yaml) documenting all public and internal endpoints/docs/openapi.yaml/healthz,/api/ai/summarize, and/verifyX-402-Signature,X-402-Nonce)This improves developer onboarding, enables interactive API testing, and allows future SDK generation while keeping documentation in sync with the implementation.
Summary by CodeRabbit
New Features
Documentation
Tests
Chores
✏️ Tip: You can customize this high-level summary in your review settings.
Greptile Summary
This PR successfully adds OpenAPI 3.1 documentation and Swagger UI to the MicroAI Paygate Gateway, making the API more discoverable and testable.
Key changes:
openapi.yamlspec documenting/healthzand/api/ai/summarizeendpoints with x402 payment headers/docsusing CDN-hosted assets/openapi.yamlfor SDK generation and toolingRecommendations:
/docsendpoint in production environmentsConfidence Score: 4/5
gateway/openapi_test.gocould benefit from more robust validation, andgateway/main.goSwagger UI serving should consider production securityImportant Files Changed
/healthzand/api/ai/summarizewith x402 payment headers and all response codes/docsand static OpenAPI spec serving at/openapi.yamlusing inline HTML with CDN resourcesopenapi.yamlcopy step to runtime image for serving the spec fileSequence Diagram
sequenceDiagram participant Dev as Developer participant GW as Gateway participant Swagger as Swagger UI participant Spec as openapi.yaml Dev->>GW: GET /docs GW-->>Dev: HTML with Swagger UI (from CDN) Dev->>Swagger: Load Swagger UI Swagger->>GW: GET /openapi.yaml GW->>Spec: Read openapi.yaml Spec-->>GW: YAML content GW-->>Swagger: OpenAPI 3.1 spec Swagger-->>Dev: Interactive API documentation Note over Dev,Swagger: Developer explores API Dev->>Swagger: Try POST /api/ai/summarize Swagger->>GW: POST /api/ai/summarize Note over GW: x402 payment validation GW-->>Swagger: Response (200/402/403/500) Swagger-->>Dev: Display result