feat(qaops): 接入真实通讯录采集并补全根部门
This commit is contained in:
@@ -0,0 +1,79 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrDirectorySync = errors.New("directory synchronization failed; active snapshot was not replaced")
|
||||
|
||||
type ExecDirectoryRunner struct {
|
||||
Python string
|
||||
Script string
|
||||
RuntimeRoot string
|
||||
SpoolRoot string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Only server-owned paths cross this boundary. Credentials are read by the
|
||||
// existing directory client from its private file, never passed in argv/logs.
|
||||
func (r ExecDirectoryRunner) Run(ctx context.Context) (Import, error) {
|
||||
for _, path := range []string{r.Python, r.Script, r.RuntimeRoot, r.SpoolRoot} {
|
||||
if !filepath.IsAbs(path) || filepath.Clean(path) != path {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
}
|
||||
if r.Timeout == 0 {
|
||||
r.Timeout = 20 * time.Minute
|
||||
}
|
||||
if r.Timeout < time.Millisecond || r.Timeout > 30*time.Minute {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
work, err := os.MkdirTemp(r.SpoolRoot, "qa-directory-")
|
||||
if err != nil {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
defer os.RemoveAll(work)
|
||||
output := filepath.Join(work, "directory.json")
|
||||
runCtx, cancel := context.WithTimeout(ctx, r.Timeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(runCtx, r.Python, r.Script, "--runtime-root", r.RuntimeRoot, "--output", output, "--fetch-live-directory")
|
||||
cmd.Dir = r.RuntimeRoot
|
||||
cmd.Env = []string{"PYTHONUNBUFFERED=1"}
|
||||
for _, key := range []string{"PATH", "HOME", "TMPDIR", "LANG", "TZ"} {
|
||||
if value, ok := os.LookupEnv(key); ok {
|
||||
cmd.Env = append(cmd.Env, key+"="+value)
|
||||
}
|
||||
}
|
||||
cmd.Stdout = io.Discard
|
||||
cmd.Stderr = io.Discard
|
||||
cmd.WaitDelay = 3 * time.Second
|
||||
if err = cmd.Run(); err != nil {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
info, err := os.Lstat(output)
|
||||
if err != nil || !info.Mode().IsRegular() || info.Mode().Perm()&0077 != 0 || info.Size() < 1 || info.Size() > 16<<20 {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
file, err := os.Open(output)
|
||||
if err != nil {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
defer file.Close()
|
||||
decoder := json.NewDecoder(io.LimitReader(file, (16<<20)+1))
|
||||
decoder.DisallowUnknownFields()
|
||||
var result Import
|
||||
if decoder.Decode(&result) != nil || decoder.Decode(&struct{}{}) != io.EOF || !result.Complete || result.Source != "weekly_report_live" || result.SyncedAt.IsZero() || result.SyncedAt.After(time.Now().Add(time.Minute)) {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
if _, err = Preview(result.Directory, nil); err != nil {
|
||||
return Import{}, ErrDirectorySync
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDirectoryBridgeRegressionSuiteRunsInDefaultCI(t *testing.T) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, "python3", "-m", "unittest", "discover", "-s", "scripts", "-p", "test_qa_ops_directory_sync.py", "-v")
|
||||
cmd.Dir = filepath.Join("..", "..")
|
||||
if output, err := cmd.CombinedOutput(); err != nil {
|
||||
t.Fatalf("directory bridge regression failed: %v\n%s", err, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectoryRunnerParsesPrivateOutputAndRemovesSpool(t *testing.T) {
|
||||
t.Setenv("DINGTALK_CLIENT_SECRET", "fixture-credential-do-not-forward")
|
||||
root := t.TempDir()
|
||||
spool := filepath.Join(root, "spool")
|
||||
if err := os.Mkdir(spool, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := filepath.Join(root, "fake-sync.sh")
|
||||
fixture := `{"source":"weekly_report_live","synced_at":"2026-10-01T00:00:00Z","complete":true,"directory":{"departments":[{"id":"root","parent_id":"","name":"隔离测试部门"}],"people":[{"id":"fixture-user","department_ids":["root"]}]}}`
|
||||
body := "#!/bin/sh\nif [ -n \"${DINGTALK_CLIENT_SECRET:-}\" ]; then exit 3; fi\nwhile [ \"$#\" -gt 0 ]; do if [ \"$1\" = --output ]; then output=$2; shift; fi; shift; done\numask 077\nprintf '%s' '" + fixture + "' > \"$output\"\n"
|
||||
if err := os.WriteFile(script, []byte(body), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := ExecDirectoryRunner{Python: "/bin/sh", Script: script, RuntimeRoot: root, SpoolRoot: spool, Timeout: time.Second}
|
||||
result, err := runner.Run(context.Background())
|
||||
if err != nil || len(result.Directory.People) != 1 {
|
||||
t.Fatalf("runner failed: %v", err)
|
||||
}
|
||||
entries, err := os.ReadDir(spool)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatal("personnel spool leaked")
|
||||
}
|
||||
if err := os.WriteFile(script, []byte("#!/bin/sh\nprintf 'secret-driver-detail' >&2\nexit 1\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = runner.Run(context.Background())
|
||||
if err == nil || strings.Contains(err.Error(), "secret-driver-detail") {
|
||||
t.Fatal("runner error is missing or leaks child stderr")
|
||||
}
|
||||
entries, _ = os.ReadDir(spool)
|
||||
if len(entries) != 0 {
|
||||
t.Fatal("failed runner leaked spool")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectoryRunnerRejectsMalformedOrPublicPersonnelOutput(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
for _, mode := range []string{"malformed", "public"} {
|
||||
script := filepath.Join(root, mode+".sh")
|
||||
body := "#!/bin/sh\numask 077\nwhile [ \"$#\" -gt 0 ]; do if [ \"$1\" = --output ]; then output=$2; shift; fi; shift; done\nprintf '%s' '{not-json}' > \"$output\"\n"
|
||||
if mode == "public" {
|
||||
body += "printf '%s' '{\"source\":\"weekly_report_live\",\"synced_at\":\"2026-10-01T00:00:00Z\",\"complete\":true,\"directory\":{\"departments\":[{\"id\":\"root\",\"parent_id\":\"\",\"name\":\"fixture\"}],\"people\":[{\"id\":\"fixture-user\",\"department_ids\":[\"root\"]}]}}' > \"$output\"\nchmod 644 \"$output\"\n"
|
||||
}
|
||||
if err := os.WriteFile(script, []byte(body), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := ExecDirectoryRunner{Python: "/bin/sh", Script: script, RuntimeRoot: root, SpoolRoot: root, Timeout: time.Second}
|
||||
if _, err := runner.Run(context.Background()); err == nil {
|
||||
t.Fatal("invalid output accepted")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDirectoryRunnerDeadlineStopsChildAndCleansPrivateSpool(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
spool := filepath.Join(root, "spool")
|
||||
if err := os.Mkdir(spool, 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
script := filepath.Join(root, "timeout.sh")
|
||||
if err := os.WriteFile(script, []byte("#!/bin/sh\nexec sleep 30\n"), 0700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
runner := ExecDirectoryRunner{Python: "/bin/sh", Script: script, RuntimeRoot: root, SpoolRoot: spool, Timeout: 50 * time.Millisecond}
|
||||
started := time.Now()
|
||||
if _, err := runner.Run(context.Background()); err == nil {
|
||||
t.Fatal("timed-out source reported success")
|
||||
}
|
||||
if time.Since(started) > 5*time.Second {
|
||||
t.Fatal("source process cleanup is unbounded")
|
||||
}
|
||||
entries, err := os.ReadDir(spool)
|
||||
if err != nil || len(entries) != 0 {
|
||||
t.Fatal("timed-out source retained personnel spool")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user