using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Text.Json; using System.Threading; using System.Threading.Tasks; namespace Scorpiox.Ssms; /// /// scorpiox-ssms-client.console — P/Invoke test harness + CLI for /// scorpiox-ssms-client.dll / libscorpiox-ssms-client.so. /// /// --test run the full offline suite against a mock SSMS API /// server on 127.0.0.1 (raw TcpListener, no admin rights needed) — every export, /// PASS/FAIL per row, exit 0 only when all pass /// (default) CLI mode against a live node: /// set host with --host URL or env SSMS_HOST /// secrets via env only: SSMS_NODE_PWD, SSMS_NODE_JWT /// public static class Program { static int s_pass, s_fail; static void Check(bool cond, string name) { if (cond) { s_pass++; Console.WriteLine($"PASS {name}"); } else { s_fail++; Console.WriteLine($"FAIL {name} [{SsmsClientInterop.LastError}]"); } } public static int Main(string[] args) { if (args.Length > 0 && args[0] == "--test") return RunTests(); return RunCli(args); } /* ═══════════════ mock SSMS API server ═══════════════ */ sealed class MockServer : IDisposable { readonly TcpListener _listener; public string Url => $"http://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/"; public volatile string LastPath = ""; public volatile string LastQuery = ""; public volatile string LastBody = ""; public volatile string LastMethod = ""; public volatile string LastBotPwdHeader = ""; public volatile string LastAuthHeader = ""; static readonly Dictionary Routes = new() { ["/ping"] = """{"ok":true,"service":"scorpiox-ssms-api","version":"1.0.0"}""", ["/connections"] = """{"ok":true,"servers":[{"id":"srv-1","name":"local","host":"db.internal","port":1433,"auth_mode":"sql","user":"sa","default_db":"master","read_only":false,"encrypt":true}],"error":null}""", ["/tree"] = """{"ok":true,"nodes":[{"id":"tbl-dbo-w","kind":"table","label":"dbo.widgets","has_children":true,"meta":{"db":"master"}},{"id":"tbl-dbo-g","kind":"table","label":"dbo.gadgets","has_children":true,"meta":{}}],"error":null}""", ["/query"] = """{"ok":true,"spid":54,"elapsed_ms":12,"batches":[{"batch":1,"results":[{"columns":[{"name":"id","type":"int","nullable":false},{"name":"name","type":"nvarchar","nullable":true},{"name":"note","type":"nvarchar","nullable":true}],"rows":[[1,"alpha","first"],[2,"beta",null],[3,"gamma","third"]],"truncated":false}],"messages":[{"type":"info","rows_affected":3}]}],"error":null}""", ["/editgrid"] = """{"ok":true,"columns":[{"name":"id","type":"int","nullable":false},{"name":"qty","type":"int","nullable":true}],"pk_columns":["id"],"rows":[[10,5],[11,null]],"read_only_reason":null,"error":null}""", ["/script"] = """{"ok":true,"title":"dbo.widgets Script","sql":"CREATE TABLE [dbo].[widgets] ( [id] int NOT NULL );","params":[],"props":{"rows":"1234","data_kb":"64"},"error":null}""", ["/activity"] = """{"ok":true,"columns":[{"name":"spid","type":"int"},{"name":"status","type":"nvarchar"}],"rows":[[54,"running"],[61,"suspended"]],"error":null}""", ["/storage"] = """{"ok":true,"columns":[{"name":"name","type":"nvarchar"},{"name":"size_mb","type":"numeric"}],"rows":[["master",5.5],["tempdb",16.0]],"error":null}""", ["/admin"] = """{"ok":true,"columns":[{"name":"name","type":"nvarchar"},{"name":"enabled","type":"bit"}],"rows":[["NightlyBackup",true],["IndexCleanup",false]],"error":null}""", ["/agent"] = """{"ok":true,"columns":[{"name":"name","type":"nvarchar"},{"name":"enabled","type":"bit"}],"rows":[["NightlyBackup",true]],"error":null}""", ["/security"] = """{"ok":true,"columns":[{"name":"name","type":"nvarchar"}],"rows":[["sa"],["##MS_PolicyResourcePurchaser##"]],"error":null}""", ["/logs"] = """{"ok":true,"columns":[{"name":"logdate","type":"datetime"},{"name":"text","type":"nvarchar"}],"rows":[["2026-11-16 09:00:00","Server is listening on 'TCP'."]],"error":null}""", }; public MockServer() { // port 0 = OS-assigned free port; never collide, never privileged _listener = new TcpListener(IPAddress.Loopback, 0); _listener.Start(); Task.Run(Loop); } async void Loop() { try { while (_listener.Server.IsBound) { var client = await _listener.AcceptTcpClientAsync(); _ = Task.Run(() => Handle(client)); } } catch { /* listener closed */ } } async Task Handle(TcpClient client) { try { using (client) { using var ms = new MemoryStream(); client.ReceiveTimeout = 10000; using var stream = client.GetStream(); var buf = new byte[8192]; string headerBlob = ""; int headerEnd = -1; while (true) { int n = await stream.ReadAsync(buf, 0, buf.Length); if (n <= 0) break; ms.Write(buf, 0, n); headerBlob = Encoding.GetEncoding("ISO-8859-1").GetString(ms.ToArray()); headerEnd = headerBlob.IndexOf("\r\n\r\n"); if (headerEnd >= 0) break; } if (headerEnd < 0) return; string head = headerBlob[..headerEnd]; byte[] raw = ms.ToArray(); var lines = head.Split("\r\n"); var parts = lines[0].Split(' '); LastMethod = parts.Length > 0 ? parts[0] : ""; string uri = parts.Length > 1 ? parts[1] : "/"; int q = uri.IndexOf('?'); string path = q >= 0 ? uri[..q] : uri; LastPath = path; LastQuery = q >= 0 ? uri[(q + 1)..] : ""; int contentLength = 0; LastBotPwdHeader = ""; LastAuthHeader = ""; for (int i = 1; i < lines.Length; i++) { int c = lines[i].IndexOf(':'); if (c < 0) continue; string k = lines[i][..c].Trim(); string v = lines[i][(c + 1)..].Trim(); if (k.Equals("Content-Length", StringComparison.OrdinalIgnoreCase)) int.TryParse(v, out contentLength); else if (k.Equals("X-Bot-Password", StringComparison.OrdinalIgnoreCase)) LastBotPwdHeader = v; else if (k.Equals("Authorization", StringComparison.OrdinalIgnoreCase)) LastAuthHeader = v; } int bodyStart = headerEnd + 4; int have = raw.Length - bodyStart; while (have < contentLength) { int n = await stream.ReadAsync(buf, 0, buf.Length); if (n <= 0) break; ms.Write(buf, 0, n); have += n; } raw = ms.ToArray(); LastBody = Encoding.UTF8.GetString(raw, Math.Min(bodyStart, raw.Length), Math.Max(0, Math.Min(contentLength, raw.Length - bodyStart))); string routePath = path; if (routePath.StartsWith("/api/")) routePath = routePath[3..]; // web-edge proxy shape string body = Routes.TryGetValue(routePath, out var fx) ? fx : """{"ok":false,"error":"not found"}"""; if (routePath == "/query" && LastQuery.Contains("action=cancel")) body = """{"ok":true,"killed":54,"error":null}"""; if (routePath == "/connections") { if (LastQuery.Contains("action=save")) body = """{"ok":true,"server":{"id":"srv-42","name":"prod","host":"db.internal","port":1433},"error":null}"""; else if (LastQuery.Contains("action=delete")) body = """{"ok":true,"deleted":"srv-1","error":null}"""; else if (LastQuery.Contains("action=test")) body = """{"ok":true,"connected":true,"server_version":"16.00.4145","error":null}"""; } if (routePath == "/editgrid" && LastQuery.Contains("action=apply")) body = """{"ok":true,"applied":2,"sql":["UPDATE [dbo].[t] SET [qty]=5 WHERE [id]=10"],"error":null}"""; if (routePath == "/activity" && LastQuery.Contains("action=kill")) body = """{"ok":true,"killed":61,"error":null}"""; if (routePath == "/storage" && LastMethod == "POST") body = """{"ok":true,"action":"backup","complete":true,"error":null}"""; if (routePath == "/agent") body = """{"ok":true,"job_id":"0A7F1234-5678-90AB-CDEF-0123456789AB","started":true,"error":null}"""; byte[] bytes = Encoding.UTF8.GetBytes(body); var resp = Encoding.ASCII.GetBytes( "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" + $"Content-Length: {bytes.Length}\r\nConnection: close\r\n\r\n"); await stream.WriteAsync(resp, 0, resp.Length); await stream.WriteAsync(bytes, 0, bytes.Length); await stream.FlushAsync(); } } catch { } } public void Dispose() { try { _listener.Stop(); } catch { } } } /* ═══════════════ test suite ═══════════════ */ static int RunTests() { Console.WriteLine("== scorpiox-ssms-client.console --test =="); int rc = SsmsClientInterop.Init(); Check(rc == 0, "init"); using var server = new MockServer(); Console.WriteLine($" mock SSMS API at {server.Url}"); SsmsClientInterop.SetHost(server.Url); // trailing slash must be trimmed SsmsClientInterop.SetPassword("test-node-pwd"); SsmsClientInterop.SetJwt("jwt.token.value"); SsmsClientInterop.SetIo(IntPtr.Zero); // built-in transport /* ping */ Check(SsmsClientInterop.Ping() == 0, "ping"); Check(server.LastPath == "/ping", "ping hits /ping (host slash trimmed)"); Check(SsmsClientInterop.Result.Contains("scorpiox-ssms-api"), "ping result JSON"); Check(server.LastBotPwdHeader == "test-node-pwd", "X-Bot-Password header arrives"); Check(server.LastAuthHeader == "Bearer jwt.token.value", "Authorization Bearer header arrives"); Check(server.LastQuery.Contains("pwd=test-node-pwd"), "pwd query-param fallback arrives"); /* connections */ Check(SsmsClientInterop.ListConnections() == 0, "list_connections"); Check(SsmsClientInterop.Result.Contains("srv-1"), "list_connections body"); Check(SsmsClientInterop.SaveConnection("""{"name":"prod","host":"db.internal","port":1433,"user":"sa","password":"x"}""") == 0, "save_connection"); Check(server.LastQuery.Contains("action=save") && server.LastBody.Contains("db.internal"), "save_connection url+body"); Check(SsmsClientInterop.SaveConnection("") == -1, "save_connection empty rejected"); Check(SsmsClientInterop.DeleteConnection("srv-1") == 0, "delete_connection"); Check(server.LastBody.Contains("\"id\":\"srv-1\""), "delete_connection body"); Check(SsmsClientInterop.TestConnection("""{"host":"db.internal","user":"sa"}""") == 0, "test_connection"); Check(server.LastQuery.Contains("action=test"), "test_connection action url"); /* tree */ Check(SsmsClientInterop.Tree("srv-1", "tables", "master", "dbo", "") == 0, "tree"); Check(server.LastQuery.Contains("node=tables") && server.LastQuery.Contains("db=master"), "tree query params"); Check(SsmsClientInterop.Tree("srv 1", "columns", "my db", "", "my tbl") == 0, "tree with spaces"); Check(server.LastQuery.Contains("srv%201") && server.LastQuery.Contains("my%20tbl"), "tree percent-encoding"); /* query + grid view */ Check(SsmsClientInterop.Query("srv-1", "master", "SELECT id, name, note FROM t", 1000, 30, "tok-7") == 0, "query"); Check(server.LastMethod == "POST", "query is POST"); Check(server.LastBody.Contains("\"max_rows\":1000") && server.LastBody.Contains("\"query_token\":\"tok-7\""), "query body fields"); Check(SsmsClientInterop.RowCount() == 3, "row_count == 3"); Check(SsmsClientInterop.ColCount() == 3, "col_count == 3"); Check(SsmsClientInterop.Cell(0, 0) == "1", "cell(0,0) == 1"); Check(SsmsClientInterop.Cell(0, 1) == "alpha", "cell(0,1) == alpha"); Check(SsmsClientInterop.Cell(1, 2) == "", "NULL cell renders empty"); Check(SsmsClientInterop.Cell(99, 0) == "", "cell row out of range empty"); Check(SsmsClientInterop.Cell(0, 99) == "", "cell col out of range empty"); /* non-ASCII survives LPUTF8Str marshaling (cp1252 trap) */ Check(SsmsClientInterop.Query("srv-1", "mastér", "PRINT 'héllo — 日本語 ok'", 0, 0, "") == 0, "query non-ASCII"); Check(server.LastBody.Contains("日本語"), "non-ASCII SQL arrives intact"); Check(server.LastBody.Contains("mastér"), "non-ASCII db arrives intact in JSON body"); /* sql escaping */ Check(SsmsClientInterop.Query("s", "db", "PRINT 'a\"b\\c'", 0, 0, "") == 0, "query quote/backslash"); Check(SsmsClientInterop.Query("s", "db", null!, 0, 0, "") == -1, "query NULL sql rejected"); /* cancel */ Check(SsmsClientInterop.Cancel("srv-1", "tok-7") == 0, "cancel by token"); Check(server.LastBody.Contains("tok-7"), "cancel body token"); Check(SsmsClientInterop.Cancel("srv-1", "") == -1, "cancel empty token rejected"); Check(SsmsClientInterop.CancelSpid("srv-1", 54) == 0, "cancel by spid"); Check(server.LastBody.Contains("\"spid\":54"), "cancel spid body"); Check(SsmsClientInterop.CancelSpid("srv-1", -1) == -1, "cancel negative spid rejected"); /* editgrid */ Check(SsmsClientInterop.EditgridLoad("srv-1", "master", "dbo", "t", 200) == 0, "editgrid_load"); Check(server.LastQuery.Contains("table=t") && server.LastQuery.Contains("top=200"), "editgrid_load query params"); Check(SsmsClientInterop.RowCount() == 2, "editgrid row_count == 2"); Check(SsmsClientInterop.Cell(0, 0) == "10", "editgrid cell(0,0)==10"); Check(SsmsClientInterop.Cell(1, 1) == "", "editgrid NULL cell empty"); Check(SsmsClientInterop.EditgridLoad("s", "db", "", null!, 10) == -1, "editgrid_load NULL table rejected"); Check(SsmsClientInterop.EditgridApply("""{"server":"srv-1","db":"master","table":"t","ops":[{"op":"update","pk":{"id":10},"values":{"qty":5}}]}""") == 0, "editgrid_apply"); Check(server.LastQuery.Contains("action=apply") && server.LastBody.Contains("\"op\":\"update\""), "editgrid_apply url+body"); Check(SsmsClientInterop.EditgridApply("") == -1, "editgrid_apply empty rejected"); /* script */ Check(SsmsClientInterop.Script("srv-1", "ddl", "table", "master", "dbo", "widgets") == 0, "script ddl"); Check(SsmsClientInterop.Result.Contains("CREATE TABLE"), "script SQL present"); Check(SsmsClientInterop.Script("srv-1", "", "table", "", "", "x") == -1, "script empty action rejected"); /* activity */ Check(SsmsClientInterop.Activity("srv-1", "sessions") == 0, "activity sessions"); Check(SsmsClientInterop.RowCount() == 2, "activity row_count == 2"); Check(SsmsClientInterop.Activity("srv-1", null!) == 0, "activity NULL action defaults sessions"); Check(server.LastQuery.Contains("action=sessions"), "activity default action query"); Check(SsmsClientInterop.ActivityKill("srv-1", 61) == 0, "activity_kill"); Check(server.LastBody.Contains("\"spid\":61"), "activity_kill body"); /* storage */ Check(SsmsClientInterop.Storage("srv-1", "files", "master") == 0, "storage files"); Check(SsmsClientInterop.Cell(0, 1) == "5.5", "storage numeric cell 5.5"); Check(SsmsClientInterop.StoragePost("backup", """{"server":"srv-1","db":"master","path":"/tmp/x.bak"}""") == 0, "storage_post backup"); Check(server.LastBody.Contains("/tmp/x.bak"), "storage_post body"); Check(SsmsClientInterop.StoragePost(null!, "{}") == -1, "storage_post NULL action rejected"); /* admin unified + fallbacks (mock answers /admin AND /agent etc.) */ Check(SsmsClientInterop.Admin("srv-1", "logins", "", "") == 0, "admin logins"); Check(SsmsClientInterop.Admin("srv-1", "errorlog", "", "") == 0, "admin errorlog"); Check(SsmsClientInterop.Admin("srv-1", "jobs", "", "") == 0, "admin jobs"); Check(SsmsClientInterop.Admin("srv-1", "", "", "") == -1, "admin empty action rejected"); /* job control */ Check(SsmsClientInterop.JobControl("srv-1", "0A7F1234-5678-90AB-CDEF-0123456789AB", "start") == 0, "job_control start"); Check(server.LastQuery.Contains("action=start"), "job_control action query"); Check(SsmsClientInterop.JobControl("srv-1", "x", "explode") == -1, "job_control bad verb rejected"); Check(SsmsClientInterop.JobControl("srv-1", null!, "start") == -1, "job_control NULL job rejected"); /* secrets clearing removes headers */ SsmsClientInterop.SetPassword(""); SsmsClientInterop.SetJwt(""); Check(SsmsClientInterop.Ping() == 0, "ping after clearing secrets"); Check(server.LastBotPwdHeader == "", "X-Bot-Password header gone"); Check(server.LastAuthHeader == "", "Authorization header gone"); /* result/last_error pointers are never null after anything */ Check(!string.IsNullOrEmpty(SsmsClientInterop.Result), "result non-empty"); Check(SsmsClientInterop.LastError == "", "last_error empty after success"); /* web-edge proxy shape: /api prefix works too */ SsmsClientInterop.SetHost(server.Url + "api"); Check(SsmsClientInterop.Ping() == 0 && server.LastPath == "/api/ping", "host with /api edge prefix"); SsmsClientInterop.SetHost(""); Check(SsmsClientInterop.Ping() == -1, "set_host empty resets to default loopback (no listener there -> fails)"); SsmsClientInterop.SetHost(server.Url.TrimEnd('/')); Check(SsmsClientInterop.Ping() == 0, "host restored, ping works again"); SsmsClientInterop.Cleanup(); Console.WriteLine(); Console.WriteLine($"{s_pass} PASS, {s_fail} FAIL"); return s_fail == 0 ? 0 : 1; } /* ═══════════════ CLI mode ═══════════════ */ static int RunCli(string[] args) { if (args.Length < 1 || args[0] is "--help" or "-h" or "help") { Console.Error.WriteLine( "usage: scorpiox-ssms-client-console [--host URL] COMMAND ...\n" + " env: SSMS_HOST, SSMS_NODE_PWD, SSMS_NODE_JWT (secrets via env only)\n" + "commands: ping | connections | save '' | delete | test ''\n" + " tree [db] [schema] [obj] | query '' [maxrows] [tmo] [token]\n" + " cancel | cancel-spid \n" + " editgrid-load [top] | editgrid-apply ''\n" + " script \n" + " activity [action] | kill | storage [db]\n" + " admin [db] [extra] | job | --test"); return 0; } string host = ""; var rest = new List(); for (int i = 0; i < args.Length; i++) { if (args[i] == "--host" && i + 1 < args.Length) { host = args[++i]; continue; } rest.Add(args[i]); } if (SsmsClientInterop.Init() != 0) { Console.Error.WriteLine($"init failed: {SsmsClientInterop.LastError}"); return 1; } var envHost = Environment.GetEnvironmentVariable("SSMS_HOST"); SsmsClientInterop.SetHost(!string.IsNullOrEmpty(host) ? host : envHost); var pwd = Environment.GetEnvironmentVariable("SSMS_NODE_PWD"); var jwt = Environment.GetEnvironmentVariable("SSMS_NODE_JWT"); if (!string.IsNullOrEmpty(pwd)) SsmsClientInterop.SetPassword(pwd); if (!string.IsNullOrEmpty(jwt)) SsmsClientInterop.SetJwt(jwt); var a = rest.ToArray(); string S(string v) => v ?? ""; int rc = a[0] switch { "ping" => SsmsClientInterop.Ping(), "connections" => SsmsClientInterop.ListConnections(), "save" when a.Length >= 2 => SsmsClientInterop.SaveConnection(a[1]), "delete" when a.Length >= 2 => SsmsClientInterop.DeleteConnection(a[1]), "test" when a.Length >= 2 => SsmsClientInterop.TestConnection(a[1]), "tree" when a.Length >= 3 => SsmsClientInterop.Tree(a[1], a[2], S(a.Length > 3 ? a[3] : null), S(a.Length > 4 ? a[4] : null), S(a.Length > 5 ? a[5] : null)), "query" when a.Length >= 4 => SsmsClientInterop.Query(a[1], a[2], a[3], a.Length > 4 ? int.Parse(a[4]) : 0, a.Length > 5 ? int.Parse(a[5]) : 0, S(a.Length > 6 ? a[6] : null)), "cancel" when a.Length >= 3 => SsmsClientInterop.Cancel(a[1], a[2]), "cancel-spid" when a.Length >= 3 => SsmsClientInterop.CancelSpid(a[1], int.Parse(a[2])), "editgrid-load" when a.Length >= 5 => SsmsClientInterop.EditgridLoad(a[1], a[2], a[3], a[4], a.Length > 5 ? int.Parse(a[5]) : 200), "editgrid-apply" when a.Length >= 2 => SsmsClientInterop.EditgridApply(a[1]), "script" when a.Length >= 4 => SsmsClientInterop.Script(a[1], a[2], a[3], S(a.Length > 4 ? a[4] : null), S(a.Length > 5 ? a[5] : null), S(a.Length > 6 ? a[6] : null)), "activity" when a.Length >= 2 => SsmsClientInterop.Activity(a[1], a.Length > 2 ? a[2] : null!), "kill" when a.Length >= 3 => SsmsClientInterop.ActivityKill(a[1], int.Parse(a[2])), "storage" when a.Length >= 3 => SsmsClientInterop.Storage(a[1], a[2], S(a.Length > 3 ? a[3] : null)), "admin" when a.Length >= 3 => SsmsClientInterop.Admin(a[1], a[2], S(a.Length > 3 ? a[3] : null), S(a.Length > 4 ? a[4] : null)), "job" when a.Length >= 4 => SsmsClientInterop.JobControl(a[1], a[2], a[3]), _ => Fail("unknown/incomplete command: " + a[0]), }; if (rc != 0) { Console.Error.WriteLine($"ERROR: {SsmsClientInterop.LastError}"); SsmsClientInterop.Cleanup(); return 1; } Console.WriteLine(SsmsClientInterop.Result); int rows = SsmsClientInterop.RowCount(); if (rows >= 0) { int cols = SsmsClientInterop.ColCount(); Console.WriteLine($"# grid: {rows} rows x {cols} cols"); for (int r = 0; r < Math.Min(rows, 20); r++) { var line = new List(); for (int c = 0; c < Math.Min(cols, 32); c++) line.Add(SsmsClientInterop.Cell(r, c)); Console.WriteLine(string.Join("\t", line)); } } SsmsClientInterop.Cleanup(); return 0; } static int Fail(string msg) { Console.Error.WriteLine(msg); return 2; } }