* feat(auth): support multi-profile login
* fix(auth): complete multi-org profile acceptance
* feat(auth): 完成多组织 profile 验收
* docs(auth): 补充多组织 Ralph 验收材料
* feat(auth): 支持 auth switch TUI 切换 profile
* feat(auth): logout 默认清理所有组织
* feat(auth): login 默认新增组织授权
* feat(profile): 使用 profile switch 切换组织
* docs(ralph): 更新 profile switch 验收材料
* fix(profile): 展示全部可切换组织
* feat(profile): support multi-org switch tui
* chore(install): add branch source installer
* fix(profile): keep global profile out of tool params
* feat(profile): support csv multi-profile runtime
* ci: add multi-profile e2e workflow
* ci: run multi-profile e2e on all branches
* docs: document multi-profile e2e ci gate
* docs: remove multi-profile test cases from pr
* ci: harden multi-profile e2e gates
* fix(auth): serialize profiles.json RMW and harden multi-profile persistence
Wrap all profiles.json read-modify-write paths (profile switch/use/remove,
status marking, token save, logout) in the existing dual-layer lock via a new
withProfilesLock helper. Split each writer into a public (locking) entry point
plus a lock-free *Locked variant so the non-reentrant lock is never re-acquired;
the refresh path (oauth_helpers) and the load-path legacy migration now call the
lock-free saver to avoid self-deadlock.
Also: write profiles.json and the token marker via per-write random temp names
(uuid) to stop concurrent writers from corrupting a fixed .tmp file; quarantine
an unparseable profiles.json and rebuild an empty config so the CLI can
self-heal instead of locking out auth reset/logout; make DeleteAllTokenData
proceed even if profiles.json cannot be read; and stop SyncLegacyTokenMirror
from deleting the legacy mirror on a transient keychain read error.
* fix(auth): do not fall back to a different org's legacy token slot
When no explicit --profile is given, LoadTokenDataForProfile resolves the
current/primary profile and reads its per-corp keychain slot. If that slot
read failed, the code silently fell through to the legacy single token slot,
which after any drift between the legacy mirror and the current profile could
belong to a different organization. The command would then run as the wrong
org with no indication to the user.
Reproduction (conceptual):
- profiles.json currentProfile = corpA
- corpA's keychain slot is unreadable, legacy single slot still holds corpB
- any read command (no --profile) silently used corpB's token
Fix: when a profile is resolved but its slot read fails and no --profile was
given, only fall back to the legacy single slot when its CorpID matches the
resolved profile (same org); otherwise return the original error instead of
acting as a different organization. The no-profile legacy path (pre-migration
installs with no resolved profile) is unchanged.
Tests:
- Covered by the existing internal/auth suite under go test -race; the
same-org fallback preserves the legacy-mirror case while the cross-org
case now surfaces the read error.
* feat(skill): document multi-org profile usage and always ship dws-shared
The skills had no guidance on the multi-profile capability, so an agent would
treat the CLI as single-org: when a lookup missed in the current org it would
give up or ask the user instead of searching other logged-in orgs. The multi
skill set also referenced a `dws-shared` prerequisite that was never actually
installed, and the only multi-org hints lived inline in three product skills.
This adds, in source only:
- A "multi-org / profile" section in the mono SKILL.md (concept, commands,
cross-org rule, aggregation, safety guardrails) plus a decision-tree entry,
trigger conditions, and a corrected logout danger-table row (logout removes
all orgs by default; removing the primary silently re-elects a new primary,
confirm before removing the primary).
- A standalone skills/multi/dingtalk-profile skill mirroring the same content.
- A new skills/multi/dws-shared skill that carries auth, global flags and the
multi-org rule, so every product skill's PREREQUISITE resolves and all
read/search skills inherit the cross-org behavior without per-skill edits.
- Cross-org fallback notes on dingtalk-aisearch / chat / contact.
To guarantee the prerequisite actually ships, multi-mode install now force-
includes dws-shared even when --skill / --exclude narrows the set (no-op when
the source has no dws-shared, preserving older layouts).
Tests:
- internal/app: TestP1SharedAlwaysIncludedWithSkillFilter installs with
`-s aitable` and asserts dws-shared still lands in the destination;
TestP1SharedNoopWhenAbsent guards the older-layout no-op.
- go test -race ./internal/auth/... ./internal/app/... passes.
---------
Co-authored-by: shangguanxuan.sgx <shangguanxuan.sgx@alibaba-inc.com>
Co-authored-by: qinze <audanye@gmail.com>
407 lines
11 KiB
Go
407 lines
11 KiB
Go
package auth
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
// ─── endpoints.go ──────────────────────────────────────────────────────
|
|
|
|
func TestClientID_RuntimeOverride(t *testing.T) {
|
|
t.Setenv("DWS_CLIENT_ID", "env-id")
|
|
SetClientID("flag-id")
|
|
t.Cleanup(func() { SetClientID("") })
|
|
if got := ClientID(); got != "flag-id" {
|
|
t.Fatalf("expected flag-id, got %s", got)
|
|
}
|
|
}
|
|
|
|
func TestClientID_EnvFallback(t *testing.T) {
|
|
SetClientID("")
|
|
t.Setenv("DWS_CONFIG_DIR", t.TempDir()) // Use temp dir to avoid reading persisted config
|
|
t.Setenv("DWS_CLIENT_ID", "env-id")
|
|
if got := ClientID(); got != "env-id" {
|
|
t.Fatalf("expected env-id, got %s", got)
|
|
}
|
|
}
|
|
|
|
func TestClientID_Default(t *testing.T) {
|
|
SetClientID("")
|
|
t.Setenv("DWS_CONFIG_DIR", t.TempDir()) // Use temp dir to avoid reading persisted config
|
|
t.Setenv("DWS_CLIENT_ID", "")
|
|
// When DefaultClientID is a placeholder (starts with "<"), ClientID() returns empty string
|
|
if strings.HasPrefix(DefaultClientID, "<") {
|
|
if got := ClientID(); got != "" {
|
|
t.Fatalf("expected empty string for placeholder, got %s", got)
|
|
}
|
|
} else {
|
|
if got := ClientID(); got != DefaultClientID {
|
|
t.Fatalf("expected default, got %s", got)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestClientSecret_RuntimeOverride(t *testing.T) {
|
|
t.Setenv("DWS_CLIENT_SECRET", "env-secret")
|
|
SetClientSecret("flag-secret")
|
|
t.Cleanup(func() { SetClientSecret("") })
|
|
if got := ClientSecret(); got != "flag-secret" {
|
|
t.Fatalf("expected flag-secret, got %s", got)
|
|
}
|
|
}
|
|
|
|
func TestClientSecret_EnvFallback(t *testing.T) {
|
|
SetClientSecret("")
|
|
t.Setenv("DWS_CONFIG_DIR", t.TempDir()) // Use temp dir to avoid reading persisted config
|
|
t.Setenv("DWS_CLIENT_SECRET", "env-secret")
|
|
if got := ClientSecret(); got != "env-secret" {
|
|
t.Fatalf("expected env-secret, got %s", got)
|
|
}
|
|
}
|
|
|
|
func TestClientSecret_Default(t *testing.T) {
|
|
SetClientSecret("")
|
|
t.Setenv("DWS_CONFIG_DIR", t.TempDir()) // Use temp dir to avoid reading persisted config
|
|
t.Setenv("DWS_CLIENT_SECRET", "")
|
|
if got := ClientSecret(); got != DefaultClientSecret {
|
|
t.Fatalf("expected default, got %s", got)
|
|
}
|
|
}
|
|
|
|
func TestClientID_ConcurrentAccess(t *testing.T) {
|
|
var wg sync.WaitGroup
|
|
for i := 0; i < 100; i++ {
|
|
wg.Add(2)
|
|
go func(n int) {
|
|
defer wg.Done()
|
|
SetClientID(fmt.Sprintf("id-%d", n))
|
|
}(i)
|
|
go func() {
|
|
defer wg.Done()
|
|
_ = ClientID()
|
|
}()
|
|
}
|
|
wg.Wait()
|
|
SetClientID("")
|
|
}
|
|
|
|
// ─── identity.go ───────────────────────────────────────────────────────
|
|
|
|
func TestGenerateUUID_Format(t *testing.T) {
|
|
t.Parallel()
|
|
uuid := generateUUID()
|
|
parts := strings.Split(uuid, "-")
|
|
if len(parts) != 5 {
|
|
t.Fatalf("expected 5 parts, got %d: %s", len(parts), uuid)
|
|
}
|
|
if len(uuid) != 36 {
|
|
t.Fatalf("expected 36 chars, got %d: %s", len(uuid), uuid)
|
|
}
|
|
// Version 4 marker
|
|
if uuid[14] != '4' {
|
|
t.Fatalf("expected version 4 at position 14, got %c", uuid[14])
|
|
}
|
|
}
|
|
|
|
func TestIdentity_LoadMissing(t *testing.T) {
|
|
t.Parallel()
|
|
id := Load(t.TempDir())
|
|
if id != nil {
|
|
t.Fatal("expected nil for missing identity")
|
|
}
|
|
}
|
|
|
|
func TestIdentity_EnsureExistsCreatesNew(t *testing.T) {
|
|
t.Parallel()
|
|
dir := t.TempDir()
|
|
id := EnsureExists(dir)
|
|
if id == nil || id.AgentID == "" {
|
|
t.Fatal("expected non-nil identity with agentID")
|
|
}
|
|
if id.Source != "dws" {
|
|
t.Fatalf("expected source dws, got %s", id.Source)
|
|
}
|
|
}
|
|
|
|
func TestIdentity_EnsureExistsLoadsExisting(t *testing.T) {
|
|
t.Parallel()
|
|
dir := t.TempDir()
|
|
id1 := EnsureExists(dir)
|
|
id2 := EnsureExists(dir)
|
|
if id1.AgentID != id2.AgentID {
|
|
t.Fatalf("expected same ID, got %s vs %s", id1.AgentID, id2.AgentID)
|
|
}
|
|
}
|
|
|
|
func TestIdentity_LoadInvalidJSON(t *testing.T) {
|
|
t.Parallel()
|
|
dir := t.TempDir()
|
|
_ = os.WriteFile(filepath.Join(dir, identityFile), []byte("not json"), 0o600)
|
|
if Load(dir) != nil {
|
|
t.Fatal("expected nil for invalid JSON")
|
|
}
|
|
}
|
|
|
|
func TestIdentity_LoadEmptyAgentID(t *testing.T) {
|
|
t.Parallel()
|
|
dir := t.TempDir()
|
|
data, _ := json.Marshal(Identity{AgentID: "", Source: "dws"})
|
|
_ = os.WriteFile(filepath.Join(dir, identityFile), data, 0o600)
|
|
if Load(dir) != nil {
|
|
t.Fatal("expected nil for empty agentID")
|
|
}
|
|
}
|
|
|
|
func TestIdentity_Headers(t *testing.T) {
|
|
t.Parallel()
|
|
id := &Identity{AgentID: "test-uuid", Source: "dws"}
|
|
h := id.Headers()
|
|
if h["x-dws-agent-id"] != "test-uuid" {
|
|
t.Fatalf("wrong agent-id header: %s", h["x-dws-agent-id"])
|
|
}
|
|
if h["x-dws-source"] != "dws" {
|
|
t.Fatalf("wrong source header: %s", h["x-dws-source"])
|
|
}
|
|
if _, ok := h["x-dingtalk-scenario-code"]; !ok {
|
|
t.Fatal("missing scenario-code header")
|
|
}
|
|
}
|
|
|
|
func TestIdentity_Headers_Nil(t *testing.T) {
|
|
t.Parallel()
|
|
var id *Identity
|
|
if h := id.Headers(); h != nil {
|
|
t.Fatalf("expected nil headers for nil identity, got %v", h)
|
|
}
|
|
}
|
|
|
|
// ─── manager.go ────────────────────────────────────────────────────────
|
|
|
|
func TestManager_SaveAndGetToken(t *testing.T) {
|
|
t.Parallel()
|
|
dir := t.TempDir()
|
|
m := NewManager(dir, nil)
|
|
if err := m.SaveToken("test-token"); err != nil {
|
|
t.Fatalf("SaveToken error: %v", err)
|
|
}
|
|
token, source, err := m.GetToken()
|
|
if err != nil {
|
|
t.Fatalf("GetToken error: %v", err)
|
|
}
|
|
if token != "test-token" {
|
|
t.Fatalf("expected test-token, got %s", token)
|
|
}
|
|
if source != "file" {
|
|
t.Fatalf("expected file source, got %s", source)
|
|
}
|
|
}
|
|
|
|
func TestManager_GetToken_Missing(t *testing.T) {
|
|
t.Parallel()
|
|
m := NewManager(t.TempDir(), nil)
|
|
_, _, err := m.GetToken()
|
|
if err == nil {
|
|
t.Fatal("expected error for missing token")
|
|
}
|
|
}
|
|
|
|
func TestManager_SaveAndGetMCPURL(t *testing.T) {
|
|
t.Parallel()
|
|
dir := t.TempDir()
|
|
m := NewManager(dir, nil)
|
|
if err := m.SaveMCPURL("https://example.com/mcp"); err != nil {
|
|
t.Fatalf("SaveMCPURL error: %v", err)
|
|
}
|
|
url, err := m.GetMCPURL()
|
|
if err != nil {
|
|
t.Fatalf("GetMCPURL error: %v", err)
|
|
}
|
|
if url != "https://example.com/mcp" {
|
|
t.Fatalf("expected url, got %s", url)
|
|
}
|
|
}
|
|
|
|
func TestManager_GetMCPURL_Missing(t *testing.T) {
|
|
t.Parallel()
|
|
m := NewManager(t.TempDir(), nil)
|
|
_, err := m.GetMCPURL()
|
|
if err == nil {
|
|
t.Fatal("expected error for missing MCP URL")
|
|
}
|
|
}
|
|
|
|
// ─── token.go ──────────────────────────────────────────────────────────
|
|
|
|
func TestTokenData_IsAccessTokenValid(t *testing.T) {
|
|
t.Parallel()
|
|
tests := []struct {
|
|
name string
|
|
data *TokenData
|
|
want bool
|
|
}{
|
|
{"nil", nil, false},
|
|
{"empty token", &TokenData{}, false},
|
|
{"expired", &TokenData{AccessToken: "t", ExpiresAt: time.Now().Add(-time.Hour)}, false},
|
|
{"valid", &TokenData{AccessToken: "t", ExpiresAt: time.Now().Add(time.Hour)}, true},
|
|
{"within buffer", &TokenData{AccessToken: "t", ExpiresAt: time.Now().Add(3 * time.Minute)}, false},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := tt.data.IsAccessTokenValid(); got != tt.want {
|
|
t.Fatalf("IsAccessTokenValid() = %v, want %v", got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestTokenData_IsRefreshTokenValid(t *testing.T) {
|
|
t.Parallel()
|
|
tests := []struct {
|
|
name string
|
|
data *TokenData
|
|
want bool
|
|
}{
|
|
{"nil", nil, false},
|
|
{"empty", &TokenData{}, false},
|
|
{"expired", &TokenData{RefreshToken: "r", RefreshExpAt: time.Now().Add(-time.Hour)}, false},
|
|
{"valid", &TokenData{RefreshToken: "r", RefreshExpAt: time.Now().Add(time.Hour)}, true},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
if got := tt.data.IsRefreshTokenValid(); got != tt.want {
|
|
t.Fatalf("IsRefreshTokenValid() = %v, want %v", got, tt.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestTokenData_HasPersistentCode(t *testing.T) {
|
|
t.Parallel()
|
|
if (&TokenData{}).HasPersistentCode() {
|
|
t.Fatal("expected false for empty")
|
|
}
|
|
if !(&TokenData{PersistentCode: "code"}).HasPersistentCode() {
|
|
t.Fatal("expected true")
|
|
}
|
|
var nilData *TokenData
|
|
if nilData.HasPersistentCode() {
|
|
t.Fatal("expected false for nil")
|
|
}
|
|
}
|
|
|
|
func TestRevokeTokenRemote(t *testing.T) {
|
|
t.Parallel()
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
w.WriteHeader(http.StatusOK)
|
|
}))
|
|
defer srv.Close()
|
|
// Can't easily test since LogoutURL is a const. Just test that it doesn't panic with real URL.
|
|
}
|
|
|
|
// ─── oauth_helpers.go ──────────────────────────────────────────────────
|
|
|
|
type tokenResponse struct {
|
|
AccessToken string `json:"accessToken"`
|
|
RefreshToken string `json:"refreshToken"`
|
|
PersistentCode string `json:"persistentCode"`
|
|
ExpiresIn int64 `json:"expiresIn"`
|
|
}
|
|
|
|
func TestBuildTokenData_DefaultExpiry(t *testing.T) {
|
|
resp := tokenResponse{
|
|
AccessToken: "access-123",
|
|
RefreshToken: "refresh-456",
|
|
ExpiresIn: 0,
|
|
}
|
|
data := buildTokenDataFromResponse(resp)
|
|
if data == nil {
|
|
t.Fatal("expected non-nil token data")
|
|
}
|
|
if data.AccessToken != "access-123" {
|
|
t.Fatalf("wrong access token: %s", data.AccessToken)
|
|
}
|
|
}
|
|
|
|
func TestParseMCPTokenResponseIncludesCorpName(t *testing.T) {
|
|
provider := &OAuthProvider{}
|
|
data, err := provider.parseMCPTokenResponse([]byte(`{
|
|
"accessToken": "access-123",
|
|
"refreshToken": "refresh-456",
|
|
"expiresIn": 7200,
|
|
"corpId": "ding123",
|
|
"corpName": "钉钉(中国)信息技术有限公司"
|
|
}`))
|
|
if err != nil {
|
|
t.Fatalf("parseMCPTokenResponse() error = %v", err)
|
|
}
|
|
if data.CorpID != "ding123" {
|
|
t.Fatalf("corp id = %q, want ding123", data.CorpID)
|
|
}
|
|
if data.CorpName != "钉钉(中国)信息技术有限公司" {
|
|
t.Fatalf("corp name = %q, want 钉钉(中国)信息技术有限公司", data.CorpName)
|
|
}
|
|
}
|
|
|
|
func TestParseMCPTokenResponseCorpNameFallbacks(t *testing.T) {
|
|
provider := &OAuthProvider{}
|
|
for _, tc := range []struct {
|
|
name string
|
|
body string
|
|
want string
|
|
}{
|
|
{
|
|
name: "snake",
|
|
body: `{"accessToken":"access","refreshToken":"refresh","expiresIn":7200,"corpId":"ding123","corp_name":"Snake Corp"}`,
|
|
want: "Snake Corp",
|
|
},
|
|
{
|
|
name: "orgName",
|
|
body: `{"accessToken":"access","refreshToken":"refresh","expiresIn":7200,"corpId":"ding123","orgName":"Org Corp"}`,
|
|
want: "Org Corp",
|
|
},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
data, err := provider.parseMCPTokenResponse([]byte(tc.body))
|
|
if err != nil {
|
|
t.Fatalf("parseMCPTokenResponse() error = %v", err)
|
|
}
|
|
if data.CorpName != tc.want {
|
|
t.Fatalf("corp name = %q, want %q", data.CorpName, tc.want)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestBuildAuthURLIncludesTargetCorpID(t *testing.T) {
|
|
authURL := buildAuthURL("client-id", "http://127.0.0.1:1234/callback", "ding-target")
|
|
if !strings.Contains(authURL, "corpId=ding-target") {
|
|
t.Fatalf("auth URL missing target corpId: %s", authURL)
|
|
}
|
|
}
|
|
|
|
func buildTokenDataFromResponse(resp tokenResponse) *TokenData {
|
|
if resp.AccessToken == "" {
|
|
return nil
|
|
}
|
|
now := time.Now()
|
|
expiresIn := resp.ExpiresIn
|
|
if expiresIn <= 0 {
|
|
expiresIn = 7200
|
|
}
|
|
return &TokenData{
|
|
AccessToken: resp.AccessToken,
|
|
RefreshToken: resp.RefreshToken,
|
|
ExpiresAt: now.Add(time.Duration(expiresIn) * time.Second),
|
|
RefreshExpAt: now.Add(30 * 24 * time.Hour),
|
|
PersistentCode: resp.PersistentCode,
|
|
}
|
|
}
|