package libraryagent import ( "context" "os" "strings" "sync" "testing" "time" ) // unix socket 路径有长度上限,测试目录要用短的(TMPDIR 太深)。 func shortSocketDir(t *testing.T) string { t.Helper() dir, err := os.MkdirTemp("/tmp", "kgswap-") if err != nil { t.Fatal(err) } t.Cleanup(func() { os.RemoveAll(dir) }) return dir } // 两个真实 agent、两个 socket:负例把调用方指到"另一个实例"的 socket 上, // 断言**错误 agent 一次 capture 都没跑**(不是跑完再拒),正例走对 socket 正常封存。 func TestCaptureRequestIsRefusedBeforeAnySourceOperationWhenSocketIsSwapped(t *testing.T) { rightAgent, rightSocket, rightCalls := agentWithProject(t, "kgmaint-weknora", "kgmaint-app") wrongAgent, wrongSocket, wrongCalls := agentWithProject(t, "weknora071full", "WKNFull-app") serveAgent(t, rightAgent, rightSocket) serveAgent(t, wrongAgent, wrongSocket) expectation := NewExpectation("kgmaint-weknora", "kgmaint-app", "") ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // 负例:调用方手上的 socket 已被换成另一个实例的执行器。 result, err := Capture(ctx, ClientConfig{Socket: wrongSocket, Timeout: 5 * time.Second}, "internal", "lib-swap", expectation) if err == nil || result.OK { t.Fatalf("capture against the wrong executor was accepted: %+v", result) } if !strings.Contains(result.Error, "期望") { t.Fatalf("refusal should name the mismatch: %q", result.Error) } if calls := captureCalls(wrongCalls()); len(calls) != 0 { t.Fatalf("wrong executor ran the capture binary %d time(s): %v", len(calls), calls) } // 旁证:错误的执行器进程本身仍然可用(health 正常),拒绝来自身份比对而不是不可达。 health, err := Health(ctx, ClientConfig{Socket: wrongSocket, Timeout: 5 * time.Second}) if err != nil || !health.OK { t.Fatalf("wrong executor should still answer health: %v %+v", err, health) } // 正例:同一份期望打到正确的 socket,正常封存一次。 result, err = Capture(ctx, ClientConfig{Socket: rightSocket, Timeout: 5 * time.Second}, "internal", "lib-swap", expectation) if err != nil || !result.OK { t.Fatalf("capture against the right executor failed: %v %+v", err, result) } if calls := captureCalls(rightCalls()); len(calls) != 1 { t.Fatalf("right executor ran %d time(s): %v", len(calls), calls) } if calls := captureCalls(wrongCalls()); len(calls) != 0 { t.Fatalf("wrong executor ran after the positive case: %v", calls) } } // 缺期望、期望指纹对不上、期望里 source_app 不同,都必须 fail closed 且不跑子进程。 func TestCaptureFailsClosedWithoutACompleteExpectation(t *testing.T) { agent, socket, calls := agentWithProject(t, "kgmaint-weknora", "kgmaint-app") serveAgent(t, agent, socket) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() tampered := NewExpectation("kgmaint-weknora", "kgmaint-app", "") tampered.Project = "someone-else" // 字段改了、指纹没改:请求在半路被改过 cases := []struct { name string expectation Expectation text string }{ {name: "missing expectation", expectation: Expectation{}, text: "缺少完整的期望执行器身份"}, {name: "tampered expectation", expectation: tampered, text: "缺少完整的期望执行器身份"}, {name: "wrong source app", expectation: NewExpectation("kgmaint-weknora", "WKNFull-app", ""), text: "源容器不一致"}, } for _, test := range cases { result, err := Capture(ctx, ClientConfig{Socket: socket, Timeout: 5 * time.Second}, "internal", "lib-"+strings.ReplaceAll(test.name, " ", "-"), test.expectation) if err == nil || result.OK { t.Fatalf("%s: accepted %+v", test.name, result) } if !strings.Contains(result.Error, test.text) { t.Fatalf("%s: error %q", test.name, result.Error) } } if calls := captureCalls(calls()); len(calls) != 0 { t.Fatalf("capture binary ran despite a refused identity: %v", calls) } } // 恢复路径不受期望约束:它只把写入者恢复回来,任何身份都必须能执行。 func TestRecoverStaysAvailableRegardlessOfExpectation(t *testing.T) { agent, socket, calls := agentWithProject(t, "kgmaint-weknora", "kgmaint-app") serveAgent(t, agent, socket) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() result, err := Recover(ctx, ClientConfig{Socket: socket, Timeout: 5 * time.Second}) if err != nil || !result.OK { t.Fatalf("recover refused: %v %+v", err, result) } if len(recoverCalls(calls())) == 0 { t.Fatal("recover did not run the recovery command") } } // agentWithProject 造一个真实 agent(不跑真命令),返回它自己的调用记录。 func agentWithProject(t *testing.T, project, sourceApp string) (*Agent, string, func() []string) { t.Helper() root := shortSocketDir(t) var mu sync.Mutex var calls []string config := Config{ Socket: root + "/agent.sock", Binary: "/bin/echo", ArchiveRoot: root + "/library", JournalRoot: root + "/freeze", SourceApp: sourceApp, SourcePG: "pg", SourceES: "es", Project: project, Writers: "app", NonWriters: "frontend=UI only", MaxDuration: time.Minute, Run: func(_ context.Context, name string, args ...string) ([]byte, error) { mu.Lock() calls = append(calls, name+" "+strings.Join(args, " ")) mu.Unlock() return []byte(`{"snapshot_id":"abc","state":"succeeded"}`), nil }, } agent, err := New(config) if err != nil { t.Fatal(err) } return agent, config.Socket, func() []string { mu.Lock() defer mu.Unlock() return append([]string(nil), calls...) } }