fix(settings): add DingTalk spaces and render the real login QR

Address two gaps in the first DingTalk-session UI:
- add an explicit admin-only '+ 新增钉钉知识库' action on the data-source
  panel; it accepts an alidocs space URL, resolves the live name/root through
  the authenticated sidecar, writes the inventory root atomically, upserts a
  deterministic source connection, and enqueues its first catalog refresh
- read DingTalk's real QR canvas pixels rather than taking a DOM screenshot;
  select by dark-pixel content, composite onto a white quiet zone, and render
  at 320x320 so the dialog contains a large complete code, not a page thumbnail

The live refresh path resolves registered roots from the connection locator,
while existing name-based DingTalk sources remain compatible.
This commit is contained in:
姚章浩
2026-09-14 22:53:01 +08:00
parent 173b44abca
commit e60b10256a
15 changed files with 560 additions and 79 deletions
+3 -2
View File
@@ -119,8 +119,9 @@ func classifyRole(method, path string) string {
}
// 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") {
// login artifact, so even polling it stays admin-only. Space
// registration writes new source connections: same boundary.
if strings.HasPrefix(path, "/api/v1/dingtalk-session") || strings.HasPrefix(path, "/api/v1/dingtalk-spaces") {
return roleAdmin
}
// Binding the internal/external knowledge bases re-routes every future
+97
View File
@@ -2,13 +2,19 @@ package httpapi
import (
"bytes"
"context"
"encoding/json"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/jobs"
postgresstore "knowledge-governance/internal/platform/postgres"
)
// DingTalk login proxy. The scan-code login itself lives in the
@@ -76,6 +82,97 @@ func deleteDingtalkSession(w http.ResponseWriter, r *http.Request) {
writeProxyResult(w, status, data)
}
// registerDingtalkSpace resolves a DingTalk knowledge-base space URL through
// the login sidecar and, on success, registers the returned space as a
// source connection (deterministic id, enabled, manual-only schedule until an
// admin sets an interval). Re-registering the same space re-syncs name/root.
func registerDingtalkSpace(w http.ResponseWriter, r *http.Request, config Config) {
if !requireDingtalkIdentity(w, r) {
return
}
operationID, ok := requireOperationID(w, r)
if !ok {
return
}
var input struct {
URL string `json:"url"`
}
if err := decodeJSONStrict(r, &input); err != nil || strings.TrimSpace(input.URL) == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "url is required"})
return
}
payload, _ := json.Marshal(map[string]string{"url": strings.TrimSpace(input.URL)})
status, data := proxyDingtalk(http.MethodPost, "/spaces/add", payload)
if status != http.StatusOK {
if status == 0 {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "dingtalk_login_unavailable"})
return
}
// Relay the sidecar's error (login_required / space_not_found /
// name_conflict) verbatim; bodies are machine codes, no secrets.
writeProxyResult(w, status, data)
return
}
var resolved struct {
Key string `json:"key"`
Name string `json:"name"`
Root string `json:"root"`
}
if err := json.Unmarshal(data, &resolved); err != nil || resolved.Key == "" || resolved.Name == "" || resolved.Root == "" {
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "invalid sidecar registration response"})
return
}
store, ok := config.Store.(interface {
RegisterDingtalkSpace(context.Context, postgresstore.RegisterDingtalkSpaceInput) (string, error)
})
if !ok {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "registration_unavailable"})
return
}
spaceID := extractDingtalkSpaceID(input.URL)
if spaceID == "" {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid space url"})
return
}
connectionID, err := store.RegisterDingtalkSpace(r.Context(), postgresstore.RegisterDingtalkSpaceInput{
RootKey: resolved.Key, Name: resolved.Name, SpaceID: spaceID, RootID: resolved.Root, Now: config.Now(),
})
if err != nil {
writeJSON(w, http.StatusConflict, map[string]string{"error": "space_registration_conflict"})
return
}
// First scan is enqueued right away: the new connection has no catalog
// head yet, so the generic sources/{id}/refresh endpoint would 404 until
// the first snapshot exists.
if enqueuer, ok := config.Store.(interface {
EnqueueCatalogRefreshWithOperation(context.Context, governance.CatalogSource, string, time.Time) (jobs.Job, bool, error)
}); ok {
if _, _, enqueueErr := enqueuer.EnqueueCatalogRefreshWithOperation(r.Context(), governance.CatalogSource{
ConnectionID: connectionID, SourceType: governance.SourceTypeDingTalk, Name: resolved.Name,
}, operationID+":first", config.Now().UTC()); enqueueErr != nil {
log.Printf("dingtalk space %s registered but first refresh enqueue failed: %v", connectionID, enqueueErr)
}
}
log.Printf("dingtalk space %q registered as connection %s by %s", resolved.Name, connectionID, actorFor(r))
writeJSON(w, http.StatusCreated, map[string]any{"data": map[string]string{
"connection_id": connectionID, "name": resolved.Name,
}})
}
var dingtalkSpacePattern = regexp.MustCompile(`/spaces/([A-Za-z0-9_-]+)`)
func extractDingtalkSpaceID(raw string) string {
match := dingtalkSpacePattern.FindStringSubmatch(raw)
if len(match) == 2 {
return match[1]
}
trimmed := strings.TrimSpace(raw)
if regexp.MustCompile(`^[A-Za-z0-9_-]{8,64}$`).MatchString(trimmed) {
return trimmed
}
return ""
}
func safeSessionID(id string) string {
id = strings.TrimSpace(id)
if id == "" || len(id) > 64 {
@@ -70,6 +70,15 @@ func TestDingtalkSessionRejectsUnauthenticatedAndHostileIDs(t *testing.T) {
if got := safeSessionID("../etc/passwd"); got != "" {
t.Fatalf("hostile id accepted: %q", got)
}
for _, test := range []struct{ raw, want string }{
{"https://alidocs.dingtalk.com/i/spaces/9JOGOQneRgkneX4Q/overview?rnd=1", "9JOGOQneRgkneX4Q"},
{"9JOGOQneRgkneX4Q", "9JOGOQneRgkneX4Q"},
{"https://example.com/not-a-space", ""},
} {
if got := extractDingtalkSpaceID(test.raw); got != test.want {
t.Fatalf("extractDingtalkSpaceID(%q) = %q, want %q", test.raw, got, test.want)
}
}
}
func TestDingtalkSessionUnavailableWithoutSidecar(t *testing.T) {
+3
View File
@@ -258,6 +258,9 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("POST /api/v1/dingtalk-session", func(w http.ResponseWriter, r *http.Request) {
startDingtalkSession(w, r)
})
mux.HandleFunc("POST /api/v1/dingtalk-spaces", func(w http.ResponseWriter, r *http.Request) {
registerDingtalkSpace(w, r, config)
})
mux.HandleFunc("GET /api/v1/dingtalk-session/{id}", func(w http.ResponseWriter, r *http.Request) {
getDingtalkSession(w, r)
})
@@ -0,0 +1,92 @@
package postgres
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
"github.com/jackc/pgx/v5"
)
// DingTalk space registration: a knowledge-base space discovered through the
// login sidecar becomes a source_connections row with a DETERMINISTIC id,
// derived the same way the catalog importer derives stable ids
// ('sc-' + sha256('dingtalk-'+root_key)[:32]). Re-registering the same space
// is an idempotent re-sync of name/root, never a duplicate row. New rows are
// enabled but carry no schedule (next_refresh_at stays NULL): automatic scans
// begin only after an admin sets an interval — same posture as the existing
// imported DingTalk sources.
// RegisterDingtalkSpaceInput describes one space resolved by the sidecar.
type RegisterDingtalkSpaceInput struct {
RootKey string // sidecar inventory key, e.g. "atom" or "space-1f2e3d4c5b"
Name string // live space name from DingTalk spaceProfile
SpaceID string // alidocs space id from the URL
RootID string // root dentry uuid
Now time.Time
}
func (in RegisterDingtalkSpaceInput) ConnectionID() string {
sum := sha256.Sum256([]byte("dingtalk-" + in.RootKey))
return "sc-" + hex.EncodeToString(sum[:])[:32]
}
func (in RegisterDingtalkSpaceInput) validate() error {
if in.Now.IsZero() {
return errors.New("dingtalk space registration: now is required")
}
if !validShortID(in.RootKey) || strings.TrimSpace(in.Name) == "" || len(in.Name) > 255 {
return errors.New("dingtalk space registration: invalid key or name")
}
for _, id := range []string{in.SpaceID, in.RootID} {
if id == "" || len(id) > 128 || strings.ContainsAny(id, " \t\r\n/") {
return errors.New("dingtalk space registration: invalid identifier")
}
}
return nil
}
func (s *Store) RegisterDingtalkSpace(ctx context.Context, in RegisterDingtalkSpaceInput) (string, error) {
if err := in.validate(); err != nil {
return "", err
}
connectionID := in.ConnectionID()
var existingName, existingRoot string
err := s.db.QueryRow(ctx, `SELECT name, base_url FROM source_connections WHERE id = $1`, connectionID).Scan(&existingName, &existingRoot)
switch {
case errors.Is(err, pgx.ErrNoRows):
// fresh registration below
case err != nil:
return "", fmt.Errorf("load dingtalk connection: %w", err)
default:
// A different space resolved under the same key must not silently
// rewrite the existing connection.
if !strings.HasPrefix(existingRoot, "spaces/"+in.RootID+"?") {
return "", fmt.Errorf("dingtalk space registration: connection %s already serves another root", connectionID)
}
}
// base_url stores a stable, non-secret locator (the root dentry uuid plus
// the space id) so re-registration can verify identity and the UI can
// explain what a DingTalk connection points at.
locator := "spaces/" + in.RootID + "?space=" + in.SpaceID
_, err = s.db.Exec(ctx, `
INSERT INTO source_connections (
id, source_type, name, base_url, secret_ref, enabled,
schedule, last_health, created_at, updated_at, updated_by
) VALUES ($1, 'dingtalk', $2, $3, '', TRUE, '{}'::jsonb, '{}'::jsonb, $4, $4, $5)
ON CONFLICT (id) DO UPDATE
SET name = EXCLUDED.name, base_url = EXCLUDED.base_url,
updated_at = EXCLUDED.updated_at, updated_by = EXCLUDED.updated_by`,
connectionID, in.Name, locator, in.Now.UTC(), "dingtalk-registration")
if err != nil {
if isUniqueViolation(err) {
return "", fmt.Errorf("dingtalk space registration: name %q already used by another connection", in.Name)
}
return "", fmt.Errorf("register dingtalk space: %w", err)
}
return connectionID, nil
}
@@ -0,0 +1,25 @@
package postgres
import (
"testing"
"time"
)
func TestRegisterDingtalkSpaceConnectionIDIsStableAndCompatibleWithImporter(t *testing.T) {
input := RegisterDingtalkSpaceInput{
RootKey: "atom", Name: "ATOM", SpaceID: "9JOGOQneRgkneX4Q",
RootID: "root-atom", Now: time.Now(),
}
first := input.ConnectionID()
second := input.ConnectionID()
if first != second || len(first) != 35 || first[:3] != "sc-" {
t.Fatalf("unstable connection id: %q / %q", first, second)
}
if err := input.validate(); err != nil {
t.Fatalf("valid registration rejected: %v", err)
}
input.SpaceID = "../bad"
if err := input.validate(); err == nil {
t.Fatal("hostile space id accepted")
}
}