feat(auth): enhance OAuth provider handling with explicit hints and metadata preservation

This commit is contained in:
Luis Pater
2026-11-07 04:38:59 +08:00
parent c9f9739869
commit 482efbf5a7
7 changed files with 1026 additions and 110 deletions

View File

@@ -2,99 +2,456 @@ package management
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
"time"
"github.com/MoeForge/moego/ojson"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
"github.com/router-for-me/CLIProxyAPI/v8/internal/pluginhost"
"github.com/router-for-me/CLIProxyAPI/v8/internal/watcher/synthesizer"
coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi"
)
func TestAuthFilesList_ReportsOAuthProvider(t *testing.T) {
manager := coreauth.NewManager(nil, nil, nil)
auths := []*coreauth.Auth{
{ID: "builtin", FileName: "builtin.json", Provider: "vendor"},
{ID: "attributes", FileName: "attributes.json", Provider: "vendor", Attributes: map[string]string{"oauth_provider": "vendor-cn"}},
{ID: "metadata", FileName: "metadata.json", Provider: "vendor", Metadata: map[string]any{"oauth_provider": "vendor-cn"}},
{ID: "portal", FileName: "portal.json", Provider: "vendor", Metadata: map[string]any{"portal": " Vendor-CN "}},
{ID: "precedence", FileName: "precedence.json", Provider: "vendor", Attributes: map[string]string{"oauth_provider": "vendor"}, Metadata: map[string]any{"oauth_provider": "vendor-cn", "portal": "ignored"}},
{ID: "non-string", FileName: "non-string.json", Provider: "vendor", Metadata: map[string]any{"oauth_provider": 42}},
}
for _, auth := range auths {
if auth.Attributes == nil {
auth.Attributes = map[string]string{}
}
// Runtime-only keeps the entries off the auth dir, which the list route does not need.
auth.Attributes["runtime_only"] = "true"
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
t.Fatalf("failed to register auth %s: %v", auth.ID, errRegister)
}
}
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
listFiles := func(v8 bool) map[string]map[string]any {
t.Helper()
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
ctx.Request = httptest.NewRequest(http.MethodGet, "/v8/management/credentials", nil)
if v8 {
ctx.Set(ConfigV8ContextKey, true)
}
h.ListAuthFiles(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("expected status 200, got %d: %s", rec.Code, rec.Body.String())
}
var resp struct {
Files []map[string]any `json:"files"`
}
if errUnmarshal := json.Unmarshal(rec.Body.Bytes(), &resp); errUnmarshal != nil {
t.Fatalf("failed to unmarshal files: %v", errUnmarshal)
}
out := make(map[string]map[string]any, len(resp.Files))
for _, f := range resp.Files {
id, _ := f["id"].(string)
out[id] = f
}
return out
}
files := listFiles(true)
cases := []struct {
id string
want string
id string
attributes map[string]string
metadata map[string]any
want string
}{
{id: "builtin"},
{id: "attributes", want: "vendor-cn"},
{id: "metadata", want: "vendor-cn"},
{id: "portal", want: "vendor-cn"},
{id: "precedence", want: "vendor"},
{id: "non-string"},
{id: "attributes-normalized", attributes: map[string]string{"oauth_provider": " Vendor-CN "}, want: "vendor-cn"},
{id: "metadata-normalized", metadata: map[string]any{"oauth_provider": " Vendor-CN "}, want: "vendor-cn"},
{id: "attributes-portal-normalized", attributes: map[string]string{"portal": " Vendor-CN "}, want: "vendor-cn"},
{id: "metadata-portal-normalized", metadata: map[string]any{"portal": " Vendor-CN "}, want: "vendor-cn"},
{
id: "attributes-oauth-over-metadata-oauth",
attributes: map[string]string{"oauth_provider": " Vendor ", "portal": "ignored-attributes"},
metadata: map[string]any{"oauth_provider": "vendor-cn", "portal": "ignored-metadata"},
want: "vendor",
},
{
id: "metadata-oauth-over-attributes-portal",
attributes: map[string]string{"portal": "ignored-attributes"},
metadata: map[string]any{"oauth_provider": " Vendor-CN ", "portal": "ignored-metadata"},
want: "vendor-cn",
},
{
id: "attributes-portal-over-metadata-portal",
attributes: map[string]string{"portal": " Vendor-CN "},
metadata: map[string]any{"portal": "ignored-metadata"},
want: "vendor-cn",
},
{
id: "blank-attributes-oauth",
attributes: map[string]string{"oauth_provider": " ", "portal": "ignored"},
metadata: map[string]any{"oauth_provider": " Vendor-CN "},
want: "vendor-cn",
},
{
id: "blank-metadata-oauth",
attributes: map[string]string{"oauth_provider": " ", "portal": " Vendor-CN "},
metadata: map[string]any{"oauth_provider": " ", "portal": "ignored"},
want: "vendor-cn",
},
{
id: "blank-attributes-portal",
attributes: map[string]string{"oauth_provider": " ", "portal": " "},
metadata: map[string]any{"oauth_provider": " ", "portal": " Vendor-CN "},
want: "vendor-cn",
},
{id: "numeric-oauth-falls-back", attributes: map[string]string{"portal": "vendor-cn"}, metadata: map[string]any{"oauth_provider": 42}, want: "vendor-cn"},
{id: "boolean-oauth-falls-back", metadata: map[string]any{"oauth_provider": true, "portal": "vendor-cn"}, want: "vendor-cn"},
{id: "numeric-portal", metadata: map[string]any{"portal": 42}},
{id: "boolean-portal", metadata: map[string]any{"portal": true}},
{id: "non-string-hints", metadata: map[string]any{"oauth_provider": 42, "portal": true}},
{id: "blank-hints", attributes: map[string]string{"oauth_provider": " ", "portal": " "}, metadata: map[string]any{"oauth_provider": " ", "portal": " "}},
}
manager := coreauth.NewManager(nil, nil, nil)
for _, tc := range cases {
attributes := tc.attributes
if attributes == nil {
attributes = make(map[string]string)
}
// Runtime-only entries do not require files on disk.
attributes["runtime_only"] = "true"
if _, errRegister := manager.Register(context.Background(), &coreauth.Auth{
ID: tc.id, FileName: tc.id + ".json", Provider: "vendor", Attributes: attributes, Metadata: tc.metadata,
}); errRegister != nil {
t.Fatalf("register auth %s: %v", tc.id, errRegister)
}
}
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: t.TempDir()}, manager)
router := oauthProviderTestRouter(h)
files := listOAuthProviderTestFiles(t, router, "/v8/management/credentials")
if len(files) != len(cases) {
t.Fatalf("v8 files count = %d, want %d", len(files), len(cases))
}
for _, tc := range cases {
file, ok := files[tc.id]
if !ok {
t.Fatalf("expected auth entry %s in list", tc.id)
}
got, hasOAuthProvider := file["oauth_provider"]
if tc.want == "" {
if hasOAuthProvider {
t.Errorf("%s: expected no oauth_provider, got %#v", tc.id, got)
}
} else if got != tc.want {
t.Errorf("%s: expected oauth_provider %q, got %#v", tc.id, tc.want, got)
}
if file["type"] != "vendor" || file["provider"] != "vendor" {
t.Errorf("%s: expected type/provider to stay vendor, got %#v/%#v", tc.id, file["type"], file["provider"])
}
t.Run(tc.id, func(t *testing.T) {
assertOAuthProviderTestFile(t, files, tc.id, "vendor", tc.want)
})
}
// The deprecated v0 route keeps its frozen response shape.
for id, file := range listFiles(false) {
if got, ok := file["oauth_provider"]; ok {
t.Errorf("%s: v0 auth files must not expose oauth_provider, got %#v", id, got)
legacyFiles := listOAuthProviderTestFiles(t, router, "/v0/management/auth-files")
if len(legacyFiles) != len(cases) {
t.Fatalf("v0 files count = %d, want %d", len(legacyFiles), len(cases))
}
for id, file := range legacyFiles {
if value := file.Get("oauth_provider"); value.Exists() {
t.Errorf("%s: v0 must not expose oauth_provider, got %s", id, value.Raw)
}
}
}
func TestAuthFilesOAuthProvider_LoginLifecycle(t *testing.T) {
for _, tc := range []struct {
portal string
provider string
identifiers []string
want string
}{
{portal: "vendor", provider: "vendor", identifiers: []string{"vendor", "vendor-cn"}, want: "vendor"},
{portal: "vendor-cn", provider: "vendor", identifiers: []string{"vendor", "vendor-cn"}, want: "vendor-cn"},
{portal: "single-vendor", provider: "single-vendor", identifiers: []string{"single-vendor"}},
} {
for _, multipleAuths := range []bool{false, true} {
responseKind := "auth"
if multipleAuths {
responseKind = "auths"
}
t.Run(tc.portal+"/"+responseKind, func(t *testing.T) {
authDir := t.TempDir()
state := "state-oauth-provider-" + tc.portal + "-" + responseKind
t.Cleanup(func() { CancelOAuthSession(state) })
provider := &testAuthProvider{
identifier: tc.identifiers[0], identifiers: tc.identifiers,
startLogin: func(_ context.Context, req pluginapi.AuthLoginStartRequest) (pluginapi.AuthLoginStartResponse, error) {
if req.Provider != tc.portal {
t.Fatalf("start provider = %q, want %q", req.Provider, tc.portal)
}
return pluginapi.AuthLoginStartResponse{
Provider: req.Provider, State: state, URL: "https://login.example/" + req.Provider, ExpiresAt: time.Now().Add(time.Hour),
}, nil
},
pollLogin: func(_ context.Context, req pluginapi.AuthLoginPollRequest) (pluginapi.AuthLoginPollResponse, error) {
if req.Provider != tc.portal {
t.Fatalf("poll provider = %q, want %q", req.Provider, tc.portal)
}
data := pluginapi.AuthData{Provider: tc.provider, ID: "account.json", FileName: "account.json"}
resp := pluginapi.AuthLoginPollResponse{Status: pluginapi.AuthLoginStatusSuccess, Auth: data}
if multipleAuths {
resp.Auths = []pluginapi.AuthData{data}
}
return resp, nil
},
}
host := pluginhost.New()
host.RegisterPluginForTest("oauth-provider", pluginapi.Plugin{Capabilities: pluginapi.Capabilities{AuthProvider: provider}})
if got := host.HasMultipleAuthProviders(tc.portal); got != (len(tc.identifiers) > 1) {
t.Fatalf("HasMultipleAuthProviders(%q) = %t", tc.portal, got)
}
// Exercise management conversion independently of the host's stamping.
rawResp, errPoll := provider.PollLogin(context.Background(), pluginapi.AuthLoginPollRequest{Provider: tc.portal})
if errPoll != nil {
t.Fatalf("plugin poll: %v", errPoll)
}
records := pluginLoginPollAuthsWithProvider(host, tc.portal, rawResp)
if len(records) != 1 {
t.Fatalf("management poll records = %d, want 1", len(records))
}
assertOAuthProviderTestAuth(t, records[0], tc.want)
resp, handled, errHostPoll := host.PollLogin(context.Background(), tc.portal, state)
if errHostPoll != nil || !handled {
t.Fatalf("host poll handled=%t error=%v", handled, errHostPoll)
}
assertOAuthProviderTestAuth(t, host.AuthDataToCoreAuth(resp.Auth, "", ""), tc.want)
for _, data := range resp.Auths {
assertOAuthProviderTestAuth(t, host.AuthDataToCoreAuth(data, "", ""), tc.want)
}
manager := coreauth.NewManager(nil, nil, nil)
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir, Port: 8317}, manager)
h.SetPluginHost(host)
router := oauthProviderTestRouter(h)
start := oauthProviderTestGET(t, router, "/v8/management/oauth/auth-url?provider="+tc.portal)
if got := start.Get("state").String(); got != state {
t.Fatalf("login state = %q, want %q: %s", got, state, start.Raw)
}
poll := oauthProviderTestGET(t, router, "/v8/management/get-auth-status?state="+state)
if got := poll.Get("status").String(); got != "ok" {
t.Fatalf("poll status = %q: %s", got, poll.Raw)
}
auth, ok := manager.GetByID("account.json")
if !ok {
t.Fatal("signed-in credential was not registered")
}
if got := authOAuthProvider(auth); got != tc.want {
t.Fatalf("registered oauth_provider = %q, want %q", got, tc.want)
}
if tc.want == "" {
assertOAuthProviderTestAuth(t, auth, "")
}
files := listOAuthProviderTestFiles(t, router, "/v8/management/credentials")
assertOAuthProviderTestFile(t, files, "account.json", tc.provider, tc.want)
saved, errRead := os.ReadFile(filepath.Join(authDir, "account.json"))
if errRead != nil {
t.Fatalf("read saved auth: %v", errRead)
}
value := ojson.GetBytes(saved, "oauth_provider")
if value.String() != tc.want || (tc.want == "" && value.Exists()) {
t.Fatalf("saved oauth_provider = %s, want %q", value.Raw, tc.want)
}
})
}
}
}
func TestPluginLoginPollAuths_PreservesStorageOAuthProviderThroughHost(t *testing.T) {
for _, responseKind := range []string{"auth", "auths"} {
for _, key := range []string{"oauth_provider", "portal"} {
t.Run(responseKind+"/"+key, func(t *testing.T) {
host := pluginhost.New()
host.RegisterPluginForTest("vendor-plugin", pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProvider: &testAuthProvider{
identifier: "vendor", identifiers: []string{"vendor", "vendor-cn"},
pollLogin: func(_ context.Context, req pluginapi.AuthLoginPollRequest) (pluginapi.AuthLoginPollResponse, error) {
if req.Provider != "vendor" {
t.Fatalf("poll provider = %q, want vendor", req.Provider)
}
doc := ojson.NewDocString(`{"type":"vendor"}`)
doc.Set(key, " Vendor-CN ")
data := pluginapi.AuthData{Provider: "vendor", StorageJSON: doc.Bytes()}
resp := pluginapi.AuthLoginPollResponse{Status: pluginapi.AuthLoginStatusSuccess}
if responseKind == "auths" {
resp.Auths = []pluginapi.AuthData{data}
} else {
resp.Auth = data
}
return resp, nil
},
},
}})
resp, handled, errPoll := host.PollLogin(context.Background(), "vendor", "state")
if errPoll != nil || !handled {
t.Fatalf("PollLogin() handled=%t error=%v", handled, errPoll)
}
records := pluginLoginPollAuthsWithProvider(host, "vendor", resp)
if len(records) != 1 {
t.Fatalf("poll records = %d, want 1", len(records))
}
assertOAuthProviderTestAuth(t, records[0], "vendor-cn")
storage := records[0].Storage.(interface{ RawJSON() []byte })
if got := ojson.GetBytes(storage.RawJSON(), "oauth_provider").String(); got != "vendor-cn" {
t.Fatalf("stored oauth_provider = %q, want vendor-cn", got)
}
})
}
}
}
func TestPluginLoginPollAuths_ExplicitOAuthProviderHints(t *testing.T) {
for _, tc := range []struct {
name string
data pluginapi.AuthData
}{
{name: "attribute-oauth", data: pluginapi.AuthData{Attributes: map[string]string{"oauth_provider": " Vendor "}}},
{name: "metadata-oauth", data: pluginapi.AuthData{Metadata: map[string]any{"oauth_provider": " Vendor "}}},
{name: "attribute-portal", data: pluginapi.AuthData{Attributes: map[string]string{"portal": " Vendor "}}},
{name: "metadata-portal", data: pluginapi.AuthData{Metadata: map[string]any{"portal": " Vendor "}}},
{name: "storage-oauth", data: pluginapi.AuthData{StorageJSON: []byte(`{"type":"vendor","oauth_provider":" Vendor "}`)}},
{name: "storage-portal-fallback", data: pluginapi.AuthData{StorageJSON: []byte(`{"oauth_provider":42,"portal":" Vendor "}`)}},
{
name: "attribute-oauth-over-all",
data: pluginapi.AuthData{
Attributes: map[string]string{"oauth_provider": " Vendor ", "portal": "vendor-cn"},
Metadata: map[string]any{"oauth_provider": "vendor-cn", "portal": "vendor-cn"},
StorageJSON: []byte(`{"oauth_provider":"vendor-cn","portal":"vendor-cn"}`),
},
},
{
name: "metadata-oauth-over-attribute-portal",
data: pluginapi.AuthData{
Attributes: map[string]string{"portal": "vendor-cn"},
Metadata: map[string]any{"oauth_provider": " Vendor ", "portal": "vendor-cn"},
StorageJSON: []byte(`{"oauth_provider":"vendor-cn","portal":"vendor-cn"}`),
},
},
{
name: "attribute-portal-over-metadata-portal",
data: pluginapi.AuthData{
Attributes: map[string]string{"portal": " Vendor "},
Metadata: map[string]any{"portal": "vendor-cn"},
StorageJSON: []byte(`{"oauth_provider":"vendor-cn","portal":"vendor-cn"}`),
},
},
{
name: "metadata-portal-over-storage-oauth",
data: pluginapi.AuthData{
Metadata: map[string]any{"portal": " Vendor "},
StorageJSON: []byte(`{"oauth_provider":"vendor-cn","portal":"vendor-cn"}`),
},
},
{name: "storage-oauth-over-storage-portal", data: pluginapi.AuthData{StorageJSON: []byte(`{"oauth_provider":" Vendor ","portal":"vendor-cn"}`)}},
} {
t.Run(tc.name, func(t *testing.T) {
tc.data.Provider = "vendor"
records := pluginLoginPollAuthsWithProvider(pluginhost.New(), "vendor-cn", pluginapi.AuthLoginPollResponse{
Status: pluginapi.AuthLoginStatusSuccess, Auth: tc.data,
})
if len(records) != 1 {
t.Fatalf("poll records = %d, want 1", len(records))
}
assertOAuthProviderTestAuth(t, records[0], "vendor")
})
}
}
func TestAuthFilesOAuthProvider_ColdStartLifecycle(t *testing.T) {
for _, parserKind := range []string{"plugin", "file-fallback", "unhandled-plugin", "core-plugin-parser"} {
t.Run(parserKind, func(t *testing.T) {
authDir := t.TempDir()
path := filepath.Join(authDir, "cold.json")
raw := []byte(`{"type":"vendor","oauth_provider":"vendor"}`)
if errWrite := os.WriteFile(path, raw, 0o600); errWrite != nil {
t.Fatalf("write cold-start auth: %v", errWrite)
}
host := pluginhost.New()
ctx := &synthesizer.SynthesisContext{AuthDir: authDir, Now: time.Now(), StrictFileParsing: true}
switch parserKind {
case "plugin":
host.RegisterPluginForTest("vendor-plugin", pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProvider: &oauthProviderParseTestProvider{testAuthProvider: testAuthProvider{
identifier: "vendor", identifiers: []string{"vendor", "vendor-cn"},
}},
}})
ctx.PluginAuthParser = host
case "unhandled-plugin":
ctx.PluginAuthParser = host
case "core-plugin-parser":
// The synthesizer must also support parsers that omit file attribution.
ctx.PluginAuthParser = oauthProviderFileParser(func(_ context.Context, req pluginapi.AuthParseRequest) (*coreauth.Auth, bool, error) {
auth := host.AuthDataToCoreAuth(pluginapi.AuthData{Provider: "vendor", StorageJSON: []byte(`{"type":"vendor"}`)}, req.Path, req.FileName)
auth.Metadata = nil
return auth, true, nil
})
}
auths, errSynthesize := synthesizer.SynthesizeAuthFile(ctx, path, raw)
if errSynthesize != nil || len(auths) != 1 {
t.Fatalf("SynthesizeAuthFile() count=%d error=%v", len(auths), errSynthesize)
}
auth := auths[0]
if got := authOAuthProvider(auth); got != "vendor" {
t.Fatalf("cold-start oauth_provider = %q, want vendor", got)
}
if parserKind == "plugin" || parserKind == "core-plugin-parser" {
assertOAuthProviderTestAuth(t, auth, "vendor")
storage, ok := auth.Storage.(interface{ RawJSON() []byte })
if !ok || ojson.GetBytes(storage.RawJSON(), "oauth_provider").String() != "vendor" {
t.Fatal("plugin storage did not retain oauth_provider=vendor")
}
}
manager := coreauth.NewManager(nil, nil, nil)
if _, errRegister := manager.Register(context.Background(), auth); errRegister != nil {
t.Fatalf("register synthesized auth: %v", errRegister)
}
h := NewHandlerWithoutConfigFilePath(&config.Config{AuthDir: authDir}, manager)
files := listOAuthProviderTestFiles(t, oauthProviderTestRouter(h), "/v8/management/credentials")
assertOAuthProviderTestFile(t, files, auth.ID, "vendor", "vendor")
})
}
}
type oauthProviderParseTestProvider struct {
testAuthProvider
}
func (p *oauthProviderParseTestProvider) ParseAuth(_ context.Context, req pluginapi.AuthParseRequest) (pluginapi.AuthParseResponse, error) {
return pluginapi.AuthParseResponse{Handled: true, Auth: pluginapi.AuthData{Provider: req.Provider, StorageJSON: req.RawJSON}}, nil
}
type oauthProviderFileParser func(context.Context, pluginapi.AuthParseRequest) (*coreauth.Auth, bool, error)
func (f oauthProviderFileParser) ParseAuth(ctx context.Context, req pluginapi.AuthParseRequest) (*coreauth.Auth, bool, error) {
return f(ctx, req)
}
func oauthProviderTestRouter(h *Handler) *gin.Engine {
router := gin.New()
v8 := router.Group("/v8/management", func(c *gin.Context) {
c.Set(ConfigV8ContextKey, true)
c.Next()
})
v8.GET("/credentials", h.ListAuthFiles)
v8.GET("/oauth/auth-url", h.StartOAuthV8)
v8.GET("/get-auth-status", h.GetAuthStatus)
router.GET("/v0/management/auth-files", h.ListAuthFiles)
return router
}
func oauthProviderTestGET(t *testing.T, router http.Handler, path string) ojson.Result {
t.Helper()
rec := httptest.NewRecorder()
router.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
if rec.Code != http.StatusOK || !ojson.ValidBytes(rec.Body.Bytes()) {
t.Fatalf("GET %s status=%d body=%s", path, rec.Code, rec.Body.String())
}
return ojson.Parse(rec.Body.String())
}
func listOAuthProviderTestFiles(t *testing.T, router http.Handler, path string) map[string]ojson.Result {
t.Helper()
resp := oauthProviderTestGET(t, router, path)
files := resp.Get("files")
if !files.IsArray() || len(files.Array()) == 0 {
t.Fatalf("GET %s returned no files: %s", path, resp.Raw)
}
out := make(map[string]ojson.Result)
for _, file := range files.Array() {
out[file.Get("id").String()] = file
}
return out
}
func assertOAuthProviderTestFile(t *testing.T, files map[string]ojson.Result, id, provider, want string) {
t.Helper()
file, ok := files[id]
if !ok {
t.Fatalf("missing credential %s", id)
}
value := file.Get("oauth_provider")
if value.String() != want || (want == "" && value.Exists()) {
t.Errorf("%s: oauth_provider = %s, want %q", id, value.Raw, want)
}
if file.Get("type").String() != provider || file.Get("provider").String() != provider {
t.Errorf("%s: credential provider changed: %s", id, file.Raw)
}
}
func assertOAuthProviderTestAuth(t *testing.T, auth *coreauth.Auth, want string) {
t.Helper()
if auth == nil {
t.Fatal("missing auth")
}
if want == "" {
for _, key := range []string{"oauth_provider", "portal"} {
if value, exists := auth.Metadata[key]; exists {
t.Errorf("single-entry metadata must omit %s, got %#v", key, value)
}
if value, exists := auth.Attributes[key]; exists {
t.Errorf("single-entry attributes must omit %s, got %q", key, value)
}
}
return
}
if auth.Metadata["oauth_provider"] != want || auth.Attributes["oauth_provider"] != want {
t.Errorf("oauth_provider metadata=%#v attributes=%q, want %q", auth.Metadata["oauth_provider"], auth.Attributes["oauth_provider"], want)
}
}

View File

@@ -14,6 +14,7 @@ import (
"strings"
"time"
"github.com/MoeForge/moego/ojson"
"github.com/gin-gonic/gin"
"github.com/router-for-me/CLIProxyAPI/v8/internal/auth/antigravity"
"github.com/router-for-me/CLIProxyAPI/v8/internal/auth/claude"
@@ -1568,10 +1569,12 @@ func pluginLoginPollAuthsWithProvider(host *pluginhost.Host, provider string, re
authData.Provider = trimmedSessionProvider
}
effectivePortal := trimmedSessionProvider
hasExplicitHint := false
for _, key := range []string{"oauth_provider", "portal"} {
if authData.Attributes != nil {
if v := strings.ToLower(strings.TrimSpace(authData.Attributes[key])); v != "" {
effectivePortal = v
hasExplicitHint = true
break
}
}
@@ -1579,24 +1582,34 @@ func pluginLoginPollAuthsWithProvider(host *pluginhost.Host, provider string, re
if raw, ok := authData.Metadata[key].(string); ok {
if v := strings.ToLower(strings.TrimSpace(raw)); v != "" {
effectivePortal = v
hasExplicitHint = true
break
}
}
}
}
if effectivePortal != "" && !strings.EqualFold(strings.TrimSpace(authData.Provider), effectivePortal) {
if !hasExplicitHint && ojson.ValidBytes(authData.StorageJSON) {
for _, key := range []string{"oauth_provider", "portal"} {
value := ojson.GetBytes(authData.StorageJSON, key)
if value.Type == ojson.String {
if hint := strings.ToLower(strings.TrimSpace(value.String())); hint != "" {
effectivePortal = hint
hasExplicitHint = true
break
}
}
}
}
isMultiEntry := host.HasMultipleAuthProviders(effectivePortal) || host.HasMultipleAuthProviders(authData.Provider)
if effectivePortal != "" && (!strings.EqualFold(strings.TrimSpace(authData.Provider), effectivePortal) || hasExplicitHint || isMultiEntry) {
if authData.Metadata == nil {
authData.Metadata = make(map[string]any)
}
if _, exists := authData.Metadata["oauth_provider"]; !exists {
authData.Metadata["oauth_provider"] = effectivePortal
}
authData.Metadata["oauth_provider"] = effectivePortal
if authData.Attributes == nil {
authData.Attributes = make(map[string]string)
}
if strings.TrimSpace(authData.Attributes["oauth_provider"]) == "" {
authData.Attributes["oauth_provider"] = effectivePortal
}
authData.Attributes["oauth_provider"] = effectivePortal
}
record := host.AuthDataToCoreAuth(authData, "", "")
if record == nil {

View File

@@ -1142,6 +1142,7 @@ func (a *executorAdapter) Refresh(ctx context.Context, auth *coreauth.Auth) (ref
return nil, errRefresh
}
data := pluginResp.Auth
explicitPortalHint := authDataPortalHint(&data)
if strings.TrimSpace(data.Provider) == "" {
data.Provider = authProvider(auth)
}
@@ -1176,7 +1177,7 @@ func (a *executorAdapter) Refresh(ctx context.Context, auth *coreauth.Auth) (ref
}
data.Attributes = attributes
}
preserveAuthOAuthProviderMetadata(&data, auth)
preserveAuthOAuthProviderMetadata(&data, auth, explicitPortalHint)
preserveFileAuthPriority(&data, auth)
preserveAuthDisabledState(&data, auth)
if len(data.StorageJSON) == 0 {

View File

@@ -12,6 +12,7 @@ import (
"strings"
"time"
"github.com/MoeForge/moego/ojson"
"github.com/router-for-me/CLIProxyAPI/v8/internal/config"
coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi"
@@ -209,6 +210,20 @@ func (h *Host) HasAuthProvider(provider string) bool {
return h.authProviderRecord(provider) != nil
}
// HasMultipleAuthProviders reports whether the active owning plugin declares multiple OAuth entries.
func (h *Host) HasMultipleAuthProviders(provider string) bool {
record := h.authProviderRecord(provider)
return record != nil && h.recordHasMultipleAuthProviders(*record)
}
func (h *Host) recordHasMultipleAuthProviders(record capabilityRecord) bool {
if h == nil || !h.recordCurrent(record) {
return false
}
identifiers, okIdentifiers := h.callRecordAuthProviderIdentifiers(record)
return okIdentifiers && len(identifiers) > 1
}
// SameAuthProvider reports whether providerA and providerB belong to the same active plugin auth provider.
func (h *Host) SameAuthProvider(providerA, providerB string) bool {
providerA = normalizeProviderID(providerA)
@@ -500,16 +515,12 @@ func (h *Host) ParseAuth(ctx context.Context, req pluginapi.AuthParseRequest) (*
}
func extractRawJSONOAuthProviderHint(raw []byte) string {
if len(bytes.TrimSpace(raw)) == 0 {
return ""
}
var payload map[string]any
if errUnmarshal := json.Unmarshal(raw, &payload); errUnmarshal != nil || payload == nil {
if !ojson.ValidBytes(raw) {
return ""
}
for _, key := range []string{"oauth_provider", "portal"} {
if value, ok := payload[key].(string); ok {
if normalized := normalizeProviderID(value); normalized != "" {
if value := ojson.GetBytes(raw, key); value.Type == ojson.String {
if normalized := normalizeProviderID(value.String()); normalized != "" {
return normalized
}
}
@@ -618,6 +629,7 @@ func (h *Host) callSingleProviderParseAuths(ctx context.Context, record capabili
return nil, false, nil
}
datas := pluginAuthParseResponseAuths(resp)
multiEntry := h.recordHasMultipleAuthProviders(record)
auths = make([]*coreauth.Auth, 0, len(datas))
for _, data := range datas {
if strings.TrimSpace(data.Provider) == "" {
@@ -629,8 +641,11 @@ func (h *Host) callSingleProviderParseAuths(ctx context.Context, record capabili
if normalizeProviderID(data.Provider) == "" {
return nil, true, fmt.Errorf("auth provider %s returned auth without provider", record.id)
}
effectivePortal := firstNonEmpty(authDataPortalHint(&data), portalIdentifier)
stampAuthDataOAuthProvider(&data, effectivePortal)
explicitHint := firstNonEmpty(authDataPortalHint(&data), extractRawJSONOAuthProviderHint(req.RawJSON))
effectivePortal := firstNonEmpty(explicitHint, portalIdentifier)
if explicitHint != "" || multiEntry || normalizeProviderID(data.Provider) != effectivePortal {
stampAuthDataOAuthProvider(&data, effectivePortal)
}
parsed := h.AuthDataToCoreAuth(data, req.Path, req.FileName)
if parsed == nil {
return nil, true, fmt.Errorf("auth provider %s returned invalid auth data", record.id)
@@ -825,12 +840,21 @@ func (h *Host) callPollLogin(ctx context.Context, record capabilityRecord, provi
return pluginapi.AuthLoginPollResponse{}, true, errPoll
}
if resp.Status == pluginapi.AuthLoginStatusSuccess {
multiEntry := h.recordHasMultipleAuthProviders(record)
for index := range resp.Auths {
stampAuthDataOAuthProvider(&resp.Auths[index], matchedPortal)
h.recordCredentialProvider(record.id, resp.Auths[index].Provider, matchedPortal)
explicitHint := authDataPortalHint(&resp.Auths[index])
effectivePortal := firstNonEmpty(explicitHint, matchedPortal)
if multiEntry || explicitHint != "" || normalizeProviderID(resp.Auths[index].Provider) != effectivePortal {
stampAuthDataOAuthProvider(&resp.Auths[index], effectivePortal)
}
h.recordCredentialProvider(record.id, resp.Auths[index].Provider, effectivePortal)
}
stampAuthDataOAuthProvider(&resp.Auth, matchedPortal)
h.recordCredentialProvider(record.id, resp.Auth.Provider, matchedPortal)
explicitHint := authDataPortalHint(&resp.Auth)
effectivePortal := firstNonEmpty(explicitHint, matchedPortal)
if multiEntry || explicitHint != "" || normalizeProviderID(resp.Auth.Provider) != effectivePortal {
stampAuthDataOAuthProvider(&resp.Auth, effectivePortal)
}
h.recordCredentialProvider(record.id, resp.Auth.Provider, effectivePortal)
}
return resp, true, nil
}
@@ -853,7 +877,7 @@ func authDataPortalHint(data *pluginapi.AuthData) string {
}
}
}
return ""
return extractRawJSONOAuthProviderHint(data.StorageJSON)
}
func stampAuthDataOAuthProvider(data *pluginapi.AuthData, portalIdentifier string) {
@@ -864,22 +888,17 @@ func stampAuthDataOAuthProvider(data *pluginapi.AuthData, portalIdentifier strin
if portalIdentifier == "" {
return
}
credProvider := normalizeProviderID(data.Provider)
if credProvider == "" || credProvider == portalIdentifier {
if normalizeProviderID(data.Provider) == "" {
return
}
if data.Metadata == nil {
data.Metadata = make(map[string]any)
}
if _, exists := data.Metadata["oauth_provider"]; !exists {
data.Metadata["oauth_provider"] = portalIdentifier
}
data.Metadata["oauth_provider"] = portalIdentifier
if data.Attributes == nil {
data.Attributes = make(map[string]string)
}
if strings.TrimSpace(data.Attributes["oauth_provider"]) == "" {
data.Attributes["oauth_provider"] = portalIdentifier
}
data.Attributes["oauth_provider"] = portalIdentifier
}
func authPortalHints(auth *coreauth.Auth) []string {
@@ -972,6 +991,7 @@ func (h *Host) RefreshAuth(ctx context.Context, auth *coreauth.Auth) (refreshed
return nil, true, errRefresh
}
data := pluginResp.Auth
explicitPortalHint := authDataPortalHint(&data)
if strings.TrimSpace(data.Provider) == "" {
data.Provider = authProvider(auth)
}
@@ -1006,7 +1026,7 @@ func (h *Host) RefreshAuth(ctx context.Context, auth *coreauth.Auth) (refreshed
}
data.Attributes = attributes
}
preserveAuthOAuthProviderMetadata(&data, auth)
preserveAuthOAuthProviderMetadata(&data, auth, explicitPortalHint)
preserveFileAuthPriority(&data, auth)
preserveAuthDisabledState(&data, auth)
if len(data.StorageJSON) == 0 {
@@ -1031,10 +1051,19 @@ func (h *Host) RefreshAuth(ctx context.Context, auth *coreauth.Auth) (refreshed
return next, true, nil
}
func preserveAuthOAuthProviderMetadata(data *pluginapi.AuthData, auth *coreauth.Auth) {
if data == nil || auth == nil || len(auth.Metadata) == 0 {
// explicitPortalHint must be resolved before merging existing auth fields.
func preserveAuthOAuthProviderMetadata(data *pluginapi.AuthData, auth *coreauth.Auth, explicitPortalHint string) {
if data == nil || auth == nil {
return
}
hint := explicitPortalHint
if hint == "" {
hint = authDataPortalHint(&pluginapi.AuthData{
Attributes: auth.Attributes,
Metadata: auth.Metadata,
StorageJSON: storageJSONFromAuth(auth),
})
}
for _, key := range []string{"oauth_provider", "portal"} {
raw, ok := auth.Metadata[key].(string)
if !ok || strings.TrimSpace(raw) == "" {
@@ -1047,6 +1076,17 @@ func preserveAuthOAuthProviderMetadata(data *pluginapi.AuthData, auth *coreauth.
data.Metadata[key] = raw
}
}
if hint == "" {
return
}
if data.Metadata == nil {
data.Metadata = make(map[string]any)
}
data.Metadata["oauth_provider"] = hint
if data.Attributes == nil {
data.Attributes = make(map[string]string)
}
data.Attributes["oauth_provider"] = hint
}
func preserveAuthDisabledState(data *pluginapi.AuthData, auth *coreauth.Auth) {
@@ -1248,6 +1288,10 @@ func pluginAuthDataToCoreAuth(data pluginapi.AuthData, path, fileName string, au
if attributes == nil {
attributes = make(map[string]string)
}
if hint := authDataPortalHint(&data); hint != "" {
metadata["oauth_provider"] = hint
attributes["oauth_provider"] = hint
}
path = strings.TrimSpace(path)
if path != "" {
if attributes[coreauth.AttributePath] == "" {

View File

@@ -0,0 +1,381 @@
package pluginhost
import (
"bytes"
"context"
"os"
"path/filepath"
"testing"
"github.com/MoeForge/moego/ojson"
coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi"
)
func TestHasMultipleAuthProviders(t *testing.T) {
host := newHostWithRecords(
capabilityRecord{id: "multi", plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProvider: fakeAuthProvider{identifier: "vendor", identifiers: []string{"vendor", "vendor-cn"}, credentialProviders: []string{"canonical-vendor"}},
}}},
capabilityRecord{id: "separate", plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProviders: []pluginapi.AuthProvider{fakeAuthProvider{identifier: "portal-one"}, fakeAuthProvider{identifier: "portal-two"}},
}}},
capabilityRecord{id: "single", plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProvider: fakeAuthProvider{identifier: "single-vendor", identifiers: []string{"single-vendor", " SINGLE-VENDOR ", ""}},
}}},
)
for _, tc := range []struct {
provider string
want bool
}{
{provider: " Vendor ", want: true},
{provider: "vendor-cn", want: true},
{provider: "canonical-vendor", want: true},
{provider: "portal-one", want: true},
{provider: "portal-two", want: true},
{provider: "single-vendor"},
{provider: "missing"},
{},
} {
if got := host.HasMultipleAuthProviders(tc.provider); got != tc.want {
t.Errorf("HasMultipleAuthProviders(%q) = %t, want %t", tc.provider, got, tc.want)
}
}
var nilHost *Host
if nilHost.HasMultipleAuthProviders("vendor") {
t.Fatal("nil host reports multiple auth providers")
}
record := host.authProviderRecord("vendor")
setHostSnapshotForTest(host, false)
if host.HasMultipleAuthProviders("vendor") || host.recordHasMultipleAuthProviders(*record) {
t.Fatal("inactive plugin reports multiple auth providers")
}
}
func TestParseAuthsOAuthProviderAttribution(t *testing.T) {
for _, tc := range []struct {
name string
request string
identifiers []string
data pluginapi.AuthData
raw []byte
want string
}{
{name: "multi-primary", request: "vendor", identifiers: []string{"vendor", "vendor-cn"}, want: "vendor"},
{name: "multi-secondary", request: "vendor-cn", identifiers: []string{"vendor", "vendor-cn"}, want: "vendor-cn"},
{name: "single-without-hint", request: "vendor", identifiers: []string{"vendor"}},
{name: "attribute-hint", request: "vendor", identifiers: []string{"vendor"}, data: pluginapi.AuthData{Attributes: map[string]string{"oauth_provider": " Vendor "}}, want: "vendor"},
{name: "metadata-hint", request: "vendor", identifiers: []string{"vendor"}, data: pluginapi.AuthData{Metadata: map[string]any{"portal": " Vendor "}}, want: "vendor"},
{name: "storage-hint", request: "vendor", identifiers: []string{"vendor"}, data: pluginapi.AuthData{StorageJSON: []byte(`{"oauth_provider":" Vendor "}`)}, want: "vendor"},
{name: "raw-hint", request: "vendor", identifiers: []string{"vendor"}, raw: []byte(`{"oauth_provider":" Vendor "}`), want: "vendor"},
{
name: "data-over-storage-over-request", request: "vendor", identifiers: []string{"vendor", "vendor-cn"},
data: pluginapi.AuthData{Attributes: map[string]string{"portal": " Vendor "}, StorageJSON: []byte(`{"oauth_provider":"vendor-cn"}`)},
raw: []byte(`{"oauth_provider":"vendor-cn"}`), want: "vendor",
},
{
name: "storage-over-request", request: "vendor", identifiers: []string{"vendor", "vendor-cn"},
data: pluginapi.AuthData{StorageJSON: []byte(`{"oauth_provider":true,"portal":" Vendor-CN "}`)},
raw: []byte(`{"oauth_provider":"vendor"}`), want: "vendor-cn",
},
} {
t.Run(tc.name, func(t *testing.T) {
host := newHostWithRecords(capabilityRecord{id: "vendor-plugin", plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProvider: fakeAuthProvider{
identifier: "vendor", identifiers: tc.identifiers,
parseAuth: func(context.Context, pluginapi.AuthParseRequest) (pluginapi.AuthParseResponse, error) {
data := tc.data
data.Provider = "vendor"
return pluginapi.AuthParseResponse{Handled: true, Auth: data}, nil
},
},
}}})
auths, handled, errParse := host.ParseAuths(context.Background(), pluginapi.AuthParseRequest{Provider: tc.request, RawJSON: tc.raw})
if errParse != nil || !handled || len(auths) != 1 {
t.Fatalf("ParseAuths() handled=%t count=%d error=%v", handled, len(auths), errParse)
}
auth := auths[0]
if tc.want == "" {
if _, exists := auth.Metadata["oauth_provider"]; exists {
t.Errorf("single-entry parser added metadata: %#v", auth.Metadata)
}
if _, exists := auth.Attributes["oauth_provider"]; exists {
t.Errorf("single-entry parser added attributes: %#v", auth.Attributes)
}
} else if auth.Metadata["oauth_provider"] != tc.want || auth.Attributes["oauth_provider"] != tc.want {
t.Errorf("parsed attribution metadata=%#v attributes=%#v, want %q", auth.Metadata, auth.Attributes, tc.want)
}
})
}
}
func TestPluginAuthDataToCoreAuthStorageOAuthProvider(t *testing.T) {
for _, tc := range []struct {
name string
data pluginapi.AuthData
want string
}{
{name: "raw-oauth", data: pluginapi.AuthData{StorageJSON: []byte(`{"oauth_provider":" Vendor "}`)}, want: "vendor"},
{name: "raw-portal", data: pluginapi.AuthData{StorageJSON: []byte(`{"oauth_provider":" ","portal":" Vendor-CN "}`)}, want: "vendor-cn"},
{name: "invalid-hints-fall-back", data: pluginapi.AuthData{Metadata: map[string]any{"oauth_provider": 42}, Attributes: map[string]string{"portal": " "}, StorageJSON: []byte(`{"oauth_provider":"vendor"}`)}, want: "vendor"},
{name: "metadata-wins", data: pluginapi.AuthData{Metadata: map[string]any{"portal": "vendor-cn"}, StorageJSON: []byte(`{"oauth_provider":"vendor"}`)}, want: "vendor-cn"},
{name: "attributes-win", data: pluginapi.AuthData{Attributes: map[string]string{"oauth_provider": "vendor-cn"}, StorageJSON: []byte(`{"oauth_provider":"vendor"}`)}, want: "vendor-cn"},
{name: "invalid-json", data: pluginapi.AuthData{StorageJSON: []byte(`{"oauth_provider":"vendor"`)}},
{name: "non-string", data: pluginapi.AuthData{StorageJSON: []byte(`{"oauth_provider":42,"portal":true}`)}},
} {
t.Run(tc.name, func(t *testing.T) {
tc.data.Provider = "vendor"
auth := pluginAuthDataToCoreAuth(tc.data, "", "", "")
hint := authDataPortalHint(&pluginapi.AuthData{Metadata: auth.Metadata, Attributes: auth.Attributes})
if hint != tc.want {
t.Fatalf("converted hint = %q, want %q", hint, tc.want)
}
if tc.want != "" {
if auth.Metadata["oauth_provider"] != tc.want || auth.Attributes["oauth_provider"] != tc.want {
t.Fatalf("hint not copied to both maps: metadata=%#v attributes=%#v", auth.Metadata, auth.Attributes)
}
}
})
}
}
func TestPreserveAuthOAuthProviderFromAttributes(t *testing.T) {
for _, key := range []string{"oauth_provider", "portal"} {
for _, metadata := range []map[string]any{nil, {"access_token": "old"}, {"oauth_provider": " ", "portal": true}} {
t.Run(key, func(t *testing.T) {
auth := &coreauth.Auth{Provider: "vendor", Metadata: metadata, Attributes: map[string]string{key: " Vendor "}}
data := pluginapi.AuthData{Provider: "vendor", Metadata: map[string]any{"access_token": "new"}}
preserveAuthOAuthProviderMetadata(&data, auth, authDataPortalHint(&data))
if data.Metadata["oauth_provider"] != "vendor" || data.Attributes["oauth_provider"] != "vendor" {
t.Fatalf("preserved metadata=%#v attributes=%#v, want vendor", data.Metadata, data.Attributes)
}
if data.Metadata["access_token"] != "new" {
t.Fatal("preservation replaced refreshed token")
}
})
}
}
}
func TestPollLoginRecordsEffectiveOAuthProvider(t *testing.T) {
for _, responseKind := range []string{"auth", "auths"} {
t.Run(responseKind, func(t *testing.T) {
host := newHostWithRecords(capabilityRecord{id: "vendor-plugin", plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProvider: fakeAuthProvider{
identifier: "vendor", identifiers: []string{"vendor", "vendor-cn"},
pollLogin: func(context.Context, pluginapi.AuthLoginPollRequest) (pluginapi.AuthLoginPollResponse, error) {
data := pluginapi.AuthData{Provider: "vendor", StorageJSON: []byte(`{"oauth_provider":"vendor-cn"}`)}
resp := pluginapi.AuthLoginPollResponse{Status: pluginapi.AuthLoginStatusSuccess}
if responseKind == "auths" {
resp.Auths = []pluginapi.AuthData{data}
} else {
resp.Auth = data
}
return resp, nil
},
},
}}})
_, handled, errPoll := host.PollLogin(context.Background(), "vendor", "state")
if errPoll != nil || !handled {
t.Fatalf("PollLogin() handled=%t error=%v", handled, errPoll)
}
if got, ok := host.recordedCredentialProviderPortal("vendor-plugin", "vendor"); !ok || got != "vendor-cn" {
t.Fatalf("recorded portal = %q, present=%t, want vendor-cn", got, ok)
}
})
}
}
func TestExecutorAdapterRefreshOAuthProvider(t *testing.T) {
for _, tc := range []struct {
name string
metadata map[string]any
want string
}{
{name: "existing-effective-hint", metadata: map[string]any{"access_token": "new"}, want: "vendor"},
{name: "plugin-explicit-hint", metadata: map[string]any{"oauth_provider": "vendor-cn", "access_token": "new"}, want: "vendor-cn"},
} {
t.Run(tc.name, func(t *testing.T) {
record := normalizeTestCapabilityRecord(capabilityRecord{id: "vendor-plugin", plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProvider: fakeAuthProvider{
identifier: "vendor", identifiers: []string{"vendor", "vendor-cn"},
refreshAuth: func(context.Context, pluginapi.AuthRefreshRequest) (pluginapi.AuthRefreshResponse, error) {
return pluginapi.AuthRefreshResponse{Auth: pluginapi.AuthData{Metadata: tc.metadata}}, nil
},
},
}}})
host := newHostWithRecords(record)
adapter := newExecutorAdapterForRecordForTest(host, record, &fakeExecutor{}, nil, nil)
refreshed, errRefresh := adapter.Refresh(context.Background(), &coreauth.Auth{
Provider: "vendor", Attributes: map[string]string{"oauth_provider": "vendor"}, Metadata: map[string]any{"portal": "vendor-cn"},
})
if errRefresh != nil || refreshed == nil {
t.Fatalf("Refresh() auth=%#v error=%v", refreshed, errRefresh)
}
if refreshed.Metadata["oauth_provider"] != tc.want || refreshed.Attributes["oauth_provider"] != tc.want {
t.Fatalf("refreshed attribution metadata=%#v attributes=%#v, want %q", refreshed.Metadata, refreshed.Attributes, tc.want)
}
storage := refreshed.Storage.(interface{ RawJSON() []byte })
if got := ojson.GetBytes(storage.RawJSON(), "oauth_provider").String(); got != tc.want {
t.Fatalf("refreshed storage hint = %q, want %q", got, tc.want)
}
})
}
}
func TestRefreshAuthOAuthProviderSurvivesColdStart(t *testing.T) {
for _, tc := range []struct {
name string
attributes map[string]string
metadata map[string]any
rawJSON []byte
response pluginapi.AuthData
want string
}{
{
name: "attribute-oauth-over-metadata-portal",
attributes: map[string]string{"oauth_provider": "vendor"},
metadata: map[string]any{"portal": "vendor-cn"},
want: "vendor",
},
{
name: "metadata-oauth-over-attribute-portal",
attributes: map[string]string{"portal": "vendor-cn"},
metadata: map[string]any{"oauth_provider": "vendor"},
want: "vendor",
},
{
name: "attribute-portal-over-metadata-portal",
attributes: map[string]string{"portal": "vendor"},
metadata: map[string]any{"portal": "vendor-cn"},
want: "vendor",
},
{
name: "metadata-portal-over-storage-oauth",
metadata: map[string]any{"portal": "vendor"},
rawJSON: []byte(`{"oauth_provider":"vendor-cn"}`),
want: "vendor",
},
{
name: "storage-only",
rawJSON: []byte(`{"oauth_provider":"vendor-cn"}`),
want: "vendor-cn",
},
{
name: "plugin-attribute-oauth-over-existing",
attributes: map[string]string{"oauth_provider": "vendor"},
metadata: map[string]any{"oauth_provider": "vendor"},
response: pluginapi.AuthData{Attributes: map[string]string{"oauth_provider": "vendor-cn"}},
want: "vendor-cn",
},
{
name: "plugin-metadata-oauth-over-existing",
attributes: map[string]string{"oauth_provider": "vendor"},
response: pluginapi.AuthData{Metadata: map[string]any{"oauth_provider": "vendor-cn"}},
want: "vendor-cn",
},
{
name: "plugin-attribute-portal-over-existing",
attributes: map[string]string{"oauth_provider": "vendor"},
response: pluginapi.AuthData{Attributes: map[string]string{"portal": "vendor-cn"}},
want: "vendor-cn",
},
{
name: "plugin-metadata-portal-over-existing",
attributes: map[string]string{"oauth_provider": "vendor"},
response: pluginapi.AuthData{Metadata: map[string]any{"portal": "vendor-cn"}},
want: "vendor-cn",
},
{
name: "plugin-storage-oauth-over-existing",
attributes: map[string]string{"oauth_provider": "vendor"},
metadata: map[string]any{"portal": "vendor"},
response: pluginapi.AuthData{StorageJSON: []byte(`{"oauth_provider":"vendor-cn"}`)},
want: "vendor-cn",
},
} {
t.Run(tc.name, func(t *testing.T) {
newHost := func() *Host {
return newHostWithRecords(capabilityRecord{id: "vendor-plugin", plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProvider: fakeAuthProvider{
identifier: "vendor", identifiers: []string{"vendor", "vendor-cn"},
refreshAuth: func(context.Context, pluginapi.AuthRefreshRequest) (pluginapi.AuthRefreshResponse, error) {
data := tc.response
data.Metadata = cloneAnyMap(data.Metadata)
if data.Metadata == nil {
data.Metadata = make(map[string]any)
}
data.Metadata["access_token"] = "new"
return pluginapi.AuthRefreshResponse{Auth: data}, nil
},
parseAuth: func(_ context.Context, req pluginapi.AuthParseRequest) (pluginapi.AuthParseResponse, error) {
return pluginapi.AuthParseResponse{Handled: true, Auth: pluginapi.AuthData{Provider: "vendor", StorageJSON: req.RawJSON}}, nil
},
},
}}})
}
auth := &coreauth.Auth{Provider: "vendor", Attributes: tc.attributes, Metadata: tc.metadata}
if len(tc.rawJSON) > 0 {
auth.Storage = &pluginTokenStorage{provider: "vendor", rawJSON: tc.rawJSON}
}
refreshed, handled, errRefresh := newHost().RefreshAuth(context.Background(), auth)
if errRefresh != nil || !handled || refreshed == nil {
t.Fatalf("RefreshAuth() handled=%t auth=%#v error=%v", handled, refreshed, errRefresh)
}
if refreshed.Metadata["oauth_provider"] != tc.want || refreshed.Attributes["oauth_provider"] != tc.want {
t.Fatalf("refreshed attribution metadata=%#v attributes=%#v, want %q", refreshed.Metadata, refreshed.Attributes, tc.want)
}
if refreshed.Metadata["access_token"] != "new" {
t.Fatal("refresh lost the updated token")
}
raw := refreshed.Storage.(interface{ RawJSON() []byte }).RawJSON()
if got := ojson.GetBytes(raw, "oauth_provider").String(); got != tc.want {
t.Fatalf("refreshed storage hint = %q, want %q", got, tc.want)
}
path := filepath.Join(t.TempDir(), "account.json")
if errSaveTokenToFile := refreshed.Storage.SaveTokenToFile(path); errSaveTokenToFile != nil {
t.Fatalf("save refreshed auth: %v", errSaveTokenToFile)
}
saved, errRead := os.ReadFile(path)
if errRead != nil {
t.Fatalf("read saved auth: %v", errRead)
}
if !bytes.Equal(saved, raw) {
t.Fatalf("saved payload = %s, want RawJSON() %s", saved, raw)
}
reloaded, handled, errParse := newHost().ParseAuth(context.Background(), pluginapi.AuthParseRequest{
Provider: "vendor", Path: path, FileName: "account.json", RawJSON: saved,
})
if errParse != nil || !handled || reloaded == nil {
t.Fatalf("cold-start ParseAuth() handled=%t auth=%#v error=%v", handled, reloaded, errParse)
}
if reloaded.Metadata["oauth_provider"] != tc.want || reloaded.Attributes["oauth_provider"] != tc.want {
t.Fatalf("cold-start attribution metadata=%#v attributes=%#v, want %q", reloaded.Metadata, reloaded.Attributes, tc.want)
}
})
}
}
func TestRefreshAuthPreservesAttributeOnlyOAuthProvider(t *testing.T) {
host := newHostWithRecords(capabilityRecord{id: "vendor-plugin", plugin: pluginapi.Plugin{Capabilities: pluginapi.Capabilities{
AuthProvider: fakeAuthProvider{
identifier: "vendor", identifiers: []string{"vendor", "vendor-cn"},
refreshAuth: func(context.Context, pluginapi.AuthRefreshRequest) (pluginapi.AuthRefreshResponse, error) {
return pluginapi.AuthRefreshResponse{Auth: pluginapi.AuthData{Provider: "vendor", Metadata: map[string]any{"access_token": "new"}}}, nil
},
},
}}})
auth, handled, errRefresh := host.RefreshAuth(context.Background(), &coreauth.Auth{
Provider: "vendor", Attributes: map[string]string{"portal": " Vendor "},
})
if errRefresh != nil || !handled || auth == nil {
t.Fatalf("RefreshAuth() handled=%t auth=%#v error=%v", handled, auth, errRefresh)
}
if auth.Metadata["oauth_provider"] != "vendor" || auth.Attributes["oauth_provider"] != "vendor" {
t.Fatalf("refreshed attribution metadata=%#v attributes=%#v", auth.Metadata, auth.Attributes)
}
storage := auth.Storage.(interface{ RawJSON() []byte })
if got := ojson.GetBytes(storage.RawJSON(), "oauth_provider").String(); got != "vendor" {
t.Fatalf("refreshed storage hint = %q, want vendor", got)
}
}

View File

@@ -126,6 +126,15 @@ func synthesizeFileAuths(ctx *SynthesisContext, fullPath string, data []byte) ([
if len(auths) == 0 {
return nil, nil
}
filePortalHint := ""
for _, key := range []string{"oauth_provider", "portal"} {
if raw, ok := metadata[key].(string); ok {
if hint := strings.ToLower(strings.TrimSpace(raw)); hint != "" {
filePortalHint = hint
break
}
}
}
perAccountModelAliases := extractOAuthModelAliasesFromMetadata(metadata)
disabled, _ := metadata["disabled"].(bool)
for index, auth := range auths {
@@ -133,6 +142,29 @@ func synthesizeFileAuths(ctx *SynthesisContext, fullPath string, data []byte) ([
continue
}
coreauth.NormalizeCredentialMetadata(auth.Metadata)
if filePortalHint != "" {
hasPortalHint := false
for _, key := range []string{"oauth_provider", "portal"} {
raw, _ := auth.Metadata[key].(string)
if strings.TrimSpace(auth.Attributes[key]) != "" || strings.TrimSpace(raw) != "" {
hasPortalHint = true
break
}
}
if !hasPortalHint {
if auth.Metadata == nil {
auth.Metadata = make(map[string]any)
}
if auth.Attributes == nil {
auth.Attributes = make(map[string]string)
}
auth.Metadata["oauth_provider"] = filePortalHint
auth.Attributes["oauth_provider"] = filePortalHint
if setter, ok := auth.Storage.(interface{ SetMetadata(map[string]any) }); ok {
setter.SetMetadata(auth.Metadata)
}
}
}
if len(auths) > 1 {
coreauth.MarkPluginVirtualAuth(auth, fullPath, index)
}

View File

@@ -0,0 +1,88 @@
package synthesizer
import (
"context"
"path/filepath"
"testing"
"time"
coreauth "github.com/router-for-me/CLIProxyAPI/v8/sdk/cliproxy/auth"
"github.com/router-for-me/CLIProxyAPI/v8/sdk/pluginapi"
)
func TestSynthesizeAuthFilePluginOAuthProviderHint(t *testing.T) {
for _, tc := range []struct {
name string
raw string
attributes map[string]string
metadata map[string]any
want string
inherit bool
}{
{name: "primary", raw: `{"type":"vendor","oauth_provider":" Vendor "}`, want: "vendor", inherit: true},
{name: "oauth-before-portal", raw: `{"type":"vendor","oauth_provider":" Vendor ","portal":"vendor-cn"}`, want: "vendor", inherit: true},
{name: "blank-oauth-fallback", raw: `{"type":"vendor","oauth_provider":" ","portal":" Vendor-CN "}`, want: "vendor-cn", inherit: true},
{name: "non-string-oauth-fallback", raw: `{"type":"vendor","oauth_provider":42,"portal":" Vendor "}`, want: "vendor", inherit: true},
{name: "invalid-parsed-hints", raw: `{"type":"vendor","oauth_provider":"vendor"}`, attributes: map[string]string{"oauth_provider": " ", "portal": " "}, metadata: map[string]any{"oauth_provider": true, "portal": 42}, want: "vendor", inherit: true},
{name: "attributes-oauth-preserved", raw: `{"type":"vendor","oauth_provider":"vendor"}`, attributes: map[string]string{"oauth_provider": "vendor-cn"}, want: "vendor-cn"},
{name: "metadata-oauth-preserved", raw: `{"type":"vendor","oauth_provider":"vendor"}`, metadata: map[string]any{"oauth_provider": "vendor-cn"}, want: "vendor-cn"},
{name: "attributes-portal-preserved", raw: `{"type":"vendor","oauth_provider":"vendor"}`, attributes: map[string]string{"portal": "vendor-cn"}, want: "vendor-cn"},
{name: "metadata-portal-preserved", raw: `{"type":"vendor","oauth_provider":"vendor"}`, metadata: map[string]any{"portal": "vendor-cn"}, want: "vendor-cn"},
{name: "no-hint", raw: `{"type":"vendor"}`},
{name: "invalid-file-hints", raw: `{"type":"vendor","oauth_provider":true,"portal":42}`},
} {
t.Run(tc.name, func(t *testing.T) {
storage := &oauthProviderMetadataStorage{}
parser := multiAuthParserFunc(func(context.Context, pluginapi.AuthParseRequest) ([]*coreauth.Auth, bool, error) {
return []*coreauth.Auth{
{Provider: "vendor", Metadata: tc.metadata, Attributes: tc.attributes, Storage: storage},
{Provider: "vendor"},
}, true, nil
})
authDir := t.TempDir()
auths, errSynthesize := SynthesizeAuthFile(&SynthesisContext{
AuthDir: authDir, PluginAuthParser: parser, Now: time.Now(), StrictFileParsing: true,
}, filepath.Join(authDir, "vendor.json"), []byte(tc.raw))
if errSynthesize != nil || len(auths) != 2 {
t.Fatalf("SynthesizeAuthFile() count=%d error=%v", len(auths), errSynthesize)
}
auth := auths[0]
hint := ""
for _, key := range []string{"oauth_provider", "portal"} {
if hint = auth.Attributes[key]; hint != "" {
break
}
if hint, _ = auth.Metadata[key].(string); hint != "" {
break
}
}
if hint != tc.want {
t.Fatalf("synthesized hint = %q, want %q", hint, tc.want)
}
if tc.inherit {
for index, parsed := range auths {
if parsed.Metadata["oauth_provider"] != tc.want || parsed.Attributes["oauth_provider"] != tc.want {
t.Errorf("auth %d did not inherit hint: metadata=%#v attributes=%#v", index, parsed.Metadata, parsed.Attributes)
}
}
if storage.metadata["oauth_provider"] != tc.want {
t.Fatalf("storage metadata=%#v, want oauth_provider=%q", storage.metadata, tc.want)
}
} else if storage.metadata != nil {
t.Fatalf("existing hint unexpectedly changed storage metadata: %#v", storage.metadata)
}
})
}
}
type oauthProviderMetadataStorage struct {
metadata map[string]any
}
func (s *oauthProviderMetadataStorage) SetMetadata(metadata map[string]any) {
s.metadata = metadata
}
func (s *oauthProviderMetadataStorage) SaveTokenToFile(string) error {
return nil
}