Skip to content

Conversation

tuannvm
Copy link
Owner

@tuannvm tuannvm commented Jul 16, 2025

Summary

This PR introduces a robust OAuth token validation system supporting both HMAC and OIDC JWT tokens, along with a revamped HTTP server that handles MCP requests with proper CORS headers, graceful shutdown, and optional HTTPS support. Additionally, server initialization now includes OAuth hooks for request authentication, enhancing security and compliance.

Affected Modules

  • internal/oauth/providers.go: Implements HMACValidator and OIDCValidator for token validation.
  • internal/server/http.go: New file defining HTTP server with request handling, CORS, and signal handling.
  • Server setup functions: integration of OAuth hooks, server startup, and transport configuration.

Key Details

  • OAuth Validation:
    • Supports HMAC secret-based verification (HMACValidator).
    • Supports OIDC/JWKS verification with automatic key rotation (OIDCValidator).
    • Initialization routines ensure proper configuration and validation.
  • HTTP Server:
    • Handles /mcp and /sse endpoints with shared handlers.
    • Incorporates CORS headers for cross-origin requests.
    • Supports HTTPS if certificate files are specified via environment variables.
    • Includes graceful shutdown with timeout management.
  • Server Initialization:
    • Adds request hooks for OAuth authentication if enabled.
    • Responds with server status info.
    • Handles signals for safe termination.

Potential Impacts

  • Security:
    • OAuth JWT tokens validated securely via standard protocols.
    • Optional HTTPS ensures data confidentiality in production.
  • Performance:
    • Token validation overhead deemed minimal and necessary for security.
  • Compatibility:
    • Backward compatibility maintained via /sse endpoint.
    • CORS headers allow broad client access; adjust as needed for security policies.
  • Deployment:
    • TLS certificate paths must be configured via environment variables.
    • OAuth feature toggle controlled through configuration.

Testing Steps

  • Functional Testing:
    • Verify token validation with both HMAC secrets and OIDC tokens.
    • Test /mcp and /sse endpoints with correct and invalid tokens.
    • Confirm CORS headers allow expected origins.
  • Security Testing:
    • Attempt unauthorized requests to ensure proper rejection.
    • Test HTTPS endpoint with valid TLS credentials.
  • Operational Testing:
    • Initiate server startup with OAuth enabled/disabled.
    • Trigger shutdown signals and verify graceful termination within 30 seconds.
    • Confirm server logs reflect OAuth status and token validation outcomes.

This PR enhances the MCP server by integrating flexible OAuth support and robust HTTP handling, aligning with secure, scalable deployment practices.

Summary by CodeRabbit

  • New Features

    • Introduced comprehensive OAuth 2.0 resource server support with multi-provider authentication (Okta, Google, Azure AD, and HMAC).
    • Added OAuth2 endpoints for authorization, token exchange, metadata discovery, and dynamic client registration.
    • Implemented PKCE support and enhanced security for OAuth flows.
    • Integrated OAuth middleware with Trino tool handlers for request authentication.
    • Provided backward compatibility for existing JWT secret-based authentication.
  • Improvements

    • Simplified server setup and unified MCP server interface for HTTP and STDIO transports.
    • Enhanced configuration with multi-provider OAuth and OIDC settings.
    • Updated documentation with streamlined OAuth architecture, deployment scenarios, and usage instructions.
    • Added token caching and improved logging for authentication processes.
  • Bug Fixes

    • Improved error handling and warnings for OAuth configuration and token validation.
  • Chores

    • Removed deprecated OAuth implementation files and replaced with new modular OAuth packages.
    • Updated dependencies to include OAuth and OIDC libraries.

tuannvm added 10 commits July 16, 2025 15:05
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
…iles

Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Copy link

coderabbitai bot commented Jul 16, 2025

Warning

Rate limit exceeded

@tuannvm has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 29 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 827ccb7 and 7e37316.

📒 Files selected for processing (3)
  • internal/mcp/server.go (1 hunks)
  • internal/oauth/handlers.go (1 hunks)
  • internal/oauth/middleware.go (1 hunks)

Walkthrough

This update refactors the MCP server initialization and HTTP handling to a new consolidated internal/mcp package with integrated OAuth 2.0 support including multiple providers (HMAC, OIDC). It removes previous OAuth middleware and HTTP server implementations, adds OAuth metadata and client registration endpoints, and updates documentation and configuration for multi-provider OAuth compliance and production readiness.

Changes

Files / Groups Change Summary
cmd/main.go Updated MCP server import path and usage to new internal/mcp package; simplified server start calls for STDIO and HTTP.
docs/oauth.md Rewritten to provide a high-level OAuth 2.0 architecture overview, supported modes, configuration, deployment, and compliance details.
go.mod Added github.com/coreos/go-oidc/v3 and golang.org/x/oauth2 dependencies; upgraded mcp-go and added indirect dependency.
internal/auth/oauth.go
internal/server/http.go
Deleted legacy OAuth middleware and HTTP server implementation files.
internal/config/config.go Extended TrinoConfig with OAuth provider and OIDC configuration fields; enhanced environment variable loading and logging.
internal/mcp/handlers.go Modified tool registration to wrap handlers conditionally with OAuth middleware from MCP server if present.
internal/mcp/server.go New consolidated MCP server implementation with integrated OAuth2 support, HTTP and STDIO transports, OAuth metadata endpoints, and graceful shutdown.
internal/oauth/config.go New OAuth setup logic creating token validators based on provider and OAuth2 handler creation.
internal/oauth/handlers.go New OAuth2 HTTP handlers for authorization, callback, and token exchange with PKCE and redirect URI proxy support.
internal/oauth/metadata.go New OAuth 2.0 metadata and client registration HTTP handlers implementing legacy and RFC-compliant endpoints.
internal/oauth/middleware.go New OAuth middleware for MCP tools with token caching, claim validation, and context helpers.
internal/oauth/providers.go New token validator implementations for HMAC and OIDC JWT validation conforming to the TokenValidator interface.
README.md Updated architecture and OAuth/JWT authentication sections reflecting new OAuth 2.0 support and configuration.
docs/jwt.md Revised JWT authentication documentation focusing on server-level JWT validation and transport endpoints.
docs/oauth-config.md Deleted detailed OAuth configuration guide replaced by streamlined OAuth overview in docs/oauth.md.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant HTTPServer
    participant OAuth2Handler
    participant TokenValidator
    participant TrinoMCPServer

    Client->>HTTPServer: Request (with Bearer token)
    HTTPServer->>TokenValidator: ValidateToken(token)
    TokenValidator-->>HTTPServer: User info or error
    alt Valid token
        HTTPServer->>TrinoMCPServer: Handle MCP request (with user context)
        TrinoMCPServer-->>HTTPServer: Response
        HTTPServer-->>Client: Response
    else Invalid token
        HTTPServer-->>Client: 401 Unauthorized + OAuth metadata
    end
Loading
sequenceDiagram
    participant Client
    participant HTTPServer
    participant OAuth2Handler
    participant OIDCProvider

    Client->>HTTPServer: GET /oauth/authorize
    HTTPServer->>OAuth2Handler: HandleAuthorize
    OAuth2Handler-->>Client: Redirect to OIDCProvider

    Client->>OIDCProvider: Authorize (login)
    OIDCProvider-->>Client: Redirect (code)
    Client->>HTTPServer: GET /oauth/callback?code=...
    HTTPServer->>OAuth2Handler: HandleCallback
    OAuth2Handler->>OIDCProvider: Exchange code for token
    OIDCProvider-->>OAuth2Handler: Token(s)
    OAuth2Handler-->>Client: Success page or proxy redirect
Loading

Possibly related PRs

  • Feat/oauth support #61: Introduced initial OAuth 2.1 JWT authentication middleware and HTTP server integration; this PR replaces and extends that approach with a new consolidated OAuth 2.0 implementation and server refactor.

Suggested labels

released

Poem

🐇✨
A hop, a leap, a bounding feat—
OAuth is here, secure and neat!
From HMAC to OIDC,
Providers join the rabbit spree.
Metadata endpoints multiply,
And tokens now can truly fly—
The MCP hops on, oh my!
✨🐇

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 15

🔭 Outside diff range comments (1)
docs/oauth.md (1)

30-38: Wrong well-known endpoint path

RFC 8414 specifies /.well-known/oauth-authorization-server (or /.well-known/openid-configuration) for AS metadata.
The bullet at line 36 introduces a non-standard /.well-known/oauth-metadata path that clients are unlikely to recognise.

- - **OAuth Metadata Endpoint**: `/.well-known/oauth-metadata` endpoint for MCP client discovery
+ - **OAuth Metadata Endpoint**: `/.well-known/oauth-authorization-server` endpoint for MCP client discovery
🧹 Nitpick comments (8)
internal/config/config.go (1)

28-36: Consider using structured types for OAuth providers

The OAuth provider is stored as a string and validated through string comparison. Consider using an enum or constant set to ensure type safety and prevent invalid provider values.

+// OAuthProvider represents supported OAuth providers
+type OAuthProvider string
+
+const (
+    OAuthProviderHMAC   OAuthProvider = "hmac"
+    OAuthProviderOkta   OAuthProvider = "okta" 
+    OAuthProviderGoogle OAuthProvider = "google"
+    OAuthProviderAzure  OAuthProvider = "azure"
+)

 type TrinoConfig struct {
     // OAuth mode configuration
     OAuthEnabled      bool   // Enable OAuth 2.1 authentication
-    OAuthProvider     string // OAuth provider: "hmac", "okta", "google", "azure"
+    OAuthProvider     OAuthProvider // OAuth provider type
     JWTSecret         string // JWT signing secret for HMAC provider
internal/oauth/middleware.go (1)

156-184: Deprecate or remove unused JWT validation code

The validateTokenClaims function is marked as deprecated but still present. If provider-based validation is the intended approach, this code should be removed to avoid confusion and reduce maintenance burden.

Consider removing this entire function if it's truly deprecated and not used anywhere in the codebase.

internal/oauth/metadata.go (1)

186-187: Security: Avoid exposing empty client secret

Even though the comment indicates it's a public client, explicitly setting an empty string for client_secret in the response could be confusing. Consider omitting the field entirely for public clients.

 response := map[string]interface{}{
     "client_id":                h.config.ClientID,
-    "client_secret":            "", // Public client, no secret  
     "client_id_issued_at":      time.Now().Unix(),
internal/oauth/handlers.go (1)

71-74: HTTPS detection logic is incomplete

The scheme detection only checks for certificate files but doesn't consider other HTTPS configurations like reverse proxies or environment-specific settings.

 // Determine scheme based on HTTPS configuration
 scheme := "http"
 if getEnv("HTTPS_CERT_FILE", "") != "" && getEnv("HTTPS_KEY_FILE", "") != "" {
     scheme = "https"
 }
+// Also check for common HTTPS indicators
+if getEnv("HTTPS", "") == "true" || getEnv("TLS", "") == "true" {
+    scheme = "https"
+}
docs/oauth.md (4)

309-317: Trailing colon in heading trips Markdown-lint

markdownlint flags MD026 here. Drop the trailing : to avoid a lint error and improve heading readability.

-### 2. Bearer Token Validation (`internal/mcp/oauth.go`):
+### 2. Bearer Token Validation (`internal/mcp/oauth.go`)

326-333: Same colon / MD026 issue for heading 4

-### 4. HTTP Authentication Implementation (`internal/mcp/oauth.go`):
+### 4. HTTP Authentication Implementation (`internal/mcp/oauth.go`)

Also consider collapsing the six single-sentence bullets into one paragraph to reduce vertical bloat.


705-766: Function names missing from surrounding package

applyOAuthMiddleware calls setOAuthMiddleware, which is not declared in the snippet or earlier listings. Either rename to the exported setter that actually exists in mcp-go, or show its definition to avoid confusion for readers following the guide.


894-978: Hard-coded version string

"mcp_version": "1.0.0" and "server_version": "%s" are baked into the example.
Consider replacing the literal with a const or param in real code snippets so readers don’t copy stale versions.

-           "mcp_version": "1.0.0",
+           "mcp_version": mcp.Version,
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b85b122 and b7a7de1.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (13)
  • cmd/main.go (2 hunks)
  • docs/oauth.md (7 hunks)
  • go.mod (1 hunks)
  • internal/auth/oauth.go (0 hunks)
  • internal/config/config.go (4 hunks)
  • internal/mcp/handlers.go (2 hunks)
  • internal/mcp/server.go (1 hunks)
  • internal/oauth/config.go (1 hunks)
  • internal/oauth/handlers.go (1 hunks)
  • internal/oauth/metadata.go (1 hunks)
  • internal/oauth/middleware.go (1 hunks)
  • internal/oauth/providers.go (1 hunks)
  • internal/server/http.go (0 hunks)
💤 Files with no reviewable changes (2)
  • internal/auth/oauth.go
  • internal/server/http.go
🧰 Additional context used
📓 Path-based instructions (2)
internal/config/config.go

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • CLAUDE.md
cmd/main.go

Instructions used from:

Sources:
📄 CodeRabbit Inference Engine

  • CLAUDE.md
🧠 Learnings (12)
📓 Common learnings
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
go.mod (6)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to .github/workflows/build.yml : Go mod tidy verification must be performed in the CI pipeline.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to examples/test_query.go : The file `examples/test_query.go` should be used for HTTP API manual testing.
internal/mcp/handlers.go (2)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
internal/oauth/config.go (2)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
internal/oauth/providers.go (1)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
internal/config/config.go (6)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Invalid timeout values for `TRINO_QUERY_TIMEOUT` must fall back to 30 seconds with a warning in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : HTTPS scheme must force SSL=true regardless of the `TRINO_SSL` setting in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to internal/trino/client.go : Connection pool settings should be: 10 max open, 5 max idle, 5min max lifetime for Trino client connections.
cmd/main.go (6)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to cmd/main.go : Main entry point for the server should be implemented in `cmd/main.go` with server initialization, Trino connection testing, transport selection (STDIO vs HTTP with SSE), graceful shutdown, and CORS support.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
internal/oauth/metadata.go (2)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
internal/oauth/handlers.go (5)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to examples/test_query.go : The file `examples/test_query.go` should be used for HTTP API manual testing.
internal/oauth/middleware.go (2)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
internal/mcp/server.go (6)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to cmd/main.go : Main entry point for the server should be implemented in `cmd/main.go` with server initialization, Trino connection testing, transport selection (STDIO vs HTTP with SSE), graceful shutdown, and CORS support.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
docs/oauth.md (5)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to examples/test_query.go : The file `examples/test_query.go` should be used for HTTP API manual testing.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
🧬 Code Graph Analysis (5)
internal/mcp/handlers.go (1)
internal/mcp/server.go (1)
  • GetOAuthMiddleware (395-397)
internal/oauth/providers.go (2)
internal/oauth/middleware.go (1)
  • User (146-150)
internal/config/config.go (1)
  • TrinoConfig (12-37)
cmd/main.go (1)
internal/mcp/server.go (2)
  • NewServer (30-46)
  • ServeStdio (340-342)
internal/oauth/handlers.go (2)
cmd/main.go (1)
  • Version (16-16)
internal/config/config.go (1)
  • TrinoConfig (12-37)
internal/oauth/middleware.go (1)
internal/oauth/providers.go (1)
  • TokenValidator (18-21)
🪛 markdownlint-cli2 (0.17.2)
docs/oauth.md

1044-1044: Unordered list indentation
Expected: 0; Actual: 3

(MD007, ul-indent)


1045-1045: Unordered list indentation
Expected: 0; Actual: 3

(MD007, ul-indent)


1046-1046: Unordered list indentation
Expected: 0; Actual: 3

(MD007, ul-indent)


1047-1047: Unordered list indentation
Expected: 0; Actual: 3

(MD007, ul-indent)


1048-1048: Unordered list indentation
Expected: 0; Actual: 3

(MD007, ul-indent)


1049-1049: Unordered list indentation
Expected: 0; Actual: 3

(MD007, ul-indent)


1050-1050: Unordered list indentation
Expected: 0; Actual: 3

(MD007, ul-indent)


1233-1233: Emphasis used instead of a heading

(MD036, no-emphasis-as-heading)


1235-1235: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)


1248-1248: Trailing punctuation in heading
Punctuation: ':'

(MD026, no-trailing-punctuation)

🔇 Additional comments (7)
go.mod (2)

6-10: ✅ Dependency Security Check Passed

I’ve verified the OAuth/OIDC dependencies against GitHub’s Security Advisories:

  • github.com/coreos/go-oidc/v3 v3.14.1 – no known vulnerabilities
  • golang.org/x/oauth2 v0.30.0 – no known vulnerabilities

These versions are safe to use.


3-3: go.mod: Go version 1.24.2 is valid

  • go.mod (line 3): go 1.24.2 is an existing patch release in the 1.24.x series.
  • The latest patch release is 1.24.5 (July 8, 2025). You may bump to 1.24.5 if you want the newest security and bug fixes.

Likely an incorrect or invalid review comment.

cmd/main.go (1)

9-9: Refactoring Approved: OAuth Initialization Confirmed

The move to internal/mcp and the simplified NewServer signature cleanly consolidates server setup. We’ve verified that:

  • NewServer creates an oauthHandler only when trinoConfig.OAuthEnabled is true.
  • createMCPServer conditionally registers all OAuth endpoints on the HTTP mux (RFC 8414, RFC 9728, legacy metadata, /oauth/*, and /callback) when OAuth is enabled.

No further changes required.

internal/mcp/handlers.go (1)

199-237: Well-implemented OAuth middleware integration

The conditional application of OAuth middleware to all Trino tool handlers is implemented correctly. The approach maintains backward compatibility when OAuth is disabled while ensuring all tools are protected when enabled. The use of a helper function applyMiddleware makes the code clean and maintainable.

internal/oauth/providers.go (2)

94-136: Excellent OIDC security implementation

The OIDC validator implementation follows security best practices:

  • Enforces TLS 1.2 minimum version
  • Enables all security verification checks (audience, expiry, issuer)
  • Uses appropriate timeouts for HTTP operations
  • Properly configures connection pooling

76-84: Helper functions verified and no action needed

Both validateTokenClaims and getStringClaim are implemented in internal/oauth/middleware.go (lines 155–184 and 188–193). No further changes are required here.

docs/oauth.md (1)

584-626: Undefined helper referenced in snippet

The sample OAuthMiddleware refers to an external GetOAuthToken(ctx) helper, but that helper is neither shown nor described anywhere in the doc. Readers cannot reproduce the code as-is.

Add a short stub or at least a one-liner describing the expected behaviour / signature of GetOAuthToken so copy-paste compilation succeeds.

Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (6)
README.md (2)

93-95: Feature bullet mixes JWT wording with new OAuth scope

StreamableHTTP support with JWT authentication (upgraded from SSE) reads as if JWT-only auth is available, yet the PR introduces full OAuth/OIDC with JWT validation. Recommend clarifying the bullet, e.g.:

- ✅ StreamableHTTP support with JWT authentication (upgraded from SSE)
+ ✅ StreamableHTTP support with OAuth 2.0 / JWT bearer authentication (replaces legacy SSE)

876-884: Missing defaults & required flags for new OAuth variables

The env-var table omits default values or “required” markers for OAUTH_PROVIDER, OIDC_ISSUER, OIDC_AUDIENCE, and OIDC_CLIENT_ID. Omitting these can trip up users. Suggest marking them as “(required when TRINO_OAUTH_ENABLED=true)” and adding defaults where applicable.

docs/jwt.md (2)

63-71: Variable naming still references OAuth, may confuse readers

Using TRINO_OAUTH_ENABLED to switch on pure HMAC-JWT auth feels counter-intuitive after the OAuth split. Consider an alias or note, e.g. “TRINO_OAUTH_ENABLED (also controls standalone JWT mode)”.


140-143: Fenced code block is missing a language identifier (MD040)

Markdown-lint flags this; add bash, json, or another appropriate tag to keep CI green.

-```json
+```json
docs/oauth.md (2)

11-24: Add language tag to ASCII diagram to satisfy markdown-lint

CI raises MD040; simply mark the block as plain text:

-```
+```text
┌─────────────────┐ ...

66-68: Typo: “backward compati…”

Small grammar issue flagged by LanguageTool: “backward compatibility” is missing the full word.

- with backward compati...
+ with backward compatibility...
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b7a7de1 and 22c8609.

📒 Files selected for processing (4)
  • README.md (5 hunks)
  • docs/jwt.md (3 hunks)
  • docs/oauth-config.md (0 hunks)
  • docs/oauth.md (1 hunks)
💤 Files with no reviewable changes (1)
  • docs/oauth-config.md
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
docs/jwt.md (5)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to cmd/main.go : Main entry point for the server should be implemented in `cmd/main.go` with server initialization, Trino connection testing, transport selection (STDIO vs HTTP with SSE), graceful shutdown, and CORS support.
README.md (7)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to cmd/main.go : Main entry point for the server should be implemented in `cmd/main.go` with server initialization, Trino connection testing, transport selection (STDIO vs HTTP with SSE), graceful shutdown, and CORS support.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : HTTPS scheme must force SSL=true regardless of the `TRINO_SSL` setting in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to internal/trino/client.go : Connection pool settings should be: 10 max open, 5 max idle, 5min max lifetime for Trino client connections.
docs/oauth.md (7)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to examples/test_query.go : The file `examples/test_query.go` should be used for HTTP API manual testing.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to cmd/main.go : Main entry point for the server should be implemented in `cmd/main.go` with server initialization, Trino connection testing, transport selection (STDIO vs HTTP with SSE), graceful shutdown, and CORS support.
🪛 LanguageTool
docs/oauth.md

[grammar] ~66-~66: Ensure spelling is correct
Context: ...and other clients - HTTP Transport: StreamableHTTP endpoint (/mcp) with backward compati...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)

🪛 markdownlint-cli2 (0.17.2)
docs/oauth.md

11-11: Fenced code blocks should have a language specified

(MD040, fenced-code-language)

⏰ 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: Build Verification
🔇 Additional comments (3)
README.md (1)

40-44: “OAuth Middleware” label is misleading given the new server-level auth-hook architecture

The diagram still shows a dedicated OAuth Middleware node, but the codebase moved validation into a server-level hook (no separate middleware layer). Updating the label to “Auth Hook (JWT/OIDC)” or similar would avoid confusion for future readers.

docs/jwt.md (1)

55-58: Claims list incomplete vs. flow diagram

The security section lists required claims (sub, exp, iat) but the flow diagram and examples reference preferred_username and email as well. Please reconcile the two sections so tooling and auditors have a single source of truth.

docs/oauth.md (1)

52-57: Confirm PKCE support is truly implemented

Doc advertises “Full OAuth 2.1 PKCE implementation”, but I can’t find PKCE verifier/challenge handling in internal/oauth/*. If that work is planned but not merged, please tone down the claim or link to the code.

tuannvm added 2 commits July 17, 2025 08:57
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
@tuannvm
Copy link
Owner Author

tuannvm commented Jul 17, 2025

@claude review PR

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

♻️ Duplicate comments (8)
internal/oauth/metadata.go (3)

17-20: Duplicate HTTP status setting causes malformed response

The code calls both WriteHeader and http.Error which sets the status twice, resulting in a malformed response.

Apply this fix:

 if r.Method != "GET" {
-    w.WriteHeader(http.StatusMethodNotAllowed)
     http.Error(w, `{"error":"Method not allowed"}`, http.StatusMethodNotAllowed)
     return
 }

80-83: Duplicate HTTP status setting causes malformed response

Same issue as in HandleMetadata - calling both WriteHeader and http.Error causes duplicate status setting.

Apply this fix:

 if r.Method != "GET" {
-    w.WriteHeader(http.StatusMethodNotAllowed)
     http.Error(w, `{"error":"Method not allowed"}`, http.StatusMethodNotAllowed)
     return
 }

115-118: Duplicate HTTP status setting causes malformed response

Same pattern repeated again - calling both WriteHeader and http.Error.

Apply this fix:

 if r.Method != "GET" {
-    w.WriteHeader(http.StatusMethodNotAllowed)
     http.Error(w, `{"error":"Method not allowed"}`, http.StatusMethodNotAllowed)
     return
 }
internal/mcp/server.go (3)

363-377: Global mutable state lacks thread safety

The global map serverMiddleware is accessed without synchronization, creating potential race conditions in concurrent environments.

Add proper synchronization:

+import "sync"
+
 // Middleware storage for the MCP server
-var serverMiddleware map[*mcpserver.MCPServer]func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc
+var (
+    serverMiddleware = make(map[*mcpserver.MCPServer]func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc)
+    serverMiddlewareMu sync.RWMutex
+)

-func init() {
-    serverMiddleware = make(map[*mcpserver.MCPServer]func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc)
-}

 // setOAuthMiddleware stores the OAuth middleware for a server
 func setOAuthMiddleware(mcpServer *mcpserver.MCPServer, middleware func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc) {
+    serverMiddlewareMu.Lock()
+    defer serverMiddlewareMu.Unlock()
     serverMiddleware[mcpServer] = middleware
 }

 // GetOAuthMiddleware retrieves the OAuth middleware for a server
 func GetOAuthMiddleware(mcpServer *mcpserver.MCPServer) func(mcpserver.ToolHandlerFunc) mcpserver.ToolHandlerFunc {
+    serverMiddlewareMu.RLock()
+    defer serverMiddlewareMu.RUnlock()
     return serverMiddleware[mcpServer]
 }

253-256: Hardcoded scheme should use server configuration

The OAuth discovery response URLs hardcode the scheme instead of using the server's actual scheme configuration, which could cause issues in development environments.

Use the dynamic scheme:

 "oauth": map[string]interface{}{
-    "issuer":                                 fmt.Sprintf("https://%s:%s", mcpHost, mcpPort),
-    "authorization_endpoint":                 fmt.Sprintf("https://%s:%s/oauth/authorize", mcpHost, mcpPort),
-    "token_endpoint":                        fmt.Sprintf("https://%s:%s/oauth/token", mcpHost, mcpPort),
-    "registration_endpoint":                 fmt.Sprintf("https://%s:%s/oauth/register", mcpHost, mcpPort),
+    "issuer":                                 fmt.Sprintf("%s://%s:%s", s.getScheme(), mcpHost, mcpPort),
+    "authorization_endpoint":                 fmt.Sprintf("%s://%s:%s/oauth/authorize", s.getScheme(), mcpHost, mcpPort),
+    "token_endpoint":                        fmt.Sprintf("%s://%s:%s/oauth/token", s.getScheme(), mcpHost, mcpPort),
+    "registration_endpoint":                 fmt.Sprintf("%s://%s:%s/oauth/register", s.getScheme(), mcpHost, mcpPort),

238-240: Hardcoded HTTPS scheme in WWW-Authenticate header

The WWW-Authenticate header always uses HTTPS scheme regardless of the actual server configuration.

Use the dynamic scheme:

 w.Header().Set("WWW-Authenticate", fmt.Sprintf(`Bearer realm="%s", authorization_uri="%s/.well-known/oauth-authorization-server"`, 
     mcpHost, 
-    fmt.Sprintf("https://%s:%s", mcpHost, mcpPort)))
+    fmt.Sprintf("%s://%s:%s", s.getScheme(), mcpHost, mcpPort)))
internal/oauth/handlers.go (2)

53-55: Hardcoded OAuth2 endpoints break provider compatibility

The authorization and token URLs are hardcoded with /oauth2/v1/ paths which will not work for providers with different endpoint structures.

Since you already use OIDC discovery in internal/oauth/providers.go, extract the endpoints from the discovered provider:

-Endpoint: oauth2.Endpoint{
-    AuthURL:  cfg.Issuer + "/oauth2/v1/authorize",
-    TokenURL: cfg.Issuer + "/oauth2/v1/token",
-},
+// Use endpoints discovered via OIDC
+Endpoint: provider.Endpoint(),

139-140: Security vulnerability in state parameter encoding

Using pipe character as delimiter is vulnerable if the state or redirect URI contains this character.

Use a more robust encoding scheme:

 // If using fixed redirect URI, encode original client URI in state
 if h.config.RedirectURI != "" {
-    encodedState := fmt.Sprintf("%s|%s", state, clientRedirectURI)
+    // Encode state and redirect URI safely
+    stateData := map[string]string{"state": state, "redirect": clientRedirectURI}
+    jsonData, _ := json.Marshal(stateData)
+    encodedState := base64.URLEncoding.EncodeToString(jsonData)
     query.Set("state", encodedState)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 22c8609 and 0423fed.

📒 Files selected for processing (6)
  • cmd/main.go (3 hunks)
  • internal/config/config.go (4 hunks)
  • internal/mcp/server.go (1 hunks)
  • internal/oauth/config.go (1 hunks)
  • internal/oauth/handlers.go (1 hunks)
  • internal/oauth/metadata.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/oauth/config.go
  • internal/config/config.go
  • cmd/main.go
🧰 Additional context used
🧠 Learnings (4)
📓 Common learnings
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
internal/oauth/metadata.go (4)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to examples/test_query.go : The file `examples/test_query.go` should be used for HTTP API manual testing.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
internal/oauth/handlers.go (5)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to examples/test_query.go : The file `examples/test_query.go` should be used for HTTP API manual testing.
internal/mcp/server.go (7)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to cmd/main.go : Main entry point for the server should be implemented in `cmd/main.go` with server initialization, Trino connection testing, transport selection (STDIO vs HTTP with SSE), graceful shutdown, and CORS support.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : HTTPS scheme must force SSL=true regardless of the `TRINO_SSL` setting in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
🧬 Code Graph Analysis (2)
internal/oauth/metadata.go (2)
internal/oauth/handlers.go (1)
  • OAuth2Handler (21-24)
cmd/main.go (1)
  • Version (16-16)
internal/oauth/handlers.go (2)
cmd/main.go (1)
  • Version (16-16)
internal/config/config.go (1)
  • TrinoConfig (13-38)
🪛 GitHub Check: Code Quality
internal/oauth/handlers.go

[failure] 345-345:
Error return value of req.Body.Close is not checked (errcheck)

🪛 GitHub Actions: Build & Verify Pipeline
internal/oauth/handlers.go

[error] 345-345: golangci-lint: Error return value of req.Body.Close is not checked (errcheck)

🔇 Additional comments (5)
internal/oauth/metadata.go (1)

53-64: Good refactoring of duplicate code

The code duplication issue for okta/google/azure providers has been properly addressed by consolidating them into a single case statement. This follows the DRY principle effectively.

internal/mcp/server.go (2)

29-46: Well-structured server initialization

The NewServer constructor properly initializes all components including conditional OAuth handler creation based on configuration. The separation of concerns is clear and the error handling is appropriate.


75-210: Robust HTTP server implementation with graceful shutdown

The ServeHTTP method implements comprehensive features including:

  • TLS support with environment-based configuration
  • Graceful shutdown with proper timeout handling
  • Clear endpoint logging for debugging
  • CORS support for cross-origin requests
internal/oauth/handlers.go (2)

91-150: Comprehensive OAuth2 authorization flow implementation

The HandleAuthorize method properly implements the OAuth2 authorization code flow with PKCE support, including parameter extraction, validation, and secure redirect handling.


201-306: Robust token exchange implementation

The HandleToken method correctly implements OAuth2 token exchange with PKCE support, proper validation, and comprehensive error handling. The custom transport for PKCE injection is a clever solution.

Comment on lines +162 to +187
response := map[string]interface{}{
"client_id": h.config.ClientID,
"client_secret": "", // Public client, no secret
"client_id_issued_at": time.Now().Unix(),
"grant_types": []string{"authorization_code", "refresh_token"},
"response_types": []string{"code"},
"token_endpoint_auth_method": "none",
"application_type": "native",
"client_name": regRequest["client_name"],
}

// Use fixed redirect URI if configured, otherwise use client's redirect URIs
if h.config.RedirectURI != "" {
response["redirect_uris"] = []string{h.config.RedirectURI}
log.Printf("OAuth2: Registration response using fixed redirect URI: %s", h.config.RedirectURI)
} else {
response["redirect_uris"] = regRequest["redirect_uris"]
}

w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Printf("OAuth2: Failed to encode registration response: %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider validating client registration request

The registration handler accepts any client registration without validation. Consider adding basic validation for required fields like client_name and redirect_uris to ensure compliance with OAuth 2.0 Dynamic Client Registration.

 // Parse the registration request
 var regRequest map[string]interface{}
 if err := json.NewDecoder(r.Body).Decode(&regRequest); err != nil {
     log.Printf("OAuth2: Failed to parse registration request: %v", err)
     http.Error(w, "Invalid request body", http.StatusBadRequest)
     return
 }

+// Validate required fields
+if _, ok := regRequest["client_name"]; !ok {
+    http.Error(w, "Missing required field: client_name", http.StatusBadRequest)
+    return
+}
+if _, ok := regRequest["redirect_uris"]; !ok {
+    http.Error(w, "Missing required field: redirect_uris", http.StatusBadRequest)
+    return
+}

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

🤖 Prompt for AI Agents
In internal/oauth/metadata.go around lines 162 to 187, the client registration
handler currently accepts all requests without validating required fields. Add
validation logic to check that essential fields like "client_name" and
"redirect_uris" are present and non-empty in the registration request. If
validation fails, respond with an appropriate HTTP error status and message to
enforce compliance with OAuth 2.0 Dynamic Client Registration requirements.

…e cache handling

Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

♻️ Duplicate comments (1)
internal/oauth/handlers.go (1)

53-56: Hardcoded OAuth2 endpoints may break with different providers

The authorization and token URLs are hardcoded with /oauth2/v1/ paths, which may not be compatible with all OIDC providers. Many providers use different endpoint paths.

Based on the past review comments, this issue was already identified. Consider using OIDC discovery to dynamically fetch the correct endpoints from the provider's well-known configuration instead of hardcoding these paths.

🧹 Nitpick comments (2)
internal/oauth/handlers.go (2)

68-76: HTTPS detection logic could be improved

The scheme detection based on environment variables is fragile and doesn't account for scenarios where HTTPS might be terminated by a load balancer or proxy.

Consider adding more robust HTTPS detection:

 // Determine scheme based on HTTPS configuration
 scheme := "http"
-if getEnv("HTTPS_CERT_FILE", "") != "" && getEnv("HTTPS_KEY_FILE", "") != "" {
+if getEnv("HTTPS_CERT_FILE", "") != "" && getEnv("HTTPS_KEY_FILE", "") != "" {
     scheme = "https"
+} else if getEnv("FORCE_HTTPS", "") == "true" || getEnv("TLS_TERMINATION", "") == "proxy" {
+    scheme = "https"
 }

395-397: PKCE code verifier handling could be more defensive

The code checks if code_verifier is empty before adding it, but doesn't validate if an existing value should be overwritten or if there are conflicts.

Consider adding more defensive handling:

 // Add code_verifier if not already present
-if values.Get("code_verifier") == "" && p.codeVerifier != "" {
+if p.codeVerifier != "" {
+    if existing := values.Get("code_verifier"); existing != "" && existing != p.codeVerifier {
+        log.Printf("Warning: Overwriting existing code_verifier in token request")
+    }
     values.Set("code_verifier", p.codeVerifier)
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 858c0c2 and 827ccb7.

📒 Files selected for processing (3)
  • internal/oauth/handlers.go (1 hunks)
  • internal/oauth/metadata.go (1 hunks)
  • internal/oauth/middleware.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/oauth/middleware.go
  • internal/oauth/metadata.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
internal/oauth/handlers.go (6)
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : MCP tool implementations with JSON response formatting, parameter validation, error handling, and consistent logging for debugging should be implemented in `internal/handlers/trino_handlers.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment-based configuration with validation, security defaults (HTTPS, read-only queries), and timeout configuration with validation should be implemented in `internal/config/config.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/trino/client.go : Database connection management, connection pooling, SQL injection protection via read-only query enforcement, and context-based timeout handling for queries should be implemented in `internal/trino/client.go`.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/handlers/trino_handlers.go : All MCP tools (`execute_query`, `list_catalogs`, `list_schemas`, `list_tables`, `get_table_schema`) must return JSON-formatted responses and handle parameter validation.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.734Z
Learning: Applies to internal/config/config.go : Environment variables such as `TRINO_HOST`, `TRINO_PORT`, `TRINO_USER`, `TRINO_PASSWORD`, `TRINO_SCHEME`, `TRINO_SSL`, `TRINO_SSL_INSECURE`, `TRINO_ALLOW_WRITE_QUERIES`, `TRINO_QUERY_TIMEOUT`, `MCP_TRANSPORT`, `MCP_PORT`, and `MCP_HOST` must be supported and validated in configuration logic.
Learnt from: CR
PR: tuannvm/mcp-trino#0
File: CLAUDE.md:0-0
Timestamp: 2025-07-01T05:50:01.735Z
Learning: Applies to examples/test_query.go : The file `examples/test_query.go` should be used for HTTP API manual testing.
🧬 Code Graph Analysis (1)
internal/oauth/handlers.go (2)
cmd/main.go (1)
  • Version (16-16)
internal/config/config.go (1)
  • TrinoConfig (13-38)
🔇 Additional comments (4)
internal/oauth/handlers.go (4)

140-154: Improved state parameter encoding implementation

The state parameter encoding has been improved to use JSON + base64 encoding instead of the previously vulnerable pipe-delimited format. This addresses the security concern raised in past reviews.

The implementation properly handles encoding errors and provides appropriate logging for debugging.


195-211: Secure state parameter decoding with proper error handling

The state parameter decoding correctly uses base64 + JSON decoding that matches the encoding implementation. The code properly handles decoding errors and validates the presence of required fields.

This implementation addresses the injection vulnerability that was identified in past reviews for the pipe-delimited format.


378-382: Proper resource cleanup with error handling

The request body closing has been properly implemented with defer and error checking, addressing the resource leak issue identified in past reviews.

The implementation correctly uses defer with a closure to handle the close error and provides appropriate logging.


109-110: Authorization code logging poses security risk

Similar to the token endpoint, logging the authorization code (even truncated) in the authorize endpoint could expose sensitive information in logs.

Apply the same logging security fix:

-log.Printf("OAuth2: Authorization request - client_id: %s, redirect_uri: %s, code_challenge: %s", 
-    clientID, clientRedirectURI, truncateString(codeChallenge, 10))
+log.Printf("OAuth2: Authorization request - client_id: %s, redirect_uri: %s, code_challenge: [REDACTED]", 
+    clientID, clientRedirectURI)

Likely an incorrect or invalid review comment.

Comment on lines +257 to +258
log.Printf("OAuth2: Token request - grant_type: %s, client_id: %s, redirect_uri: %s, code: %s",
grantType, clientID, clientRedirectURI, truncateString(code, 10))
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Potential information leakage in logging

The authorization code is being logged with truncation, but this could still pose a security risk in production environments where logs might be accessible to unauthorized parties.

Consider removing or further masking the authorization code in logs:

-log.Printf("OAuth2: Token request - grant_type: %s, client_id: %s, redirect_uri: %s, code: %s", 
-    grantType, clientID, clientRedirectURI, truncateString(code, 10))
+log.Printf("OAuth2: Token request - grant_type: %s, client_id: %s, redirect_uri: %s, code: [REDACTED]", 
+    grantType, clientID, clientRedirectURI)
📝 Committable suggestion

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

Suggested change
log.Printf("OAuth2: Token request - grant_type: %s, client_id: %s, redirect_uri: %s, code: %s",
grantType, clientID, clientRedirectURI, truncateString(code, 10))
log.Printf("OAuth2: Token request - grant_type: %s, client_id: %s, redirect_uri: %s, code: [REDACTED]",
grantType, clientID, clientRedirectURI)
🤖 Prompt for AI Agents
In internal/oauth/handlers.go around lines 257 to 258, the authorization code is
logged with partial truncation, which can still risk sensitive information
exposure. To fix this, remove the authorization code from the log statement
entirely or replace it with a fixed placeholder like "[REDACTED]" to prevent any
sensitive data from being written to logs.

Comment on lines +176 to +177
log.Printf("OAuth2: Callback received - code: %s, state: %s, error: %s",
truncateString(code, 10), state, errorParam)
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Authorization code logging in callback handler

The callback handler also logs the authorization code, which should be redacted for security.

-log.Printf("OAuth2: Callback received - code: %s, state: %s, error: %s", 
-    truncateString(code, 10), state, errorParam)
+log.Printf("OAuth2: Callback received - code: [REDACTED], state: %s, error: %s", 
+    state, errorParam)
📝 Committable suggestion

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

Suggested change
log.Printf("OAuth2: Callback received - code: %s, state: %s, error: %s",
truncateString(code, 10), state, errorParam)
log.Printf("OAuth2: Callback received - code: [REDACTED], state: %s, error: %s",
state, errorParam)
🤖 Prompt for AI Agents
In internal/oauth/handlers.go around lines 176 to 177, the authorization code is
logged in the callback handler, which poses a security risk. Modify the log
statement to redact or omit the authorization code instead of printing it
directly. You can replace the code with a fixed placeholder like "[REDACTED]" or
remove it entirely from the log message to prevent sensitive information
exposure.

Comment on lines +312 to +313
"expires_in": int(time.Until(token.Expiry).Seconds()),
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Token expiration calculation may return negative values

The expires_in calculation using time.Until(token.Expiry).Seconds() could return negative values if the token is already expired, which might confuse OAuth2 clients.

Add a check to ensure non-negative expiration times:

-"expires_in":   int(time.Until(token.Expiry).Seconds()),
+"expires_in":   int(max(0, time.Until(token.Expiry).Seconds())),

Or use a helper function:

+func max(a, b float64) float64 {
+    if a > b {
+        return a
+    }
+    return b
+}
📝 Committable suggestion

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

Suggested change
"expires_in": int(time.Until(token.Expiry).Seconds()),
}
"expires_in": int(max(0, time.Until(token.Expiry).Seconds())),
}
// max returns the larger of a and b.
func max(a, b float64) float64 {
if a > b {
return a
}
return b
}
🤖 Prompt for AI Agents
In internal/oauth/handlers.go around lines 312 to 313, the calculation for
"expires_in" using time.Until(token.Expiry).Seconds() can yield negative values
if the token is already expired. To fix this, add a check to ensure the
expiration time is never negative by using a conditional or helper function that
returns zero if the calculated duration is negative, otherwise returns the
actual seconds until expiry.

…ling

Signed-off-by: Tommy Nguyen <tuannvm@hotmail.com>
Repository owner deleted a comment from claude bot Jul 17, 2025
@tuannvm tuannvm merged commit be678b6 into main Jul 17, 2025
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant