diff --git a/README.md b/README.md index 432541f434..7e3c0a0d96 100644 --- a/README.md +++ b/README.md @@ -1699,6 +1699,35 @@ docker run -i --rm \ ghcr.io/github/github-mcp-server ``` +## Allowed Repositories + +When running locally (stdio), you can restrict the server to a fixed set of repositories with `--allowed-repos` or the `GITHUB_ALLOWED_REPOS` environment variable. This is useful when a token can see more than an agent should, for example a fine-grained token, which can always read public repositories. + +Each entry is `owner/repo`, or `owner/*` for every repository of an owner. The repository part also accepts wildcards such as `octo-org/svc-*`. Names are matched case-insensitively. + +```bash +./github-mcp-server stdio --allowed-repos=octo-org/*,octocat/hello-world +``` + +```bash +docker run -i --rm \ + -e GITHUB_PERSONAL_ACCESS_TOKEN= \ + -e GITHUB_ALLOWED_REPOS=octo-org/*,octocat/hello-world \ + ghcr.io/github/github-mcp-server +``` + +When an allowlist is set, every tool call, `repo://` resource read and resource completion is checked before any GitHub API request is made. The check fails closed: a call goes through only when every repository it can reach is known from its arguments and is in the list. + +- Calls with `owner` and `repo` must name an allowed repository. Secondary repositories named by other arguments (`parent_owner`/`parent_repo` on issue creation, `related_owner`/`related_repo` on issue dependencies, `item_owner`/`item_repo` on project items) are checked the same way. +- Calls scoped to a whole owner or organization (for example project tools or organization security advisories) need an `owner/*` entry. `list_notifications` and `mark_all_notifications_read` need both `owner` and `repo`, because without them they cover every repository. +- `create_repository` and `fork_repository` need an `organization` with an `owner/*` entry; the personal account cannot be checked. +- Rulesets and custom properties are checked at the selected `level`: `repository` needs `owner` and `repo`, `organization` needs `org` with an `org/*` entry, and `enterprise` is rejected. +- Search tools need a positive `repo:`, `org:` or `user:` qualifier in the query, and every such qualifier must be allowed. Negated qualifiers such as `-repo:` only narrow the results and are ignored; quoted qualifiers are free text and don't count as scope. Queries with `OR`, `NOT`, `AND` or parentheses are rejected, because a qualifier in one branch doesn't constrain the others. `search_issues` and `search_pull_requests` also accept `owner` and `repo` arguments, as long as the query has no `repo:` qualifier of its own. +- Tools that can't be tied to a repository are rejected: notification threads addressed by ID, project items (`list_project_items`, `get_project_item`, and item updates or deletions that don't name `item_owner`, `item_repo` and `issue_number`), and project views or status updates addressed by node ID. Tools that never return repository content (`get_me`, `get_teams`, `get_team_members`, `search_users`, `search_orgs`, global security advisories and gists) keep working, and so do the bundled `ui://` app resources. +- Resource completions for `repo://` templates are checked against the resolved `owner` and `repo`; owner suggestions, and repository suggestions for an owner without an `owner/*` entry, are rejected. + +Rejected calls return a tool error that names the repository and the allowlist, so the model can correct itself. The allowlist limits what this server will do; it doesn't change what the token itself can access. + ## Lockdown Mode Lockdown mode limits the content that the server will surface from public repositories. When enabled, the server checks whether the author of each item has push access to the repository. Private repositories are unaffected, and collaborators keep full access to their own content. diff --git a/cmd/github-mcp-server/main.go b/cmd/github-mcp-server/main.go index 04ba68e226..915ddfbd90 100644 --- a/cmd/github-mcp-server/main.go +++ b/cmd/github-mcp-server/main.go @@ -115,6 +115,13 @@ var ( } } + var allowedRepos []string + if viper.IsSet("allowed_repos") { + if err := viper.UnmarshalKey("allowed_repos", &allowedRepos); err != nil { + return fmt.Errorf("failed to unmarshal allowed-repos: %w", err) + } + } + ttl := viper.GetDuration("repo-access-cache-ttl") stdioServerConfig := ghmcp.StdioServerConfig{ Version: serverVersion, @@ -132,6 +139,7 @@ var ( InsidersMode: viper.GetBool("insiders"), ExcludeTools: excludeTools, RepoAccessCacheTTL: &ttl, + AllowedRepos: allowedRepos, } // When no static token is provided, log in via OAuth using the given @@ -260,6 +268,7 @@ func init() { stdioCmd.Flags().String("oauth-client-id", "", "OAuth App or GitHub App client ID, enabling interactive OAuth login when no token is set") stdioCmd.Flags().String("oauth-client-secret", "", "OAuth client secret, if the app requires one (it is a public, non-confidential credential for distributed clients)") stdioCmd.Flags().StringSlice("oauth-scopes", nil, "Comma-separated OAuth scopes to request; also filters tools to those scopes. Defaults to the full supported set") + stdioCmd.Flags().StringSlice("allowed-repos", nil, "Comma-separated repositories (owner/repo or owner/*) that tools may access; calls outside the list are rejected") stdioCmd.Flags().Int("oauth-callback-port", 0, "Fixed local port for the OAuth callback server. Defaults to a random port; set a fixed port when mapping it through Docker") // The private key has no flag because passing it in argv would expose it. @@ -293,6 +302,7 @@ func init() { _ = viper.BindPFlag("oauth-client-id", stdioCmd.Flags().Lookup("oauth-client-id")) _ = viper.BindPFlag("oauth-client-secret", stdioCmd.Flags().Lookup("oauth-client-secret")) _ = viper.BindPFlag("oauth-scopes", stdioCmd.Flags().Lookup("oauth-scopes")) + _ = viper.BindPFlag("allowed_repos", stdioCmd.Flags().Lookup("allowed-repos")) _ = viper.BindPFlag("oauth-callback-port", stdioCmd.Flags().Lookup("oauth-callback-port")) _ = viper.BindPFlag("app-id", stdioCmd.Flags().Lookup("app-id")) _ = viper.BindPFlag("app-installation-id", stdioCmd.Flags().Lookup("app-installation-id")) diff --git a/docs/server-configuration.md b/docs/server-configuration.md index 25c641153e..0dd3985294 100644 --- a/docs/server-configuration.md +++ b/docs/server-configuration.md @@ -12,6 +12,7 @@ We currently support the following ways in which the GitHub MCP Server can be co | Exclude Tools | `X-MCP-Exclude-Tools` header | `--exclude-tools` flag or `GITHUB_EXCLUDE_TOOLS` env var | | Read-Only Mode | `X-MCP-Readonly` header or `/readonly` URL | `--read-only` flag or `GITHUB_READ_ONLY` env var | | Lockdown Mode | `X-MCP-Lockdown` header | `--lockdown-mode` flag or `GITHUB_LOCKDOWN_MODE` env var | +| Allowed Repositories | Not available | `--allowed-repos` flag or `GITHUB_ALLOWED_REPOS` env var | | Insiders Mode | `X-MCP-Insiders` header or `/insiders` URL | `--insiders` flag or `GITHUB_INSIDERS` env var | | Feature Flags | `X-MCP-Features` header or `?features=` URL query parameter | `--features` flag | | Scope Filtering | Always enabled | Always enabled | @@ -341,6 +342,30 @@ As an intentional exception, content authored by trusted bot accounts (currently --- +### Allowed Repositories + +**Best for:** Sandboxing an agent to specific repositories when the token can see more, for example a fine-grained token that also has read access to public repositories. + +Pass `owner/repo` or `owner/*` entries. Tool calls, `repo://` resource reads and resource completions outside the list are rejected before any GitHub API request is made, search queries must be scoped with positive `repo:`, `org:` or `user:` qualifiers inside the list, and tools whose target cannot be told from their arguments (notification threads, project items, enterprise-level settings) are rejected. See [Allowed Repositories](../README.md#allowed-repositories) for the full rules. This option is only available for the local server. + +```json +{ + "type": "stdio", + "command": "go", + "args": [ + "run", + "./cmd/github-mcp-server", + "stdio", + "--allowed-repos=octo-org/*,octocat/hello-world" + ], + "env": { + "GITHUB_PERSONAL_ACCESS_TOKEN": "${input:github_token}" + } +} +``` + +--- + ### Insiders Mode **Best for:** Users who want early access to experimental features and new tools before they reach general availability. diff --git a/internal/ghmcp/allowed_repos.go b/internal/ghmcp/allowed_repos.go new file mode 100644 index 0000000000..4f57315922 --- /dev/null +++ b/internal/ghmcp/allowed_repos.go @@ -0,0 +1,463 @@ +package ghmcp + +import ( + "context" + "encoding/json" + "fmt" + "net/url" + "path" + "strings" + + "github.com/github/github-mcp-server/v2/pkg/utils" + "github.com/modelcontextprotocol/go-sdk/mcp" +) + +// repoAllowlist restricts tool calls, resource reads and completions to a +// fixed set of repositories. Entries are "owner/repo" or "owner/", where +// the repo part may use path.Match wildcards (for example "octo-org/*" or +// "octo-org/svc-*"). Matching is case-insensitive, like GitHub names. +// +// The check is applied to the arguments of each request before the tool runs. +// It fails closed: a call is only allowed when every repository it can reach +// is known from its arguments and is in the list. Owner-wide calls need an +// "owner/*" entry, search queries must carry allowed repo:, org: or user: +// qualifiers, and tools whose target cannot be told from their arguments +// (notification threads, project items, enterprise-level settings) are +// rejected, except for a small set of tools that never return repository +// content. +type repoAllowlist struct { + entries []repoAllowlistEntry +} + +type repoAllowlistEntry struct { + owner string + repo string // path.Match pattern, lower case +} + +// allowlistExemptTools never read or write repository content, so they keep +// working when an allowlist is configured. +var allowlistExemptTools = map[string]bool{ + "get_me": true, + "get_teams": true, + "get_team_members": true, + "search_users": true, + "search_orgs": true, + "get_global_security_advisory": true, + "list_global_security_advisories": true, + "create_gist": true, + "get_gist": true, + "list_gists": true, + "update_gist": true, +} + +// allowlistBlockedTools address their target by an opaque identifier (a +// notification thread), so the repository involved cannot be checked here. +var allowlistBlockedTools = map[string]string{ + "dismiss_notification": "notification threads are not tied to a repository", + "get_notification_details": "notification threads are not tied to a repository", + "manage_notification_subscription": "notification threads are not tied to a repository", +} + +// allowlistRepoRequiredTools fall back to account-wide endpoints unless both +// owner and repo are given, so an owner-only call is not enough for them. +var allowlistRepoRequiredTools = map[string]bool{ + "list_notifications": true, + "mark_all_notifications_read": true, +} + +// allowlistBlockedProjectMethods read or write project items whose +// repositories are not known from the arguments, or address a project +// resource by node ID alone. +var allowlistBlockedProjectMethods = map[string]string{ + "list_project_items": "project items may belong to repositories outside the allowlist", + "get_project_item": "project items may belong to repositories outside the allowlist", + "get_project_status_update": "the project cannot be told from a node ID", + "get_project_view": "the project cannot be told from a node ID", +} + +// allowlistItemRefProjectMethods act on a single project item, which must be +// named by item_owner, item_repo and issue_number so its repository can be +// checked. +var allowlistItemRefProjectMethods = map[string]bool{ + "add_project_item": true, + "update_project_item": true, + "delete_project_item": true, +} + +// parseRepoAllowlist validates the configured entries. It returns nil when no +// entries are given, which disables the check. +func parseRepoAllowlist(values []string) (*repoAllowlist, error) { + var list repoAllowlist + for _, raw := range values { + value := strings.TrimSpace(raw) + if value == "" { + continue + } + owner, repo, ok := strings.Cut(value, "/") + if !ok || owner == "" || repo == "" || strings.Contains(repo, "/") { + return nil, fmt.Errorf("invalid allowed repository %q: expected owner/repo or owner/*", value) + } + if strings.ContainsAny(owner, "*?[]\\") { + return nil, fmt.Errorf("invalid allowed repository %q: wildcards are only supported in the repository name", value) + } + repo = strings.ToLower(repo) + if _, err := path.Match(repo, ""); err != nil { + return nil, fmt.Errorf("invalid allowed repository %q: %w", value, err) + } + list.entries = append(list.entries, repoAllowlistEntry{owner: strings.ToLower(owner), repo: repo}) + } + if len(list.entries) == 0 { + return nil, nil + } + return &list, nil +} + +func (l *repoAllowlist) allowsRepo(owner, repo string) bool { + owner, repo = strings.ToLower(owner), strings.ToLower(repo) + for _, e := range l.entries { + if e.owner != owner { + continue + } + if ok, _ := path.Match(e.repo, repo); ok { + return true + } + } + return false +} + +// allowsOwner reports whether every repository of owner is allowed, which is +// required for calls scoped to an owner rather than a single repository. +func (l *repoAllowlist) allowsOwner(owner string) bool { + owner = strings.ToLower(owner) + for _, e := range l.entries { + if e.owner == owner && e.repo == "*" { + return true + } + } + return false +} + +func (l *repoAllowlist) String() string { + parts := make([]string, len(l.entries)) + for i, e := range l.entries { + parts[i] = e.owner + "/" + e.repo + } + return strings.Join(parts, ", ") +} + +// checkPair validates an owner/repo pair taken from tool arguments. An owner +// without a repository is an owner-wide call and needs an owner/* entry. +func (l *repoAllowlist) checkPair(owner, repo string) string { + switch { + case owner != "" && repo != "": + if !l.allowsRepo(owner, repo) { + return fmt.Sprintf("repository %s/%s is not in the allowed repositories", owner, repo) + } + case owner != "": + if !l.allowsOwner(owner) { + return fmt.Sprintf("owner-wide access to %s requires %s/* in the allowed repositories", owner, owner) + } + } + return "" +} + +// checkToolCall returns a non-empty reason when the call must be rejected. +func (l *repoAllowlist) checkToolCall(name string, rawArgs json.RawMessage) string { + if allowlistExemptTools[name] { + return "" + } + if reason, blocked := allowlistBlockedTools[name]; blocked { + return fmt.Sprintf("%s is not available when allowed repositories are configured: %s", name, reason) + } + + args := map[string]any{} + if len(rawArgs) > 0 { + if err := json.Unmarshal(rawArgs, &args); err != nil { + return "tool arguments could not be read to check the repository allowlist" + } + } + str := func(key string) string { + s, _ := args[key].(string) + return strings.TrimSpace(s) + } + + owner, repo := str("owner"), str("repo") + scoped := owner != "" || str("org") != "" + + // Tools with a "level" argument (rulesets, custom properties) only use the + // arguments of the selected level, so other arguments must not count. + if level := str("level"); level != "" { + switch level { + case "repository": + if owner == "" || repo == "" { + return fmt.Sprintf("%s at the repository level needs owner and repo for one of the allowed repositories", name) + } + case "organization": + if str("org") == "" { + return fmt.Sprintf("%s at the organization level needs org, with an org/* entry in the allowed repositories", name) + } + default: + return fmt.Sprintf("%s at the %s level is not available when allowed repositories are configured", name, level) + } + } + + if allowlistRepoRequiredTools[name] && (owner == "" || repo == "") { + return fmt.Sprintf("%s needs both owner and repo when allowed repositories are configured; without them it covers every repository", name) + } + + if reason := l.checkPair(owner, repo); reason != "" { + return reason + } + if org := str("org"); org != "" { + if reason := l.checkPair(org, ""); reason != "" { + return reason + } + } + + // Secondary repository targets. Missing parts default the way the + // handlers default them. + if po, pr := str("parent_owner"), str("parent_repo"); po != "" || pr != "" { + if po == "" { + po = owner + } + if pr == "" { + pr = repo + } + if reason := l.checkPair(po, pr); reason != "" { + return reason + } + } + if ro, rr := str("related_owner"), str("related_repo"); ro != "" || rr != "" { + if ro == "" { + ro = owner + } + if rr == "" { + rr = repo + } + if reason := l.checkPair(ro, rr); reason != "" { + return reason + } + } + if reason := l.checkPair(str("item_owner"), str("item_repo")); reason != "" { + return reason + } + + switch name { + case "create_repository": + org := str("organization") + if org == "" { + return "create_repository needs an organization when allowed repositories are configured" + } + if reason := l.checkPair(org, str("name")); reason != "" { + return reason + } + scoped = true + case "fork_repository": + org := str("organization") + if org == "" { + return "fork_repository needs an organization when allowed repositories are configured; forks into the personal account cannot be checked" + } + if reason := l.checkPair(org, repo); reason != "" { + return reason + } + case "projects_list", "projects_get", "projects_write": + if reason := l.checkProjectCall(name, args, str); reason != "" { + return reason + } + } + + if query, ok := args["query"].(string); ok && strings.HasPrefix(name, "search_") { + found, reason := l.checkSearchQuery(query) + if reason != "" { + return reason + } + // search_issues and search_pull_requests add repo:owner/repo to the + // query for the owner/repo arguments, but only when the query has no + // repo: qualifier of its own. Every other search tool ignores them. + argsScope := (name == "search_issues" || name == "search_pull_requests") && + owner != "" && repo != "" && !found.anyRepoQualifier + scoped = found.scoped || argsScope + } + + if !scoped { + return fmt.Sprintf("%s is not scoped to a repository; pass owner and repo (or repo:owner/name in a search query) for one of the allowed repositories", name) + } + return "" +} + +// checkProjectCall rejects project methods whose items cannot be tied to an +// allowed repository. Projects are owner-wide, so the owner argument has +// already been checked against an owner/* entry. +func (l *repoAllowlist) checkProjectCall(name string, args map[string]any, str func(string) string) string { + method := str("method") + if reason, blocked := allowlistBlockedProjectMethods[method]; blocked { + return fmt.Sprintf("%s %s is not available when allowed repositories are configured: %s", name, method, reason) + } + if allowlistItemRefProjectMethods[method] && (str("item_owner") == "" || str("item_repo") == "") { + return fmt.Sprintf("%s %s needs item_owner and item_repo for one of the allowed repositories", name, method) + } + if method != "update_project_items" { + return "" + } + items, _ := args["items"].([]any) + if len(items) == 0 { + return fmt.Sprintf("%s %s needs items that name item_owner and item_repo for allowed repositories", name, method) + } + for i, raw := range items { + entry, ok := raw.(map[string]any) + if !ok { + return fmt.Sprintf("%s %s: item %d could not be read to check the repository allowlist", name, method, i) + } + itemOwner, _ := entry["item_owner"].(string) + itemRepo, _ := entry["item_repo"].(string) + itemOwner, itemRepo = strings.TrimSpace(itemOwner), strings.TrimSpace(itemRepo) + if itemOwner == "" || itemRepo == "" { + return fmt.Sprintf("%s %s: item %d must be named by item_owner, item_repo and issue_number when allowed repositories are configured", name, method, i) + } + if !l.allowsRepo(itemOwner, itemRepo) { + return fmt.Sprintf("%s %s: item %d is in %s/%s, which is not in the allowed repositories", name, method, i, itemOwner, itemRepo) + } + } + return "" +} + +// searchQueryScope is what checkSearchQuery learned about a query. +type searchQueryScope struct { + // scoped is true when a positive, unquoted repo:, org:, user: or owner: + // qualifier restricts the query to allowed repositories. + scoped bool + // anyRepoQualifier is true when the query carries any repo: qualifier, + // positive or negated, which stops the issue search tools from adding + // their own. + anyRepoQualifier bool +} + +// checkSearchQuery validates the scope qualifiers in a GitHub search query. +// Multiple qualifiers are OR-ed by GitHub search, so every repo:, org:, user: +// and owner: qualifier must be allowed, and only positive, unquoted ones count +// as scope: a negated qualifier only narrows the results, and a quoted one is +// free text to the lexical search. Boolean operators and parentheses are +// rejected because a qualifier in one branch does not constrain the others. +func (l *repoAllowlist) checkSearchQuery(query string) (searchQueryScope, string) { + var found searchQueryScope + for field := range strings.FieldsSeq(query) { + if field == "OR" || field == "NOT" || field == "AND" || strings.ContainsAny(field, "()") { + return found, "search queries with boolean operators or parentheses are not supported when allowed repositories are configured; use plain qualifiers" + } + quoted := strings.ContainsAny(field, `"'`) + negated := strings.HasPrefix(field, "-") + key, value, ok := strings.Cut(strings.TrimPrefix(field, "-"), ":") + if !ok { + continue + } + value = strings.Trim(value, `"'`) + switch strings.ToLower(key) { + case "repo": + found.anyRepoQualifier = true + if negated { + continue + } + owner, repo, ok := strings.Cut(value, "/") + if !ok || !l.allowsRepo(owner, repo) { + return found, fmt.Sprintf("search qualifier repo:%s is not in the allowed repositories", value) + } + found.scoped = found.scoped || !quoted + case "org", "user", "owner": + if negated { + continue + } + if !l.allowsOwner(value) { + return found, fmt.Sprintf("search qualifier %s:%s requires %s/* in the allowed repositories", key, value, value) + } + found.scoped = found.scoped || !quoted + } + } + return found, "" +} + +// uiResourceScheme is the scheme of the bundled MCP App resources, which only +// serve static HTML and never touch a repository. +const uiResourceScheme = "ui" + +// checkResourceURI validates resource URIs. repo:// URIs must name an allowed +// repository; the static ui:// resources are always allowed; anything else is +// rejected. +func (l *repoAllowlist) checkResourceURI(uri string) string { + u, err := url.Parse(uri) + if err != nil { + return fmt.Sprintf("resource %s is not scoped to an allowed repository", uri) + } + switch u.Scheme { + case uiResourceScheme: + return "" + case "repo": + owner := u.Host + repo, _, _ := strings.Cut(strings.TrimPrefix(u.Path, "/"), "/") + if owner == "" || repo == "" || !l.allowsRepo(owner, repo) { + return fmt.Sprintf("repository %s/%s is not in the allowed repositories", owner, repo) + } + return "" + default: + return fmt.Sprintf("resource %s is not scoped to an allowed repository", uri) + } +} + +// checkCompletion validates a completion request for a repo:// resource +// template. Owner suggestions and repository suggestions for an owner without +// an owner/* entry would list repositories outside the allowlist, so they are +// rejected; every other argument is completed only for an allowed repository. +func (l *repoAllowlist) checkCompletion(params *mcp.CompleteParams) string { + if params == nil || params.Ref == nil || params.Ref.Type != "ref/resource" { + return "" + } + if !strings.HasPrefix(params.Ref.URI, "repo://") { + return "" + } + var owner, repo string + if params.Context != nil { + owner = strings.TrimSpace(params.Context.Arguments["owner"]) + repo = strings.TrimSpace(params.Context.Arguments["repo"]) + } + switch params.Argument.Name { + case "owner": + return "owner completions are not available when allowed repositories are configured" + case "repo": + if owner == "" || !l.allowsOwner(owner) { + return fmt.Sprintf("repository completions for %q require %s/* in the allowed repositories", owner, owner) + } + return "" + default: + if owner == "" || repo == "" { + return "completions need a resolved owner and repo for one of the allowed repositories" + } + return l.checkPair(owner, repo) + } +} + +// allowedReposMiddleware enforces the allowlist on tools/call, resources/read +// and completion/complete before any GitHub API request is made. +func allowedReposMiddleware(list *repoAllowlist) mcp.Middleware { + return func(next mcp.MethodHandler) mcp.MethodHandler { + return func(ctx context.Context, method string, request mcp.Request) (mcp.Result, error) { + switch req := request.(type) { + case *mcp.CallToolRequest: + if req.Params != nil { + if reason := list.checkToolCall(req.Params.Name, req.Params.Arguments); reason != "" { + return utils.NewToolResultError(fmt.Sprintf("access denied: %s (allowed: %s)", reason, list)), nil + } + } + case *mcp.ReadResourceRequest: + if req.Params != nil { + if reason := list.checkResourceURI(req.Params.URI); reason != "" { + return nil, fmt.Errorf("access denied: %s (allowed: %s)", reason, list) + } + } + case *mcp.CompleteRequest: + if reason := list.checkCompletion(req.Params); reason != "" { + return nil, fmt.Errorf("access denied: %s (allowed: %s)", reason, list) + } + } + return next(ctx, method, request) + } + } +} diff --git a/internal/ghmcp/allowed_repos_test.go b/internal/ghmcp/allowed_repos_test.go new file mode 100644 index 0000000000..faa1d8e272 --- /dev/null +++ b/internal/ghmcp/allowed_repos_test.go @@ -0,0 +1,225 @@ +package ghmcp + +import ( + "context" + "encoding/json" + "testing" + + "github.com/modelcontextprotocol/go-sdk/mcp" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestParseRepoAllowlist(t *testing.T) { + list, err := parseRepoAllowlist(nil) + require.NoError(t, err) + assert.Nil(t, list) + + list, err = parseRepoAllowlist([]string{" ", ""}) + require.NoError(t, err) + assert.Nil(t, list) + + list, err = parseRepoAllowlist([]string{"Octo-Org/*", " octocat/Hello-World ", "acme/svc-*"}) + require.NoError(t, err) + require.NotNil(t, list) + assert.Equal(t, "octo-org/*, octocat/hello-world, acme/svc-*", list.String()) + + for _, bad := range []string{"octocat", "/repo", "owner/", "a/b/c", "*/repo", "owner/[abc"} { + _, err := parseRepoAllowlist([]string{bad}) + assert.Error(t, err, bad) + } +} + +func TestRepoAllowlistCheckToolCall(t *testing.T) { + list, err := parseRepoAllowlist([]string{"octo-org/*", "octocat/hello-world", "acme/svc-*"}) + require.NoError(t, err) + + tests := []struct { + name string + tool string + args string + allowed bool + }{ + {"exact repo", "get_file_contents", `{"owner":"octocat","repo":"hello-world","path":"README.md"}`, true}, + {"case insensitive", "get_file_contents", `{"owner":"OctoCat","repo":"Hello-World"}`, true}, + {"other repo same owner", "get_file_contents", `{"owner":"octocat","repo":"spoon-knife"}`, false}, + {"owner wildcard", "list_issues", `{"owner":"octo-org","repo":"anything"}`, true}, + {"repo glob", "list_issues", `{"owner":"acme","repo":"svc-billing"}`, true}, + {"repo glob miss", "list_issues", `{"owner":"acme","repo":"website"}`, false}, + {"other owner", "list_issues", `{"owner":"someone","repo":"public"}`, false}, + {"owner only needs wildcard", "projects_list", `{"owner":"octo-org","method":"list_projects"}`, true}, + {"owner only without wildcard", "projects_list", `{"owner":"octocat","method":"list_projects"}`, false}, + {"project item in other repo", "projects_write", `{"owner":"octo-org","item_owner":"someone","item_repo":"x"}`, false}, + {"org advisories", "list_org_repository_security_advisories", `{"org":"octo-org"}`, true}, + {"org advisories other org", "list_org_repository_security_advisories", `{"org":"acme"}`, false}, + {"unscoped notifications", "list_notifications", `{}`, false}, + {"scoped notifications", "list_notifications", `{"owner":"octocat","repo":"hello-world"}`, true}, + {"notification by id", "get_notification_details", `{"notificationID":"1"}`, false}, + {"exempt tool", "get_me", ``, true}, + {"exempt search users", "search_users", `{"query":"location:berlin"}`, true}, + {"search with repo qualifier", "search_code", `{"query":"func main repo:octocat/hello-world"}`, true}, + {"search with org qualifier", "search_code", `{"query":"org:octo-org TODO"}`, true}, + {"search without scope", "search_code", `{"query":"func main"}`, false}, + {"search with outside repo", "search_code", `{"query":"repo:octocat/hello-world repo:evil/leak"}`, false}, + {"search negated qualifier ignored", "search_code", `{"query":"org:octo-org -repo:evil/leak"}`, true}, + {"search org without wildcard", "search_repositories", `{"query":"user:octocat"}`, false}, + {"search issues scoped by args", "search_issues", `{"query":"is:open","owner":"octocat","repo":"hello-world"}`, true}, + {"search issues args plus outside qualifier", "search_issues", `{"query":"repo:evil/leak","owner":"octocat","repo":"hello-world"}`, false}, + {"create repository in allowed org", "create_repository", `{"name":"new","organization":"octo-org"}`, true}, + {"create repository for user", "create_repository", `{"name":"new"}`, false}, + {"fork into allowed org", "fork_repository", `{"owner":"octocat","repo":"hello-world","organization":"octo-org"}`, true}, + {"fork into other org", "fork_repository", `{"owner":"octocat","repo":"hello-world","organization":"acme"}`, false}, + {"fork into personal account", "fork_repository", `{"owner":"octocat","repo":"hello-world"}`, false}, + {"owner-only notifications", "list_notifications", `{"owner":"octo-org"}`, false}, + {"owner-only mark all read", "mark_all_notifications_read", `{"owner":"octo-org"}`, false}, + {"notification thread by id", "dismiss_notification", `{"threadID":"1","state":"read"}`, false}, + {"notification thread with decoy repo", "get_notification_details", `{"notificationID":"1","owner":"octocat","repo":"hello-world"}`, false}, + {"notification subscription by id", "manage_notification_subscription", `{"notificationID":"1","action":"watch"}`, false}, + {"repository level needs pair", "repository_ruleset_read", `{"level":"repository","method":"list","owner":"octo-org"}`, false}, + {"repository level", "repository_ruleset_read", `{"level":"repository","method":"list","owner":"octocat","repo":"hello-world"}`, true}, + {"organization level", "custom_properties_read", `{"level":"organization","org":"octo-org"}`, true}, + {"organization level other org", "custom_properties_read", `{"level":"organization","org":"acme"}`, false}, + {"organization level with decoy repo", "custom_properties_read", `{"level":"organization","owner":"octocat","repo":"hello-world"}`, false}, + {"enterprise level", "repository_ruleset_read", `{"level":"enterprise","method":"list","enterprise":"x","owner":"octocat","repo":"hello-world"}`, false}, + {"parent issue same repo", "issue_write", `{"method":"create","owner":"octocat","repo":"hello-world","parent_issue_number":1,"parent_repo":"hello-world"}`, true}, + {"parent issue other repo", "issue_write", `{"method":"create","owner":"octocat","repo":"hello-world","parent_issue_number":1,"parent_repo":"spoon-knife"}`, false}, + {"parent issue other owner", "issue_write", `{"method":"create","owner":"octocat","repo":"hello-world","parent_owner":"someone","parent_repo":"hello-world"}`, false}, + {"related issue defaults", "issue_dependency_write", `{"owner":"octocat","repo":"hello-world","related_owner":"octocat"}`, true}, + {"related issue other repo", "issue_dependency_write", `{"owner":"octocat","repo":"hello-world","related_repo":"spoon-knife"}`, false}, + {"project items listing", "projects_list", `{"owner":"octo-org","method":"list_project_items","project_number":1}`, false}, + {"project item by id", "projects_get", `{"owner":"octo-org","method":"get_project_item","project_number":1,"item_id":5}`, false}, + {"project view by node id", "projects_get", `{"method":"get_project_view","view_id":"PVTV_1"}`, false}, + {"project status update by node id", "projects_get", `{"owner":"octo-org","method":"get_project_status_update","status_update_id":"PVTSU_1"}`, false}, + {"project get", "projects_get", `{"owner":"octo-org","method":"get_project","project_number":1}`, true}, + {"add project item in allowed repo", "projects_write", `{"owner":"octo-org","method":"add_project_item","project_number":1,"item_type":"issue","item_owner":"octocat","item_repo":"hello-world","issue_number":1}`, true}, + {"update project item by id", "projects_write", `{"owner":"octo-org","method":"update_project_item","project_number":1,"item_id":5}`, false}, + {"update project item by issue", "projects_write", `{"owner":"octo-org","method":"update_project_item","project_number":1,"item_owner":"octo-org","item_repo":"x","issue_number":2}`, true}, + {"batch items all allowed", "projects_write", `{"owner":"octo-org","method":"update_project_items","project_number":1,"items":[{"item_owner":"octocat","item_repo":"hello-world","issue_number":1},{"item_owner":"acme","item_repo":"svc-a","issue_number":2}]}`, true}, + {"batch item outside", "projects_write", `{"owner":"octo-org","method":"update_project_items","project_number":1,"items":[{"item_owner":"octocat","item_repo":"hello-world","issue_number":1},{"item_owner":"acme","item_repo":"web","issue_number":2}]}`, false}, + {"batch item by node id", "projects_write", `{"owner":"octo-org","method":"update_project_items","project_number":1,"items":[{"node_id":"PVTI_1"}]}`, false}, + {"batch without items", "projects_write", `{"owner":"octo-org","method":"update_project_items","project_number":1}`, false}, + {"search issues args with negated repo in query", "search_issues", `{"query":"is:open -repo:octocat/other","owner":"octocat","repo":"hello-world"}`, false}, + {"search issues args with allowed positive repo", "search_issues", `{"query":"repo:octocat/hello-world -repo:octocat/other","owner":"octocat","repo":"hello-world"}`, true}, + {"search pull requests args only", "search_pull_requests", `{"query":"is:open","owner":"octocat","repo":"hello-world"}`, true}, + {"search code ignores owner args", "search_code", `{"query":"func main","owner":"octocat","repo":"hello-world"}`, false}, + {"search quoted qualifier is free text", "search_issues", `{"query":""repo:octocat/hello-world" crash"}`, false}, + {"search quoted outside repo", "search_issues", `{"query":""repo:evil/leak" repo:octocat/hello-world"}`, false}, + {"search OR branch", "search_code", `{"query":"repo:octocat/hello-world foo OR bar"}`, false}, + {"search parentheses", "search_code", `{"query":"(repo:octocat/hello-world OR repo:evil/leak) foo"}`, false}, + {"search NOT", "search_code", `{"query":"repo:octocat/hello-world NOT foo"}`, false}, + {"search negated owner ignored", "search_code", `{"query":"org:octo-org -user:someone TODO"}`, true}, + {"invalid json", "get_file_contents", `{`, false}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + reason := list.checkToolCall(tc.tool, json.RawMessage(tc.args)) + if tc.allowed { + assert.Empty(t, reason) + } else { + assert.NotEmpty(t, reason) + } + }) + } +} + +func TestRepoAllowlistCheckResourceURI(t *testing.T) { + list, err := parseRepoAllowlist([]string{"octocat/hello-world"}) + require.NoError(t, err) + + assert.Empty(t, list.checkResourceURI("repo://octocat/hello-world/contents/README.md")) + assert.Empty(t, list.checkResourceURI("repo://OctoCat/Hello-World/refs/heads/main/contents/")) + assert.NotEmpty(t, list.checkResourceURI("repo://octocat/spoon-knife/contents/README.md")) + assert.NotEmpty(t, list.checkResourceURI("https://example.com/x")) + assert.Empty(t, list.checkResourceURI("ui://github-mcp-server/get-me")) + assert.Empty(t, list.checkResourceURI("ui://github-mcp-server/issue-write")) +} + +func TestRepoAllowlistCheckCompletion(t *testing.T) { + list, err := parseRepoAllowlist([]string{"octo-org/*", "octocat/hello-world"}) + require.NoError(t, err) + + resource := &mcp.CompleteReference{Type: "ref/resource", URI: "repo://{owner}/{repo}/contents{/path*}"} + complete := func(arg string, resolved map[string]string) string { + return list.checkCompletion(&mcp.CompleteParams{ + Ref: resource, + Argument: mcp.CompleteParamsArgument{Name: arg, Value: ""}, + Context: &mcp.CompleteContext{Arguments: resolved}, + }) + } + + assert.Empty(t, list.checkCompletion(nil)) + assert.Empty(t, list.checkCompletion(&mcp.CompleteParams{Ref: &mcp.CompleteReference{Type: "ref/prompt", Name: "x"}})) + assert.NotEmpty(t, complete("owner", nil)) + assert.NotEmpty(t, complete("repo", map[string]string{"owner": "octocat"})) + assert.Empty(t, complete("repo", map[string]string{"owner": "octo-org"})) + assert.NotEmpty(t, complete("branch", map[string]string{"owner": "octocat"})) + assert.NotEmpty(t, complete("branch", map[string]string{"owner": "octocat", "repo": "spoon-knife"})) + assert.Empty(t, complete("path", map[string]string{"owner": "octocat", "repo": "hello-world"})) +} + +func TestAllowedReposMiddleware(t *testing.T) { + list, err := parseRepoAllowlist([]string{"octocat/hello-world"}) + require.NoError(t, err) + + called := 0 + next := func(_ context.Context, _ string, _ mcp.Request) (mcp.Result, error) { + called++ + return &mcp.CallToolResult{}, nil + } + handler := allowedReposMiddleware(list)(next) + + allowed := &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{ + Name: "get_file_contents", + Arguments: json.RawMessage(`{"owner":"octocat","repo":"hello-world"}`), + }} + res, err := handler(context.Background(), "tools/call", allowed) + require.NoError(t, err) + assert.False(t, res.(*mcp.CallToolResult).IsError) + assert.Equal(t, 1, called) + + denied := &mcp.CallToolRequest{Params: &mcp.CallToolParamsRaw{ + Name: "get_file_contents", + Arguments: json.RawMessage(`{"owner":"octocat","repo":"spoon-knife"}`), + }} + res, err = handler(context.Background(), "tools/call", denied) + require.NoError(t, err) + result := res.(*mcp.CallToolResult) + assert.True(t, result.IsError) + assert.Contains(t, result.Content[0].(*mcp.TextContent).Text, "octocat/spoon-knife is not in the allowed repositories") + assert.Equal(t, 1, called) + + _, err = handler(context.Background(), "resources/read", &mcp.ReadResourceRequest{Params: &mcp.ReadResourceParams{ + URI: "repo://octocat/spoon-knife/contents/README.md", + }}) + require.Error(t, err) + assert.Equal(t, 1, called) + + _, err = handler(context.Background(), "resources/read", &mcp.ReadResourceRequest{Params: &mcp.ReadResourceParams{ + URI: "repo://octocat/hello-world/contents/README.md", + }}) + require.NoError(t, err) + assert.Equal(t, 2, called) + + _, err = handler(context.Background(), "resources/read", &mcp.ReadResourceRequest{Params: &mcp.ReadResourceParams{ + URI: "ui://github-mcp-server/get-me", + }}) + require.NoError(t, err) + assert.Equal(t, 3, called) + + resource := &mcp.CompleteReference{Type: "ref/resource", URI: "repo://{owner}/{repo}/refs/heads/{branch}/contents{/path*}"} + _, err = handler(context.Background(), "completion/complete", &mcp.CompleteRequest{Params: &mcp.CompleteParams{ + Ref: resource, + Argument: mcp.CompleteParamsArgument{Name: "branch"}, + Context: &mcp.CompleteContext{Arguments: map[string]string{"owner": "octocat", "repo": "spoon-knife"}}, + }}) + require.Error(t, err) + assert.Equal(t, 3, called) + + _, err = handler(context.Background(), "completion/complete", &mcp.CompleteRequest{Params: &mcp.CompleteParams{ + Ref: resource, + Argument: mcp.CompleteParamsArgument{Name: "branch"}, + Context: &mcp.CompleteContext{Arguments: map[string]string{"owner": "octocat", "repo": "hello-world"}}, + }}) + require.NoError(t, err) + assert.Equal(t, 4, called) +} diff --git a/internal/ghmcp/server.go b/internal/ghmcp/server.go index c826b6d0ea..f38c6fe275 100644 --- a/internal/ghmcp/server.go +++ b/internal/ghmcp/server.go @@ -289,6 +289,10 @@ type StdioServerConfig struct { // RepoAccessCacheTTL overrides the default TTL for repository access cache entries. RepoAccessCacheTTL *time.Duration + // AllowedRepos restricts tool calls and resource reads to these + // repositories ("owner/repo" or "owner/*"). Empty means no restriction. + AllowedRepos []string + // OAuthManager, when non-nil, enables OAuth 2.1 login for stdio mode. The // server starts without a token and runs the authorization flow on the // first tool call (see createOAuthMiddleware). It is mutually exclusive with @@ -360,6 +364,14 @@ func RunStdioServer(cfg StdioServerConfig) error { logger.Debug("skipping scope filtering for non-PAT token") } + allowedRepos, err := parseRepoAllowlist(cfg.AllowedRepos) + if err != nil { + return err + } + if allowedRepos != nil { + logger.Info("restricting tools to allowed repositories", "allowedRepos", allowedRepos.String()) + } + tokenProvider := cfg.TokenProvider var toolHandlerMiddleware []inventory.ToolHandlerMiddleware if cfg.OAuthManager != nil { @@ -389,6 +401,9 @@ func RunStdioServer(cfg StdioServerConfig) error { if err != nil { return fmt.Errorf("failed to create MCP server: %w", err) } + if allowedRepos != nil { + ghServer.AddReceivingMiddleware(allowedReposMiddleware(allowedRepos)) + } if cfg.ExportTranslations { // Once server is initialized, all translations are loaded