fix: store tokens in ~/.config/mcp-publisher/ instead of cwd (#1166)

## Summary

Fixes #663

- **Security fix**: `mcp-publisher login` no longer writes
`.mcpregistry_github_token` and `.mcpregistry_registry_token` to the
current working directory. GitHub tokens are kept in memory during the
login→exchange flow and cleared immediately after.
- **Token location**: Unified token moved from `~/.mcp_publisher_token`
to `~/.config/mcp-publisher/token.json` (dir 0700, file 0600), following
the convention used by `gh`, `docker`, and `kubectl`.
- **Dead code removed**: `NeedsLogin()` was on the `Provider` interface
but never called — removed from interface and all 4 implementations.
`forceLogin` field also removed.
- **Auth tests added**: 11 new tests for `GitHubATProvider` (package
previously had 0 tests).
- **Test isolation**: `SetupTestToken` now uses `t.TempDir()` +
`t.Setenv("HOME", ...)` instead of writing to real `$HOME`.

### Breaking change

Users must re-login after upgrading (`mcp-publisher login <method>`).
Existing tokens at `~/.mcp_publisher_token` are not auto-migrated.
`logout` cleans up both old and new locations.

## Test plan

- [x] `make check` passes (lint, unit tests, integration tests)
- [x] `mcp-publisher login none` stores token at
`~/.config/mcp-publisher/token.json`
- [x] No `.mcpregistry_*` files created in cwd after login (with
`--token`, `MCP_GITHUB_TOKEN`, or device flow)
- [x] `mcp-publisher publish` reads token from new location
- [x] `mcp-publisher validate` reads registry URL from new location
- [x] `mcp-publisher logout` cleans up new location, legacy
`~/.mcp_publisher_token`, and cwd `.mcpregistry_*` files
- [x] `mcp-publisher logout` when not logged in shows "Not logged in"
- [x] File permissions: dir 0700, file 0600

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Radoslav Dimitrov 2026-04-15 03:23:07 -04:00 • committed by GitHub
commit 90baa0528f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 556 additions and 203 deletions

View file

@ -16,15 +16,45 @@ import (
)
const (
DefaultRegistryURL = "https://registry.modelcontextprotocol.io"
TokenFileName = ".mcp_publisher_token" //nolint:gosec // Not a credential, just a filename
MethodGitHub = "github"
MethodGitHubOIDC = "github-oidc"
MethodDNS = "dns"
MethodHTTP = "http"
MethodNone = "none"
DefaultRegistryURL = "https://registry.modelcontextprotocol.io"
LegacyTokenFileName = ".mcp_publisher_token" //nolint:gosec // Not a credential, just a filename
MethodGitHub = "github"
MethodGitHubOIDC = "github-oidc"
MethodDNS = "dns"
MethodHTTP = "http"
MethodNone = "none"
)
// tokenFilePath returns the path to the token file in the user's config directory
// (~/.config/mcp-publisher/token.json). It does not create the directory.
func tokenFilePath() (string, error) {
homeDir, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("failed to get home directory: %w", err)
}
return filepath.Join(homeDir, ".config", "mcp-publisher", "token.json"), nil
}
// notAuthenticatedError returns an error guiding the user to log in,
// with a hint about the token location change for users upgrading.
func notAuthenticatedError() error {
_, _ = fmt.Fprintln(os.Stderr, "hint: token storage moved to ~/.config/mcp-publisher/. If you recently upgraded, please re-login.")
return errors.New("not authenticated, run 'mcp-publisher login <method>' first")
}
// ensureTokenDir creates the token directory (~/.config/mcp-publisher/) if needed.
func ensureTokenDir() error {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
dir := filepath.Join(homeDir, ".config", "mcp-publisher")
if err := os.MkdirAll(dir, 0700); err != nil {
return fmt.Errorf("failed to create config directory: %w", err)
}
return nil
}
type CryptoAlgorithm auth.CryptoAlgorithm
type SignerType string
@ -130,7 +160,7 @@ func createSigner(flags LoginFlags) (auth.Signer, error) {
func createAuthProvider(method, registryURL, domain string, token Token, signer auth.Signer) (auth.Provider, error) {
switch method {
case MethodGitHub:
return auth.NewGitHubATProvider(true, registryURL, string(token)), nil
return auth.NewGitHubATProvider(registryURL, string(token)), nil
case MethodGitHubOIDC:
return auth.NewGitHubOIDCProvider(registryURL), nil
case MethodDNS:
@ -226,12 +256,15 @@ Examples:
return fmt.Errorf("failed to get token: %w", err)
}
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
if err := ensureTokenDir(); err != nil {
return err
}
tokenPath, err := tokenFilePath()
if err != nil {
return err
}
tokenPath := filepath.Join(homeDir, TokenFileName)
tokenData := map[string]string{
"token": token,
"method": method,

View file

@ -0,0 +1,97 @@
package commands_test
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"github.com/modelcontextprotocol/registry/cmd/publisher/commands"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLoginCommand_WritesTokenToConfigDir(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
// Mock registry that returns a token for "none" auth
server := setupNoneAuthServer(t)
err := commands.LoginCommand([]string{"none", "--registry", server.URL})
require.NoError(t, err)
// Verify token written to new location
tokenPath := filepath.Join(tempHome, ".config", "mcp-publisher", "token.json")
data, err := os.ReadFile(tokenPath)
require.NoError(t, err)
var tokenInfo map[string]string
require.NoError(t, json.Unmarshal(data, &tokenInfo))
assert.Equal(t, "none", tokenInfo["method"])
assert.Equal(t, server.URL, tokenInfo["registry"])
assert.NotEmpty(t, tokenInfo["token"])
}
func TestLoginCommand_CreatesDirectoryWithCorrectPerms(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
server := setupNoneAuthServer(t)
err := commands.LoginCommand([]string{"none", "--registry", server.URL})
require.NoError(t, err)
// Verify directory permissions
dir := filepath.Join(tempHome, ".config", "mcp-publisher")
info, err := os.Stat(dir)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0700), info.Mode().Perm())
// Verify file permissions
tokenPath := filepath.Join(dir, "token.json")
info, err = os.Stat(tokenPath)
require.NoError(t, err)
assert.Equal(t, os.FileMode(0600), info.Mode().Perm())
}
func TestLoginCommand_DoesNotWriteLegacyFiles(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
server := setupNoneAuthServer(t)
err := commands.LoginCommand([]string{"none", "--registry", server.URL})
require.NoError(t, err)
// Verify no legacy file at $HOME
_, err = os.Stat(filepath.Join(tempHome, ".mcp_publisher_token"))
assert.True(t, os.IsNotExist(err), "should not create legacy ~/.mcp_publisher_token")
// Verify no .mcpregistry_* files in cwd
cwd, err := os.Getwd()
require.NoError(t, err)
for _, name := range []string{".mcpregistry_github_token", ".mcpregistry_registry_token"} {
_, err := os.Stat(filepath.Join(cwd, name))
assert.True(t, os.IsNotExist(err), "should not create %s in cwd", name)
}
}
// setupNoneAuthServer creates a mock registry that handles the "none" auth flow.
func setupNoneAuthServer(t *testing.T) *httptest.Server {
t.Helper()
mux := http.NewServeMux()
mux.HandleFunc("/v0/auth/none", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]interface{}{
"registry_token": "test-registry-jwt",
"expires_at": 9999999999,
})
})
server := httptest.NewServer(mux)
t.Cleanup(server.Close)
return server
}

View file

@ -7,37 +7,57 @@ import (
)
func LogoutCommand() error {
homeDir, err := os.UserHomeDir()
tokenPath, err := tokenFilePath()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
return err
}
tokenPath := filepath.Join(homeDir, TokenFileName)
// Check if token file exists at new location or legacy location
homeDir, err := os.UserHomeDir()
if err != nil {
homeDir = "" // degrade gracefully for legacy cleanup
}
legacyTokenPath := ""
if homeDir != "" {
legacyTokenPath = filepath.Join(homeDir, LegacyTokenFileName)
}
// Check if token file exists
if _, err := os.Stat(tokenPath); os.IsNotExist(err) {
newExists := fileExists(tokenPath)
legacyExists := legacyTokenPath != "" && fileExists(legacyTokenPath)
if !newExists && !legacyExists {
_, _ = fmt.Fprintln(os.Stdout, "Not logged in")
return nil
}
// Remove token file
if err := os.Remove(tokenPath); err != nil {
return fmt.Errorf("failed to remove token: %w", err)
// Remove token file from new location
os.Remove(tokenPath)
// Remove from legacy location
if legacyTokenPath != "" {
os.Remove(legacyTokenPath)
}
// Also clean up legacy token files if they exist
legacyFiles := []string{
// Clean up legacy intermediate token files from $HOME and cwd
legacyIntermediateFiles := []string{
".mcpregistry_github_token",
".mcpregistry_registry_token",
}
for _, file := range legacyFiles {
path := filepath.Join(homeDir, file)
if _, err := os.Stat(path); err == nil {
os.Remove(path) // Ignore errors for legacy files
for _, file := range legacyIntermediateFiles {
// Clean from $HOME
if homeDir != "" {
os.Remove(filepath.Join(homeDir, file))
}
// Clean from cwd (the original bug location)
os.Remove(file)
}
_, _ = fmt.Fprintln(os.Stdout, "✓ Successfully logged out")
return nil
}
func fileExists(path string) bool {
_, err := os.Stat(path)
return err == nil
}

View file

@ -0,0 +1,123 @@
package commands_test
import (
"os"
"path/filepath"
"testing"
"github.com/modelcontextprotocol/registry/cmd/publisher/commands"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLogoutCommand_RemovesNewToken(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
// Create token at new location
dir := filepath.Join(tempHome, ".config", "mcp-publisher")
require.NoError(t, os.MkdirAll(dir, 0700))
require.NoError(t, os.WriteFile(filepath.Join(dir, "token.json"), []byte(`{"token":"t"}`), 0600))
err := commands.LogoutCommand()
require.NoError(t, err)
_, err = os.Stat(filepath.Join(dir, "token.json"))
assert.True(t, os.IsNotExist(err))
}
func TestLogoutCommand_RemovesLegacyToken(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
// Create token at legacy location only
require.NoError(t, os.WriteFile(filepath.Join(tempHome, ".mcp_publisher_token"), []byte(`{"token":"t"}`), 0600))
err := commands.LogoutCommand()
require.NoError(t, err)
_, err = os.Stat(filepath.Join(tempHome, ".mcp_publisher_token"))
assert.True(t, os.IsNotExist(err))
}
func TestLogoutCommand_RemovesBothOldAndNew(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
// Create tokens at both locations
dir := filepath.Join(tempHome, ".config", "mcp-publisher")
require.NoError(t, os.MkdirAll(dir, 0700))
require.NoError(t, os.WriteFile(filepath.Join(dir, "token.json"), []byte(`{"token":"new"}`), 0600))
require.NoError(t, os.WriteFile(filepath.Join(tempHome, ".mcp_publisher_token"), []byte(`{"token":"old"}`), 0600))
err := commands.LogoutCommand()
require.NoError(t, err)
_, err = os.Stat(filepath.Join(dir, "token.json"))
assert.True(t, os.IsNotExist(err), "new token should be removed")
_, err = os.Stat(filepath.Join(tempHome, ".mcp_publisher_token"))
assert.True(t, os.IsNotExist(err), "legacy token should be removed")
}
func TestLogoutCommand_CleansUpCwdLegacyFiles(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
// Create a token so logout doesn't say "Not logged in"
dir := filepath.Join(tempHome, ".config", "mcp-publisher")
require.NoError(t, os.MkdirAll(dir, 0700))
require.NoError(t, os.WriteFile(filepath.Join(dir, "token.json"), []byte(`{"token":"t"}`), 0600))
// Create legacy intermediate files in a temp cwd
tempCwd := t.TempDir()
origDir, err := os.Getwd()
require.NoError(t, err)
t.Cleanup(func() { _ = os.Chdir(origDir) })
require.NoError(t, os.Chdir(tempCwd))
require.NoError(t, os.WriteFile(".mcpregistry_github_token", []byte("gh-token"), 0600))
require.NoError(t, os.WriteFile(".mcpregistry_registry_token", []byte("reg-token"), 0600))
err = commands.LogoutCommand()
require.NoError(t, err)
_, err = os.Stat(filepath.Join(tempCwd, ".mcpregistry_github_token"))
assert.True(t, os.IsNotExist(err), ".mcpregistry_github_token should be removed from cwd")
_, err = os.Stat(filepath.Join(tempCwd, ".mcpregistry_registry_token"))
assert.True(t, os.IsNotExist(err), ".mcpregistry_registry_token should be removed from cwd")
}
func TestLogoutCommand_CleansUpHomeLegacyFiles(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
// Create a token so logout doesn't say "Not logged in"
dir := filepath.Join(tempHome, ".config", "mcp-publisher")
require.NoError(t, os.MkdirAll(dir, 0700))
require.NoError(t, os.WriteFile(filepath.Join(dir, "token.json"), []byte(`{"token":"t"}`), 0600))
// Create legacy intermediate files in $HOME
require.NoError(t, os.WriteFile(filepath.Join(tempHome, ".mcpregistry_github_token"), []byte("gh-token"), 0600))
require.NoError(t, os.WriteFile(filepath.Join(tempHome, ".mcpregistry_registry_token"), []byte("reg-token"), 0600))
err := commands.LogoutCommand()
require.NoError(t, err)
_, err = os.Stat(filepath.Join(tempHome, ".mcpregistry_github_token"))
assert.True(t, os.IsNotExist(err), ".mcpregistry_github_token should be removed from $HOME")
_, err = os.Stat(filepath.Join(tempHome, ".mcpregistry_registry_token"))
assert.True(t, os.IsNotExist(err), ".mcpregistry_registry_token should be removed from $HOME")
}
func TestLogoutCommand_NotLoggedIn(t *testing.T) {
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
// No token files exist anywhere
err := commands.LogoutCommand()
// Should not error, just print "Not logged in"
require.NoError(t, err)
}

View file

@ -4,12 +4,10 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
@ -38,16 +36,15 @@ func PublishCommand(args []string) error {
}
// Load saved token
homeDir, err := os.UserHomeDir()
tokenPath, err := tokenFilePath()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
return err
}
tokenPath := filepath.Join(homeDir, TokenFileName)
tokenData, err := os.ReadFile(tokenPath)
if err != nil {
if os.IsNotExist(err) {
return errors.New("not authenticated. Run 'mcp-publisher login <method>' first")
return notAuthenticatedError()
}
return fmt.Errorf("failed to read token: %w", err)
}

View file

@ -12,7 +12,6 @@ import (
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
)
@ -95,16 +94,15 @@ func StatusCommand(args []string) error {
}
// Load saved token
homeDir, err := os.UserHomeDir()
tokenPath, err := tokenFilePath()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
return err
}
tokenPath := filepath.Join(homeDir, TokenFileName)
tokenData, err := os.ReadFile(tokenPath)
if err != nil {
if os.IsNotExist(err) {
return errors.New("not authenticated. Run 'mcp-publisher login <method>' first")
return notAuthenticatedError()
}
return fmt.Errorf("failed to read token: %w", err)
}

View file

@ -8,7 +8,6 @@ import (
"path/filepath"
"testing"
"github.com/modelcontextprotocol/registry/cmd/publisher/commands"
"github.com/modelcontextprotocol/registry/internal/validators"
apiv0 "github.com/modelcontextprotocol/registry/pkg/api/v0"
"github.com/stretchr/testify/require"
@ -64,14 +63,19 @@ func SetupMockRegistryServer(t *testing.T, publishHandler func(w http.ResponseWr
return server
}
// SetupTestToken creates a token file pointing to the test server
// SetupTestToken creates a token file pointing to the test server.
// It overrides $HOME to a temp directory so tests don't touch real credentials.
func SetupTestToken(t *testing.T, registryURL, token string) string {
t.Helper()
homeDir, err := os.UserHomeDir()
require.NoError(t, err)
// Override $HOME so tokenFilePath() resolves to a temp directory
tempHome := t.TempDir()
t.Setenv("HOME", tempHome)
tokenPath := filepath.Join(homeDir, commands.TokenFileName)
dir := filepath.Join(tempHome, ".config", "mcp-publisher")
require.NoError(t, os.MkdirAll(dir, 0700))
tokenPath := filepath.Join(dir, "token.json")
tokenData := map[string]string{
"token": token,
"registry": registryURL,
@ -83,10 +87,6 @@ func SetupTestToken(t *testing.T, registryURL, token string) string {
err = os.WriteFile(tokenPath, data, 0600)
require.NoError(t, err)
t.Cleanup(func() {
_ = os.Remove(tokenPath)
})
return tokenPath
}

View file

@ -8,7 +8,6 @@ import (
"io"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/modelcontextprotocol/registry/internal/validators"
@ -151,19 +150,15 @@ func ValidateCommand(args []string) error {
}
// Get registry URL (same pattern as publish)
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("failed to get home directory: %w", err)
}
tokenPath := filepath.Join(homeDir, TokenFileName)
registryURL := DefaultRegistryURL
// Try to read registry URL from token file (if it exists)
if tokenData, err := os.ReadFile(tokenPath); err == nil {
var tokenInfo map[string]string
if err := json.Unmarshal(tokenData, &tokenInfo); err == nil {
if url := tokenInfo["registry"]; url != "" {
registryURL = url
if tokenPath, err := tokenFilePath(); err == nil {
if tokenData, err := os.ReadFile(tokenPath); err == nil {
var tokenInfo map[string]string
if err := json.Unmarshal(tokenData, &tokenInfo); err == nil {
if url := tokenInfo["registry"]; url != "" {
registryURL = url
}
}
}
}