数据源配置可发起钉钉官方设备授权、重新授权和取消,完成后刷新共享账号状态并独立检查目录权限。 授权会话限定发起的管理员登录会话,令牌由现有 CLI 存储,取消等待子进程退出。 验证:完整 make verify 通过;前端 582 项、Go 1545 项通过,487 项声明的可选集成未运行。 授权处理器与 HTTP 边界通过 race 检查;本人钉钉授权仍由管理员在官方页面完成。
This commit is contained in:
@@ -0,0 +1,160 @@
|
||||
package dingtalkdiscovery
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func deviceFixture(t *testing.T) (*DeviceLoginManager, string) {
|
||||
t.Helper()
|
||||
root := t.TempDir()
|
||||
binary := filepath.Join(root, "dws")
|
||||
script := `#!/usr/bin/env python3
|
||||
import sys,time,pathlib,json,os
|
||||
root=pathlib.Path(` + strconv.Quote(root) + `)
|
||||
a=sys.argv[1:]
|
||||
if a==['auth','login','--device','--no-browser','--format','json']:
|
||||
(root/'pid').write_text(str(os.getpid()))
|
||||
print(' 授权码: TEST-CODE',file=sys.stderr,flush=True)
|
||||
print('授权码将在 900 秒后过期。',file=sys.stderr,flush=True)
|
||||
print('https://login.dingtalk.com/oauth2/device/verify.htm?user_code=TEST-CODE',file=sys.stderr,flush=True)
|
||||
print('https://login.dingtalk.com/oauth2/device/verify.htm',file=sys.stderr,flush=True)
|
||||
print('never-expose-this-marker',file=sys.stderr,flush=True)
|
||||
while not (root/'finish').exists(): time.sleep(.01)
|
||||
if (root/'fail').exists(): sys.exit(1)
|
||||
elif a==['auth','status','--readonly','--format','json']:
|
||||
print(json.dumps({'authenticated':not (root/'invalid').exists(),'refresh_token_valid':True,'corp_name':'测试组织','user_name':'测试账号','access_token':'never-expose-this-marker'}))
|
||||
else: sys.exit(9)
|
||||
`
|
||||
if err := os.WriteFile(binary, []byte(script), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
t.Cleanup(cancel)
|
||||
return NewDeviceLoginManager(ctx, ExecRunner{Binary: binary}), root
|
||||
}
|
||||
func awaitDevice(t *testing.T, m *DeviceLoginManager, id, state string) DeviceLoginView {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(3 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
v, e := m.Get("owner", id)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if v.State == state {
|
||||
return v
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
v, _ := m.Get("owner", id)
|
||||
t.Fatalf("state=%s want=%s error=%s", v.State, state, v.Error)
|
||||
return v
|
||||
}
|
||||
func TestDeviceLoginUsesOfficialChallengeAndSharedCLI(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
initial, err := m.Start("owner")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if initial.State != "starting" {
|
||||
t.Fatal(initial)
|
||||
}
|
||||
waiting := awaitDevice(t, m, initial.ID, "waiting")
|
||||
if waiting.UserCode != "TEST-CODE" || !strings.Contains(waiting.VerificationURL, "user_code=TEST-CODE") {
|
||||
t.Fatal("missing complete official challenge")
|
||||
}
|
||||
if _, err = m.Start("other"); !errors.Is(err, ErrLoginBusy) {
|
||||
t.Fatal("parallel logins may overwrite shared credentials")
|
||||
}
|
||||
duplicate, _ := m.Start("owner")
|
||||
if duplicate.ID != initial.ID {
|
||||
t.Fatal("duplicate start was not idempotent")
|
||||
}
|
||||
if _, err = m.Get("other", initial.ID); !errors.Is(err, ErrLoginNotFound) {
|
||||
t.Fatal("challenge leaked to another owner")
|
||||
}
|
||||
if _, err = m.Cancel("other", initial.ID); !errors.Is(err, ErrLoginNotFound) {
|
||||
t.Fatal("foreign cancellation permitted")
|
||||
}
|
||||
if err = os.WriteFile(filepath.Join(root, "finish"), nil, 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
done := awaitDevice(t, m, initial.ID, "succeeded")
|
||||
raw, _ := json.Marshal(done)
|
||||
if done.UserCode != "" || done.VerificationURL != "" || strings.Contains(string(raw), "never-expose") {
|
||||
t.Fatal("completed session retained sensitive output")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginCancellationClearsChallenge(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
v, _ := m.Start("owner")
|
||||
awaitDevice(t, m, v.ID, "waiting")
|
||||
closed, err := m.Cancel("owner", v.ID)
|
||||
if err != nil || closed.State != "cancelled" || closed.UserCode != "" || closed.VerificationURL != "" {
|
||||
t.Fatal(closed, err)
|
||||
}
|
||||
pidBytes, err := os.ReadFile(filepath.Join(root, "pid"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pid, _ := strconv.Atoi(string(pidBytes))
|
||||
if syscall.Kill(pid, 0) == nil {
|
||||
t.Fatal("cancel returned while credential-writing process was still running")
|
||||
}
|
||||
again, _ := m.Get("owner", v.ID)
|
||||
if again.State != "cancelled" {
|
||||
t.Fatal("late process exit overwrote cancellation")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginRejectsExitWithoutPersistedCredentials(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
os.WriteFile(filepath.Join(root, "invalid"), nil, 0600)
|
||||
os.WriteFile(filepath.Join(root, "finish"), nil, 0600)
|
||||
v, _ := m.Start("owner")
|
||||
done := awaitDevice(t, m, v.ID, "failed")
|
||||
if !strings.Contains(done.Error, "未读到有效") {
|
||||
t.Fatal("successful exit was treated as authenticated")
|
||||
}
|
||||
}
|
||||
func TestDeviceLoginFailureIsRedactedAndRetryable(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
os.WriteFile(filepath.Join(root, "fail"), nil, 0600)
|
||||
os.WriteFile(filepath.Join(root, "finish"), nil, 0600)
|
||||
v, _ := m.Start("owner")
|
||||
done := awaitDevice(t, m, v.ID, "failed")
|
||||
if strings.Contains(done.Error, "never-expose") || done.Error == "" {
|
||||
t.Fatal("raw CLI output or missing error")
|
||||
}
|
||||
retry, e := m.Start("owner")
|
||||
if e != nil || retry.ID == v.ID {
|
||||
t.Fatal("cannot retry failed authorization")
|
||||
}
|
||||
}
|
||||
func TestDeviceChallengeRejectsUntrustedLinksAndExpires(t *testing.T) {
|
||||
m, root := deviceFixture(t)
|
||||
_ = root
|
||||
s := &deviceLogin{view: DeviceLoginView{State: "starting", ExpiresAt: time.Now().Add(time.Minute)}, cancel: func() {}}
|
||||
m.observe(s, "授权码: TEST-CODE")
|
||||
for _, link := range []string{"http://login.dingtalk.com/oauth2/device/verify.htm", "https://login.dingtalk.com.evil.invalid/oauth2/device/verify.htm", "https://user:pass@login.dingtalk.com/oauth2/device/verify.htm", "javascript:alert(1)", "https://login.dingtalk.com/other"} {
|
||||
m.observe(s, link)
|
||||
}
|
||||
if s.view.State != "starting" || s.view.VerificationURL != "" {
|
||||
t.Fatal("untrusted link accepted")
|
||||
}
|
||||
s.view.ID = "test-expired"
|
||||
s.owner = "owner"
|
||||
s.view.ExpiresAt = time.Now().Add(-time.Second)
|
||||
m.sessions[s.view.ID] = s
|
||||
got, e := m.Get("owner", s.view.ID)
|
||||
if e != nil || got.State != "expired" || got.UserCode != "" {
|
||||
t.Fatal("expired challenge retained")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user