feat(settings): refresh DingTalk scan sessions from the data-source page

DingTalk source scanning depends on a shared browser session whose capture
file had to be replaced by hand whenever it expired (every scan 401s).

- services/dingtalk-login: admin-triggered Playwright sidecar that opens the
  space page in a persistent headless Chromium, publishes the QR through
  session polling, verifies the first authenticated XHR against the box API,
  then writes the capture in place (same inode keeps the worker's ro bind
  mount current); tokens never leave the sidecar
- api: POST/GET/DELETE /api/v1/dingtalk-session authenticated relay; QR is a
  login artifact, so the whole prefix is admin-only in classifyRole; OpenAPI
  contract and proxy/503/hostile-ID tests included
- web: 系统设置 → 数据源配置 钉钉卡片新增扫码刷新会话(仅管理员可见),
  QR 弹窗 + 1.5s 轮询 + 成功/过期/失败状态
- compose: sidecar service owns the ONLY rw mount of secrets/; worker keeps ro
This commit is contained in:
姚章浩
2026-09-14 19:20:01 +08:00
parent 021e91eae4
commit 173b44abca
14 changed files with 683 additions and 0 deletions
+6
View File
@@ -117,6 +117,12 @@ func classifyRole(method, path string) string {
if strings.Contains(path, "/settings/revisions") {
return roleAdmin
}
// The DingTalk scan session replaces the shared browser credentials:
// admin-only, like every other credential surface. The QR image is a
// login artifact, so even polling it stays admin-only.
if strings.HasPrefix(path, "/api/v1/dingtalk-session") {
return roleAdmin
}
// Binding the internal/external knowledge bases re-routes every future
// annotation: admin-only, like the roster and production authority.
if path == "/api/v1/routing-bindings" && method != http.MethodGet {
+129
View File
@@ -0,0 +1,129 @@
package httpapi
import (
"bytes"
"encoding/json"
"io"
"log"
"net/http"
"os"
"strings"
"time"
)
// DingTalk login proxy. The scan-code login itself lives in the
// dingtalk-login sidecar (headless Chromium); the API is the authenticated
// gate and browser relay, so no QR or token crosses the web origin without a
// session. classifyRole keeps every non-GET at engineer+; capture replacement
// remains a deliberate human action.
//
// POST /api/v1/dingtalk-session -> start a login session {space?}
// GET /api/v1/dingtalk-session/{id} -> poll state (qr_png while waiting)
// DELETE /api/v1/dingtalk-session/{id} -> abort a session
func dingtalkSidecarURL() string {
return strings.TrimRight(strings.TrimSpace(os.Getenv("DINGTALK_LOGIN_SIDECAR_URL")), "/")
}
func requireDingtalkIdentity(w http.ResponseWriter, r *http.Request) bool {
_, ok := requireSessionIdentity(w, r)
return ok
}
func startDingtalkSession(w http.ResponseWriter, r *http.Request) {
if !requireDingtalkIdentity(w, r) {
return
}
var body struct {
Space string `json:"space"`
}
if r.Body != nil && r.ContentLength != 0 {
if err := decodeJSONStrict(r, &body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_request_body"})
return
}
}
payload, _ := json.Marshal(map[string]string{"space": strings.TrimSpace(body.Space)})
status, data := proxyDingtalk(http.MethodPost, "/sessions", payload)
log.Printf("dingtalk-login session started by %s (status %d)", actorFor(r), status)
writeProxyResult(w, status, data)
}
func getDingtalkSession(w http.ResponseWriter, r *http.Request) {
if !requireDingtalkIdentity(w, r) {
return
}
id := safeSessionID(r.PathValue("id"))
if id == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_session_id"})
return
}
status, data := proxyDingtalk(http.MethodGet, "/sessions/"+id, nil)
writeProxyResult(w, status, data)
}
func deleteDingtalkSession(w http.ResponseWriter, r *http.Request) {
if !requireDingtalkIdentity(w, r) {
return
}
id := safeSessionID(r.PathValue("id"))
if id == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid_session_id"})
return
}
status, data := proxyDingtalk(http.MethodDelete, "/sessions/"+id, nil)
log.Printf("dingtalk-login session %s closed by %s", id, actorFor(r))
writeProxyResult(w, status, data)
}
func safeSessionID(id string) string {
id = strings.TrimSpace(id)
if id == "" || len(id) > 64 {
return ""
}
for _, c := range id {
if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-') {
return ""
}
}
return id
}
func writeProxyResult(w http.ResponseWriter, status int, data []byte) {
if status == 0 || data == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "dingtalk_login_unavailable"})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, _ = w.Write(data)
}
func proxyDingtalk(method, path string, body []byte) (int, []byte) {
base := dingtalkSidecarURL()
if base == "" {
return 0, nil
}
var reader io.Reader
if body != nil {
reader = bytes.NewReader(body)
}
req, err := http.NewRequest(method, base+path, reader)
if err != nil {
return 0, nil
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Do(req)
if err != nil {
return 0, nil
}
defer resp.Body.Close()
data, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
if err != nil {
return resp.StatusCode, nil
}
return resp.StatusCode, data
}
+85
View File
@@ -0,0 +1,85 @@
package httpapi
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func TestDingtalkSessionProxyRelaysSidecarStates(t *testing.T) {
sidecar := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case r.Method == http.MethodPost && r.URL.Path == "/sessions":
w.WriteHeader(http.StatusCreated)
_ = json.NewEncoder(w).Encode(map[string]any{"id": "abc123", "state": "qr", "created_at": 1, "expires_at": 2})
case r.Method == http.MethodGet && r.URL.Path == "/sessions/abc123":
_ = json.NewEncoder(w).Encode(map[string]any{"id": "abc123", "state": "success"})
case r.Method == http.MethodGet && r.URL.Path == "/sessions/missing":
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"error":"session_not_found"}`))
default:
w.WriteHeader(http.StatusNotFound)
}
}))
defer sidecar.Close()
t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", sidecar.URL)
start := httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-session", strings.NewReader(`{}`))
start = start.WithContext(context.WithValue(start.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
rec := httptest.NewRecorder()
startDingtalkSession(rec, start)
if rec.Code != http.StatusCreated {
t.Fatalf("start proxy status = %d body=%s", rec.Code, rec.Body.String())
}
var created map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &created); err != nil {
t.Fatal(err)
}
if created["state"] != "qr" {
t.Fatalf("relayed state = %v", created["state"])
}
poll := httptest.NewRequest(http.MethodGet, "/api/v1/dingtalk-session/abc123", nil)
poll = poll.WithContext(context.WithValue(poll.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
poll.SetPathValue("id", "abc123")
rec = httptest.NewRecorder()
getDingtalkSession(rec, poll)
if !strings.Contains(rec.Body.String(), `"success"`) {
t.Fatalf("poll body = %s", rec.Body.String())
}
missing := httptest.NewRequest(http.MethodGet, "/api/v1/dingtalk-session/missing", nil)
missing = missing.WithContext(context.WithValue(missing.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
missing.SetPathValue("id", "missing")
rec = httptest.NewRecorder()
getDingtalkSession(rec, missing)
if rec.Code != http.StatusNotFound {
t.Fatalf("missing status = %d", rec.Code)
}
}
func TestDingtalkSessionRejectsUnauthenticatedAndHostileIDs(t *testing.T) {
rec := httptest.NewRecorder()
startDingtalkSession(rec, httptest.NewRequest(http.MethodPost, "/api/v1/dingtalk-session", nil))
if rec.Code != http.StatusUnauthorized {
t.Fatalf("unauthenticated start = %d, want 401", rec.Code)
}
if got := safeSessionID("../etc/passwd"); got != "" {
t.Fatalf("hostile id accepted: %q", got)
}
}
func TestDingtalkSessionUnavailableWithoutSidecar(t *testing.T) {
t.Setenv("DINGTALK_LOGIN_SIDECAR_URL", "")
req := httptest.NewRequest(http.MethodGet, "/api/v1/dingtalk-session/abc", nil)
req = req.WithContext(context.WithValue(req.Context(), sessionKey{}, sessionIdentity{Username: "tester", Role: roleAdmin}))
req.SetPathValue("id", "abc")
rec := httptest.NewRecorder()
getDingtalkSession(rec, req)
if rec.Code != http.StatusServiceUnavailable {
t.Fatalf("sidecar down status = %d, want 503", rec.Code)
}
}
+9
View File
@@ -255,6 +255,15 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("GET /api/v1/source-connections", func(w http.ResponseWriter, r *http.Request) {
listSourceConnections(w, r, config.Store)
})
mux.HandleFunc("POST /api/v1/dingtalk-session", func(w http.ResponseWriter, r *http.Request) {
startDingtalkSession(w, r)
})
mux.HandleFunc("GET /api/v1/dingtalk-session/{id}", func(w http.ResponseWriter, r *http.Request) {
getDingtalkSession(w, r)
})
mux.HandleFunc("DELETE /api/v1/dingtalk-session/{id}", func(w http.ResponseWriter, r *http.Request) {
deleteDingtalkSession(w, r)
})
mux.HandleFunc("POST /api/v1/source-connections/{id}/scan", func(w http.ResponseWriter, r *http.Request) {
triggerPPSourceScan(w, r, config)
})