package main import ( "context" "io" "net" "os" "path/filepath" "strings" "testing" "time" agentpb "git.ipao.vip/rogee/go-sip/gen/agent" "git.ipao.vip/rogee/go-sip/internal/rpc" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" "google.golang.org/grpc/status" ) func TestCurrentAgentCommandRejectsRealModesAndObsoleteCallEntry(t *testing.T) { for _, tc := range []struct { name string args []string want string }{ {"real", []string{"--mode", "real"}, "Mock"}, {"mixed", []string{"--mode", "mixed"}, "Mock"}, {"old call-once", []string{"--call-once"}, "unknown flag"}, {"no deployment identity", []string{"--mode", "mock"}, "AGENT_ID"}, } { t.Run(tc.name, func(t *testing.T) { state := filepath.Join(t.TempDir(), "session.json") t.Setenv("AGENT_ID", "") t.Setenv("AGENT_SESSION_PATH", state) command := newCurrentAgentCommand() command.SetOut(io.Discard) command.SetErr(io.Discard) command.SetArgs(tc.args) if err := command.Execute(); err == nil || !strings.Contains(err.Error(), tc.want) { t.Fatalf("unsafe current Agent command was admitted: %v", err) } if _, err := os.Stat(state); !os.IsNotExist(err) { t.Fatalf("rejected command opened durable Agent state: %v", err) } }) } } func TestLoadMockAppliedSIPAcceptsOnlyExplicitLocalFacts(t *testing.T) { path := filepath.Join(t.TempDir(), "applied-sip.json") if err := os.WriteFile(path, []byte(`{"trunks":{"trunk-mock":8}}`), 0600); err != nil { t.Fatal(err) } applied, err := loadMockAppliedSIP(path) if err != nil || len(applied) != 1 || applied["trunk-mock"] != 8 { t.Fatalf("explicit isolated applied SIP facts were changed: %v %v", applied, err) } if _, err := loadMockAppliedSIP(""); err == nil { t.Fatal("missing applied SIP facts were defaulted") } for _, data := range []string{ `{"trunks":{}}`, `{"trunks":{"trunk-mock":0}}`, `{"trunks":{"":8}}`, `{"trunks":{"trunk-mock":8},"schema_version":"v3"}`, `{"trunks":{"trunk-mock":8}} {}`, } { if err := os.WriteFile(path, []byte(data), 0600); err != nil { t.Fatal(err) } if _, err := loadMockAppliedSIP(path); err == nil { t.Fatalf("unapproved Mock SIP fixture was admitted: %s", data) } } } func TestCurrentAgentCommandServesPinnedMutualTLSOnly(t *testing.T) { ca, agentCert, agentKey, dispatcherCert, dispatcherKey, dispatcherLeaf := localCommandCertificates(t) settings, _ := currentAgentSetupFixture(t) for path, body := range map[string][]byte{ settings.CAFile: ca, settings.CertFile: agentCert, settings.KeyFile: agentKey, } { if err := os.WriteFile(path, body, 0600); err != nil { t.Fatal(err) } } scenarioFile := filepath.Join(settings.RecoveryRoot, "scenario.json") appliedFile := filepath.Join(settings.RecoveryRoot, "applied-sip.json") if err := os.WriteFile(scenarioFile, []byte(`{"inbound_pcm16":"AQABAA==","script":{"Turns":[{"Transcript":"synthetic fixture"}]},"max_wav_bytes":4096,"expected_recording":false,"outcome":"no_answer","reason_message":"synthetic no answer"}`), 0600); err != nil { t.Fatal(err) } if err := os.WriteFile(appliedFile, []byte(`{"trunks":{"trunk-mock":8}}`), 0600); err != nil { t.Fatal(err) } reserved, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } settings.Listen = reserved.Addr().String() _ = reserved.Close() for name, value := range map[string]string{ "AGENT_ID": settings.AgentID, "CELL_ID": settings.CellID, "AGENT_GRPC_LISTEN": settings.Listen, "AGENT_SESSION_PATH": settings.SessionPath, "AGENT_RECOVERY_ROOT": settings.RecoveryRoot, "DISPATCHER_ID": settings.DispatcherID, "DISPATCHER_GRPC_ENDPOINT": settings.DispatcherEndpoint, "DISPATCHER_GRPC_SERVER_NAME": settings.DispatcherServerName, "MTLS_CA_FILE": settings.CAFile, "MTLS_CERT_FILE": settings.CertFile, "MTLS_KEY_FILE": settings.KeyFile, "MTLS_PEER_CERT_FINGERPRINTS": rpc.CertificateFingerprint(dispatcherLeaf), "AGENT_MOCK_SCENARIO_FILE": scenarioFile, "AGENT_MOCK_APPLIED_SIP_FILE": appliedFile, } { t.Setenv(name, value) } process, cancel := context.WithCancel(context.Background()) command := newCurrentAgentCommand() command.SetOut(io.Discard) command.SetErr(io.Discard) command.SetContext(process) command.SetArgs([]string{"--mode", "mock"}) finished := make(chan error, 1) go func() { finished <- command.Execute() }() finishedConsumed := false t.Cleanup(func() { cancel() if finishedConsumed { return } select { case err := <-finished: if err != nil { t.Errorf("isolated Agent shutdown failed: %v", err) } case <-time.After(5 * time.Second): t.Error("isolated Agent did not stop after process cancellation") } }) trustedTLS, err := rpc.NewClientTLSConfig(ca, dispatcherCert, dispatcherKey, "agent.local") if err != nil { t.Fatal(err) } dial, stopDial := context.WithTimeout(context.Background(), 6*time.Second) defer stopDial() trusted, err := grpc.DialContext(dial, settings.Listen, grpc.WithTransportCredentials(credentials.NewTLS(trustedTLS)), grpc.WithBlock()) if err != nil { select { case startupErr := <-finished: finishedConsumed = true t.Fatalf("Agent startup failed: %v (dial: %v)", startupErr, err) default: t.Fatalf("isolated Agent mTLS listener unavailable: %v", err) } } defer trusted.Close() probe := &agentpb.GetAgentStatusRequest{ Meta: &agentpb.RequestMeta{ProtocolVersion: "agent.v1", RequestId: "mock-status", TraceId: "mock-status", OperationId: "mock-status", AgentId: settings.AgentID, CellId: settings.CellID}, Target: &agentpb.AgentBinding{AgentId: settings.AgentID, CellId: settings.CellID}, } trustedClient := agentpb.NewAgentControlServiceClient(trusted) response, err := trustedClient.GetAgentStatus(dial, probe) if err != nil || response.GetStatus().GetAgentId() != settings.AgentID || response.GetStatus().GetCellId() != settings.CellID { t.Fatalf("trusted D could not probe the actual Agent command: response=%v err=%v", response, err) } activation := &agentpb.ActivateAgentRequest{ Meta: &agentpb.RequestMeta{ProtocolVersion: "agent.v1", RequestId: "bind-dispatcher", TraceId: "bind-dispatcher", OperationId: "bind-dispatcher", AgentId: settings.AgentID, CellId: settings.CellID, BootId: response.GetStatus().GetBootId(), DispatcherEpoch: "epoch-test"}, Binding: &agentpb.AgentBinding{AgentId: settings.AgentID, CellId: settings.CellID, ExpectedBootId: response.GetStatus().GetBootId(), DispatcherEpoch: "epoch-test", DispatcherId: "22222222-2222-4222-8222-222222222222"}, ActivationOperationId: "bind-dispatcher", } if _, err := trustedClient.ActivateAgent(dial, activation); status.Code(err) != codes.PermissionDenied { t.Fatalf("pinned certificate could claim another Dispatcher identity: %v", err) } if _, err := os.Stat(settings.SessionPath); !os.IsNotExist(err) { t.Fatalf("unapproved Dispatcher wrote a session: %v", err) } activation.Binding.DispatcherId = settings.DispatcherID if _, err := trustedClient.ActivateAgent(dial, activation); err != nil { t.Fatalf("approved Dispatcher could not activate the Agent: %v", err) } untrustedTLS, err := rpc.NewClientTLSConfig(ca, agentCert, agentKey, "agent.local") if err != nil { t.Fatal(err) } untrusted, err := grpc.NewClient(settings.Listen, grpc.WithTransportCredentials(credentials.NewTLS(untrustedTLS))) if err != nil { t.Fatal(err) } defer untrusted.Close() if _, err := agentpb.NewAgentControlServiceClient(untrusted).GetAgentStatus(dial, probe); status.Code(err) != codes.PermissionDenied { t.Fatalf("unpinned but CA-valid client could probe Agent: %v", err) } }