forked from sigbit/mcp-auth-proxy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.go
More file actions
162 lines (146 loc) · 4.28 KB
/
proxy.go
File metadata and controls
162 lines (146 loc) · 4.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
package proxy
import (
"crypto/rsa"
"fmt"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v5"
"github.com/mattn/go-jsonpointer"
)
type ProxyRouter struct {
externalURL string
proxy http.Handler
publicKey *rsa.PublicKey
proxyHeaders http.Header
httpStreamingOnly bool
forwardAuthorizationHeader bool
headerMapping map[string]string
headerMappingBase string
}
func NewProxyRouter(
externalURL string,
proxy http.Handler,
publicKey *rsa.PublicKey,
proxyHeaders http.Header,
httpStreamingOnly bool,
forwardAuthorizationHeader bool,
headerMapping map[string]string,
headerMappingBase string,
) (*ProxyRouter, error) {
return &ProxyRouter{
externalURL: externalURL,
proxy: proxy,
publicKey: publicKey,
proxyHeaders: proxyHeaders,
httpStreamingOnly: httpStreamingOnly,
forwardAuthorizationHeader: forwardAuthorizationHeader,
headerMapping: headerMapping,
headerMappingBase: headerMappingBase,
}, nil
}
const (
OauthProtectedResourceEndpoint = "/.well-known/oauth-protected-resource"
)
func (p *ProxyRouter) SetupRoutes(router gin.IRouter) {
router.GET(OauthProtectedResourceEndpoint, p.handleProtectedResource)
router.Use(p.handleProxy)
}
type protectedResourceResponse struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers"`
}
func (p *ProxyRouter) handleProtectedResource(c *gin.Context) {
c.JSON(http.StatusOK, protectedResourceResponse{
Resource: p.externalURL,
AuthorizationServers: []string{p.externalURL},
})
}
func (p *ProxyRouter) handleProxy(c *gin.Context) {
authHeader := c.Request.Header.Get("Authorization")
if !strings.HasPrefix(authHeader, "Bearer ") {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
bearerToken := strings.TrimPrefix(authHeader, "Bearer ")
token, err := jwt.Parse(bearerToken, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return p.publicKey, nil
})
if err != nil || !token.Valid {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Invalid token"})
return
}
if p.httpStreamingOnly && isSSEGetRequest(c.Request) {
c.AbortWithStatusJSON(http.StatusMethodNotAllowed, gin.H{"error": "SSE (GET) streaming is not supported by this backend; use POST-based HTTP streaming instead"})
return
}
if !p.forwardAuthorizationHeader {
c.Request.Header.Del("Authorization")
}
for key, values := range p.proxyHeaders {
if strings.EqualFold(key, "Authorization") {
c.Request.Header.Del("Authorization")
}
for _, value := range values {
c.Request.Header.Add(key, value)
}
}
if len(p.headerMapping) > 0 {
if claims, ok := token.Claims.(jwt.MapClaims); ok {
var source any = map[string]any(claims)
if p.headerMappingBase != "/" {
val, err := jsonpointer.Get(source, p.headerMappingBase)
if err != nil {
source = nil
} else {
source = val
}
}
if source != nil {
for pointer, headerName := range p.headerMapping {
val, err := jsonpointer.Get(source, pointer)
if err != nil {
continue
}
switch v := val.(type) {
case string:
c.Request.Header.Set(headerName, v)
case []any:
var parts []string
for _, item := range v {
if s, ok := item.(string); ok {
parts = append(parts, s)
}
}
c.Request.Header.Set(headerName, strings.Join(parts, ","))
default:
c.Request.Header.Set(headerName, fmt.Sprintf("%v", v))
}
}
}
}
}
p.proxy.ServeHTTP(c.Writer, c.Request)
}
func isSSEGetRequest(r *http.Request) bool {
if r.Method != http.MethodGet {
return false
}
accept := r.Header.Get("Accept")
if accept == "" {
return false
}
for _, value := range strings.Split(accept, ",") {
mediaType := strings.TrimSpace(strings.ToLower(value))
if idx := strings.Index(mediaType, ";"); idx != -1 {
mediaType = strings.TrimSpace(mediaType[:idx])
}
if mediaType == "text/event-stream" {
return true
}
}
return false
}