forgejo-mcp/operation/user/user.go
Byte Flavour 4969ee5881
feat: robust stateless auth with security fixes and improved tests
This commit addresses the review feedback on PR #138:
- Fixed a privilege escalation vulnerability where failed ephemeral client
  creation would silently fall back to the global singleton token.
- Refactored forgejo.Client(ctx) to return (*forgejo.Client, error).
- Updated all 100+ tool handlers to properly handle client initialization errors.
- Improved token extraction to handle schemes (token/bearer) case-insensitively.
- Enhanced Unit Tests (pkg/forgejo/forgejo_test.go) to verify that different
  concurrent requests with different tokens correctly use their respective
  tokens in the Authorization header.
- Updated README and demos to reflect case-insensitivity support.
2026-05-24 13:44:48 +02:00

65 lines
1.8 KiB
Go

package user
import (
"context"
"fmt"
"time"
"codeberg.org/goern/forgejo-mcp/v2/pkg/forgejo"
"codeberg.org/goern/forgejo-mcp/v2/pkg/log"
"codeberg.org/goern/forgejo-mcp/v2/pkg/to"
"github.com/mark3labs/mcp-go/mcp"
"github.com/mark3labs/mcp-go/server"
)
const (
GetMyUserInfoToolName = "get_my_user_info"
)
var (
GetMyUserInfoTool = mcp.NewTool(
GetMyUserInfoToolName,
mcp.WithDescription("Get user info"),
)
)
func RegisterTool(s *server.MCPServer) {
s.AddTool(GetMyUserInfoTool, GetUserInfoFn)
s.AddTool(CheckNotificationsTool, CheckNotificationsFn)
s.AddTool(GetNotificationThreadTool, GetNotificationThreadFn)
s.AddTool(MarkNotificationReadTool, MarkNotificationReadFn)
s.AddTool(MarkAllNotificationsReadTool, MarkAllNotificationsReadFn)
s.AddTool(ListRepoNotificationsTool, ListRepoNotificationsFn)
s.AddTool(MarkRepoNotificationsReadTool, MarkRepoNotificationsReadFn)
}
func GetUserInfoFn(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
ctx, _ = log.WithMCPContext(ctx, GetMyUserInfoToolName)
start := time.Now()
log.LogMCPToolStart(ctx, GetMyUserInfoToolName, map[string]interface{}{})
client, err := forgejo.Client(ctx)
if err != nil {
return to.ErrorResult(err)
}
user, resp, err := client.GetMyUserInfo()
duration := time.Since(start)
// Log API call details — guard resp against nil (e.g. network error)
statusCode := 0
if resp != nil {
statusCode = resp.StatusCode
}
forgejo.LogAPICall(ctx, "GET", "/user", duration, statusCode, err)
if err != nil {
log.LogMCPToolError(ctx, GetMyUserInfoToolName, duration, err)
return to.ErrorResult(fmt.Errorf("get user info err: %v", err))
}
log.LogMCPToolComplete(ctx, GetMyUserInfoToolName, duration, fmt.Sprintf("Retrieved info for user: %s", user.UserName))
return to.TextResult(user)
}