feat(settings): 新增 DWS 设备登录与目录连接检查
build / build (push) Successful in 1m52s

数据源配置可发起钉钉官方设备授权、重新授权和取消,完成后刷新共享账号状态并独立检查目录权限。
授权会话限定发起的管理员登录会话,令牌由现有 CLI 存储,取消等待子进程退出。

验证:完整 make verify 通过;前端 582 项、Go 1545 项通过,487 项声明的可选集成未运行。
授权处理器与 HTTP 边界通过 race 检查;本人钉钉授权仍由管理员在官方页面完成。
This commit is contained in:
姚章浩
2026-11-17 16:59:47 +08:00
parent 6c10f71c28
commit b2cea6ed84
20 changed files with 1291 additions and 46 deletions
+7 -1
View File
@@ -12,6 +12,9 @@ type CredentialStatus struct {
RefreshTokenValid bool `json:"refresh_token_valid"`
ExpiresAt string `json:"expires_at,omitempty"`
RefreshExpiresAt string `json:"refresh_expires_at,omitempty"`
CorpName string `json:"corp_name,omitempty"`
UserName string `json:"user_name,omitempty"`
StatusKnown bool `json:"status_known"`
}
func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus, error) {
@@ -24,9 +27,12 @@ func ReadCredentialStatus(ctx context.Context, runner Runner) (CredentialStatus,
RefreshTokenValid bool `json:"refresh_token_valid"`
ExpiresAt string `json:"expires_at"`
RefreshExpiresAt string `json:"refresh_expires_at"`
CorpName string `json:"corp_name"`
UserName string `json:"user_name"`
Reason string `json:"reason"`
}
if json.Unmarshal(raw, &decoded) != nil || decoded.Authenticated == nil {
return CredentialStatus{}, errors.New("invalid DWS credential status")
}
return CredentialStatus{*decoded.Authenticated, decoded.RefreshTokenValid, decoded.ExpiresAt, decoded.RefreshExpiresAt}, nil
return CredentialStatus{Authenticated: *decoded.Authenticated, RefreshTokenValid: decoded.RefreshTokenValid, ExpiresAt: decoded.ExpiresAt, RefreshExpiresAt: decoded.RefreshExpiresAt, CorpName: decoded.CorpName, UserName: decoded.UserName, StatusKnown: decoded.Reason == ""}, nil
}
+243
View File
@@ -0,0 +1,243 @@
package dingtalkdiscovery
import (
"bufio"
"context"
"crypto/rand"
"encoding/hex"
"errors"
"io"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
var ErrLoginBusy = errors.New("another DWS authorization is active")
var ErrLoginNotFound = errors.New("DWS authorization not found")
// DeviceLoginView contains only the user-facing challenge. Tokens remain in the
// CLI's shared credential store; command output is never logged or returned.
type DeviceLoginView struct {
ID string `json:"id"`
State string `json:"state"`
VerificationURL string `json:"verification_url,omitempty"`
UserCode string `json:"user_code,omitempty"`
ExpiresAt time.Time `json:"expires_at"`
Error string `json:"error,omitempty"`
}
type deviceLogin struct {
view DeviceLoginView
owner string
cancel context.CancelFunc
done chan struct{}
}
type DeviceLoginManager struct {
ctx context.Context
runner ExecRunner
mu sync.Mutex
sessions map[string]*deviceLogin
}
func NewDeviceLoginManager(ctx context.Context, runner ExecRunner) *DeviceLoginManager {
return &DeviceLoginManager{ctx: ctx, runner: runner, sessions: make(map[string]*deviceLogin)}
}
func loginActive(state string) bool {
return state == "starting" || state == "waiting" || state == "verifying"
}
func (m *DeviceLoginManager) Start(owner string) (DeviceLoginView, error) {
if owner == "" {
return DeviceLoginView{}, ErrLoginNotFound
}
m.mu.Lock()
defer m.mu.Unlock()
for id, s := range m.sessions {
if s.view.State == "cancelled" || s.view.State == "expired" {
select {
case <-s.done:
default:
return DeviceLoginView{}, ErrLoginBusy
}
}
if loginActive(s.view.State) {
if s.owner == owner {
return s.view, nil
}
return DeviceLoginView{}, ErrLoginBusy
}
if time.Since(s.view.ExpiresAt) > 30*time.Minute || len(m.sessions) >= 16 {
delete(m.sessions, id)
}
}
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
return DeviceLoginView{}, err
}
ctx, cancel := context.WithTimeout(m.ctx, 20*time.Minute)
s := &deviceLogin{view: DeviceLoginView{ID: hex.EncodeToString(b[:]), State: "starting", ExpiresAt: time.Now().UTC().Add(20 * time.Minute)}, owner: owner, cancel: cancel, done: make(chan struct{})}
m.sessions[s.view.ID] = s
go m.run(ctx, s)
return s.view, nil
}
func (m *DeviceLoginManager) Get(owner, id string) (DeviceLoginView, error) {
m.mu.Lock()
defer m.mu.Unlock()
s := m.sessions[id]
if s == nil || s.owner != owner {
return DeviceLoginView{}, ErrLoginNotFound
}
if loginActive(s.view.State) && !time.Now().Before(s.view.ExpiresAt) {
s.cancel()
finishLogin(s, "expired", "授权已过期,请重新发起。")
}
return s.view, nil
}
func (m *DeviceLoginManager) Cancel(owner, id string) (DeviceLoginView, error) {
m.mu.Lock()
s := m.sessions[id]
if s == nil || s.owner != owner {
m.mu.Unlock()
return DeviceLoginView{}, ErrLoginNotFound
}
if loginActive(s.view.State) {
s.cancel()
finishLogin(s, "cancelled", "")
}
m.mu.Unlock()
// Do not acknowledge cancellation while the old CLI could still write tokens.
timer := time.NewTimer(7 * time.Second)
defer timer.Stop()
select {
case <-s.done:
case <-timer.C:
return DeviceLoginView{}, ErrLoginBusy
}
m.mu.Lock()
defer m.mu.Unlock()
return s.view, nil
}
func finishLogin(s *deviceLogin, state, message string) {
s.view.State = state
s.view.Error = message
s.view.VerificationURL = ""
s.view.UserCode = ""
}
var ansiEscape = regexp.MustCompile(`\x1b\[[0-9;]*[A-Za-z]`)
var challengeCode = regexp.MustCompile(`(?:授权码|User code|User Code)\s*[::]\s*([A-Za-z0-9-]{4,32})`)
var challengeExpiry = regexp.MustCompile(`(?:将在\s*|expires in\s*)([0-9]+)\s*(?:秒|seconds)`)
func safeDeviceURL(raw string) bool {
u, err := url.Parse(raw)
return err == nil && u.Scheme == "https" && u.Host == "login.dingtalk.com" && u.User == nil && u.Fragment == "" && u.Path == "/oauth2/device/verify.htm"
}
func (m *DeviceLoginManager) observe(s *deviceLogin, line string) {
line = strings.TrimSpace(ansiEscape.ReplaceAllString(line, ""))
m.mu.Lock()
defer m.mu.Unlock()
if !loginActive(s.view.State) {
return
}
if match := challengeCode.FindStringSubmatch(line); len(match) == 2 {
s.view.UserCode = match[1]
}
if match := challengeExpiry.FindStringSubmatch(line); len(match) == 2 {
seconds, _ := strconv.Atoi(match[1])
if seconds > 0 && seconds <= 1800 {
s.view.ExpiresAt = time.Now().UTC().Add(time.Duration(seconds) * time.Second)
}
}
if safeDeviceURL(line) {
u, _ := url.Parse(line)
if s.view.VerificationURL == "" || u.Query().Get("user_code") != "" {
s.view.VerificationURL = line
}
}
if s.view.State == "starting" && s.view.UserCode != "" && s.view.VerificationURL != "" {
s.view.State = "waiting"
}
if strings.Contains(line, "Step 3:") {
s.view.State = "verifying"
}
}
func (m *DeviceLoginManager) run(ctx context.Context, s *deviceLogin) {
defer close(s.done)
defer s.cancel()
command, err := m.runner.command(ctx, "auth", "login", "--device", "--no-browser", "--format", "json")
if err != nil {
m.failed(s, "DWS 登录程序不可用,请联系管理员检查服务配置。")
return
}
command.Env = append(command.Env, "DWS_LANG=zh", "NO_COLOR=1", "TERM=dumb")
command.Stdout = io.Discard
stderr, err := command.StderrPipe()
if err != nil {
m.failed(s, "无法启动 DWS 授权,请重试。")
return
}
if err = command.Start(); err != nil {
m.failed(s, "无法启动 DWS 授权,请检查凭据目录权限。")
return
}
scanner := bufio.NewScanner(stderr)
scanner.Buffer(make([]byte, 4096), 64*1024)
for scanner.Scan() {
m.observe(s, scanner.Text())
}
if scanner.Err() != nil {
s.cancel()
}
err = command.Wait()
m.mu.Lock()
active := loginActive(s.view.State)
m.mu.Unlock()
if !active {
return
}
if err != nil || ctx.Err() != nil {
m.mu.Lock()
defer m.mu.Unlock()
if !loginActive(s.view.State) {
return
}
if errors.Is(ctx.Err(), context.DeadlineExceeded) || !time.Now().Before(s.view.ExpiresAt) {
finishLogin(s, "expired", "授权已过期,请重新发起。")
} else {
finishLogin(s, "failed", "DWS 授权未完成,请重试;若组织未开通 CLI 数据权限,请联系钉钉管理员。")
}
return
}
// A process exit alone is not proof that usable credentials were persisted.
checkCtx, cancel := context.WithTimeout(m.ctx, 5*time.Second)
defer cancel()
status, statusErr := ReadCredentialStatus(checkCtx, m.runner)
m.mu.Lock()
defer m.mu.Unlock()
if !loginActive(s.view.State) {
return
}
if statusErr != nil || !status.Authenticated || !status.RefreshTokenValid || !status.StatusKnown {
finishLogin(s, "failed", "授权结束,但未读到有效 DWS 凭据,请重新授权。")
} else {
finishLogin(s, "succeeded", "")
}
}
func (m *DeviceLoginManager) failed(s *deviceLogin, message string) {
m.mu.Lock()
defer m.mu.Unlock()
if loginActive(s.view.State) {
finishLogin(s, "failed", message)
}
}
@@ -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")
}
}
+14 -4
View File
@@ -19,8 +19,8 @@ type ExecRunner struct {
Timeout time.Duration
}
// RunDWS 运行 `dws <args…>` 并返回 stdout。
func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) {
// command keeps device login and source reads on one credential environment.
func (r ExecRunner) command(ctx context.Context, args ...string) (*exec.Cmd, error) {
binary := r.Binary
if binary == "" {
binary = os.Getenv("DWS_BIN")
@@ -32,14 +32,24 @@ func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error)
}
binary = found
}
command := exec.CommandContext(ctx, binary, args...)
command.Env = dwsEnv()
command.WaitDelay = 2 * time.Second
return command, nil
}
// RunDWS uses the same executable and credential environment as device login.
func (r ExecRunner) RunDWS(ctx context.Context, args ...string) ([]byte, error) {
timeout := r.Timeout
if timeout <= 0 {
timeout = 25 * time.Second
}
runCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
command := exec.CommandContext(runCtx, binary, args...)
command.Env = dwsEnv()
command, err := r.command(runCtx, args...)
if err != nil {
return nil, err
}
var stdout, stderr bytes.Buffer
command.Stdout = &stdout
command.Stderr = &stderr
+3
View File
@@ -107,6 +107,9 @@ func classifyRole(method, path string) string {
if strings.HasPrefix(path, "/api/v1/users") || strings.HasPrefix(path, "/api/v1/qa-ops/") {
return roleAdmin
}
if strings.HasPrefix(path, "/api/v1/dws-login") {
return roleAdmin
}
if method == http.MethodGet {
return roleViewer
}
+74
View File
@@ -0,0 +1,74 @@
package httpapi
import (
"errors"
"log"
"net/http"
"net/url"
"knowledge-governance/internal/dingtalkdiscovery"
)
func registerDWSLoginRoutes(mux *http.ServeMux, config Config) {
mux.HandleFunc("POST /api/v1/dws-login", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "start") })
mux.HandleFunc("GET /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "get") })
mux.HandleFunc("DELETE /api/v1/dws-login/{id}", func(w http.ResponseWriter, r *http.Request) { handleDWSLogin(w, r, config, "cancel") })
}
func handleDWSLogin(w http.ResponseWriter, r *http.Request, config Config, action string) {
w.Header().Set("Cache-Control", "no-store")
identity, ok := requireSessionIdentity(w, r)
if !ok {
return
}
if identity.Role != roleAdmin {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "需要管理员身份才能管理 DWS 授权"})
return
}
if action != "get" {
originOK := true
if raw := r.Header.Get("Origin"); raw != "" {
origin, err := url.Parse(raw)
originOK = err == nil && origin.Host == r.Host && (origin.Scheme == "http" || origin.Scheme == "https")
}
if !originOK || r.Header.Get("Sec-Fetch-Site") == "cross-site" || r.Header.Get("X-Governance-Action") != "dws-login" {
writeJSON(w, http.StatusForbidden, map[string]string{"error": "请从本平台的数据源配置页发起授权"})
return
}
}
if config.DWSLogin == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "DWS 登录服务未接通,请联系管理员"})
return
}
// Bind the challenge to this authenticated administrator and browser session.
owner := identity.UserID + "/" + identity.SessionID
var view dingtalkdiscovery.DeviceLoginView
var err error
switch action {
case "start":
view, err = config.DWSLogin.Start(owner)
case "get":
view, err = config.DWSLogin.Get(owner, r.PathValue("id"))
case "cancel":
view, err = config.DWSLogin.Cancel(owner, r.PathValue("id"))
}
if err != nil {
switch {
case errors.Is(err, dingtalkdiscovery.ErrLoginNotFound):
writeJSON(w, http.StatusNotFound, map[string]string{"error": "授权会话已结束或服务已重启,请重新发起"})
case errors.Is(err, dingtalkdiscovery.ErrLoginBusy):
writeJSON(w, http.StatusConflict, map[string]string{"error": "另一位管理员正在授权,请稍后再试"})
default:
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "无法发起 DWS 授权,请重试"})
}
return
}
if action != "get" {
log.Printf("DWS authorization action=%s id=%s actor=%s", action, view.ID, identity.Username)
}
status := http.StatusOK
if action == "start" {
status = http.StatusAccepted
}
writeJSON(w, status, map[string]any{"data": view})
}
+82
View File
@@ -0,0 +1,82 @@
package httpapi
import (
"context"
"encoding/json"
"knowledge-governance/internal/dingtalkdiscovery"
"net/http"
"net/http/httptest"
"testing"
)
func TestDWSLoginHTTPAuthenticationOwnershipAndOrigin(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
manager := dingtalkdiscovery.NewDeviceLoginManager(ctx, dingtalkdiscovery.ExecRunner{Binary: "/nonexistent/dws"})
h, err := NewHandler(Config{Store: &fakeJobStore{}, DWSLogin: manager})
if err != nil {
t.Fatal(err)
}
call := func(method, path, role, session, origin, intent string) *httptest.ResponseRecorder {
r := httptest.NewRequest(method, path, nil)
if role != "" {
r = r.WithContext(context.WithValue(r.Context(), sessionKey{}, sessionIdentity{UserID: "admin-user", Username: "tester", Role: role, SessionID: session}))
}
r.Header.Set("Origin", origin)
r.Header.Set("X-Governance-Action", intent)
w := httptest.NewRecorder()
h.ServeHTTP(w, r)
return w
}
for _, role := range []string{"", roleViewer, roleEngineer} {
w := call("POST", "/api/v1/dws-login", role, "s1", "", "dws-login")
if w.Code != 401 && w.Code != 403 {
t.Fatalf("role=%q status=%d", role, w.Code)
}
}
for _, input := range [][2]string{{"", ""}, {"https://foreign.invalid", "dws-login"}} {
w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", input[0], input[1])
if w.Code != 403 {
t.Fatalf("origin/intent not enforced: %d", w.Code)
}
}
w := call("POST", "/api/v1/dws-login", roleAdmin, "s1", "", "dws-login")
if w.Code != 202 || w.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("start=%d body=%s", w.Code, w.Body)
}
var body struct {
Data dingtalkdiscovery.DeviceLoginView `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &body); err != nil || body.Data.ID == "" {
t.Fatal("missing session", err)
}
path := "/api/v1/dws-login/" + body.Data.ID
for _, method := range []string{"GET", "DELETE"} {
w = call(method, path, roleAdmin, "other-session", "", "dws-login")
if w.Code != 404 {
t.Fatalf("foreign session %s=%d", method, w.Code)
}
w = call(method, path, roleEngineer, "s1", "", "dws-login")
if w.Code != 403 {
t.Fatalf("engineer %s=%d", method, w.Code)
}
}
w = call("GET", path, roleAdmin, "s1", "", "")
if w.Code != 200 {
t.Fatalf("get=%d", w.Code)
}
w = call("DELETE", path, roleAdmin, "s1", "", "dws-login")
if w.Code != 200 {
t.Fatalf("cancel=%d", w.Code)
}
}
func TestDWSLoginRoutesAreAdminOnly(t *testing.T) {
for _, method := range []string{http.MethodGet, http.MethodPost, http.MethodDelete} {
for _, path := range []string{"/api/v1/dws-login", "/api/v1/dws-login/session-id"} {
if got := classifyRole(method, path); got != roleAdmin {
t.Errorf("%s %s role=%s; authorization artifacts must be admin-only", method, path, got)
}
}
}
}
+3
View File
@@ -15,6 +15,7 @@ import (
"time"
"knowledge-governance/internal/backuphost"
"knowledge-governance/internal/dingtalkdiscovery"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
"knowledge-governance/internal/monitoring"
@@ -222,6 +223,7 @@ type Config struct {
DingtalkSources dingtalkSourcesLister
// DingtalkDocuments 列在线文档/表格并校验可读(只读,dws)。
DingtalkDocuments dingtalkDocLister
DWSLogin *dingtalkdiscovery.DeviceLoginManager
NewID func() (string, error)
Auth *AuthConfig
}
@@ -256,6 +258,7 @@ func NewHandler(config Config) (http.Handler, error) {
config.NewID = newID
}
mux := http.NewServeMux()
registerDWSLoginRoutes(mux, config)
registerQAAIRoutes(mux, config)
mux.HandleFunc("POST /api/v1/qa-ops/departments/statistics", func(w http.ResponseWriter, r *http.Request) { qaDepartmentStatistics(w, r, config) })
mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) })