-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathpat_scope.go
More file actions
54 lines (45 loc) · 1.71 KB
/
pat_scope.go
File metadata and controls
54 lines (45 loc) · 1.71 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
package middleware
import (
"log/slog"
"net/http"
ghcontext "github.com/github/github-mcp-server/pkg/context"
"github.com/github/github-mcp-server/pkg/scopes"
"github.com/github/github-mcp-server/pkg/utils"
)
// WithPATScopes is a middleware that fetches and stores scopes for classic Personal Access Tokens (PATs) in the request context.
func WithPATScopes(logger *slog.Logger, scopeFetcher scopes.FetcherInterface) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
tokenInfo, ok := ghcontext.GetTokenInfo(ctx)
if !ok || tokenInfo == nil {
logger.Warn("no token info found in context")
next.ServeHTTP(w, r)
return
}
// Fetch token scopes for scope-based tool filtering (PAT tokens only)
// Only classic PATs (ghp_ prefix) return OAuth scopes via X-OAuth-Scopes header.
// Fine-grained PATs and other token types don't support this, so we skip filtering.
if tokenInfo.TokenType == utils.TokenTypePersonalAccessToken {
existingScopes, ok := ghcontext.GetTokenScopesForToken(ctx, tokenInfo.Token)
if ok {
logger.Debug("using existing scopes from context", "scopes", existingScopes)
next.ServeHTTP(w, r)
return
}
scopesList, err := scopeFetcher.FetchTokenScopes(ctx, tokenInfo.Token)
if err != nil {
logger.Warn("failed to fetch PAT scopes", "error", err)
next.ServeHTTP(w, r)
return
}
// Store fetched scopes in context for downstream use
ctx = ghcontext.WithTokenScopesForToken(ctx, tokenInfo.Token, scopesList)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
next.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}
}