InventoryEndpointTests.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255
  1. using System.Net;
  2. using System.Net.Http.Json;
  3. using System.Text.Json;
  4. using RackPeek.Domain.Api;
  5. using RackPeek.Domain.Discovery;
  6. using RackPeek.Domain.Persistence.Yaml;
  7. using RackPeek.Domain.Resources.Connections;
  8. using RackPeek.Domain.Resources.SystemResources;
  9. using Xunit.Abstractions;
  10. namespace Tests.Api;
  11. [Collection("Process-wide static state")]
  12. public class InventoryEndpointTests(ITestOutputHelper output) : ApiTestBase(output) {
  13. private static (string Id, string Placeholder, string ServicePlaceholder) CreatePlaceholderNames() {
  14. var id = DiscoveryId.Create(DiscoveryId.NetworkScheme, "192.0.2.55");
  15. var placeholder = $"host-{DiscoveryId.ShortSuffix(id)}";
  16. return (id, placeholder, $"{placeholder}-ssh");
  17. }
  18. private static string PlaceholderInventoryYaml(
  19. string id,
  20. string placeholder,
  21. string servicePlaceholder) => $$"""
  22. version: 4
  23. resources:
  24. - kind: System
  25. name: {{placeholder}}
  26. discoveryId: {{id}}
  27. ip: 192.0.2.55
  28. - kind: Service
  29. name: {{servicePlaceholder}}
  30. discoveryId: rpk1:docker:1359175a57049554
  31. runsOn:
  32. - {{placeholder}}
  33. - kind: Switch
  34. name: core-switch
  35. ports:
  36. - type: rj45
  37. speed: 1
  38. count: 2
  39. connections:
  40. - a:
  41. resource: {{placeholder}}
  42. portGroup: 0
  43. portIndex: 0
  44. b:
  45. resource: core-switch
  46. portGroup: 0
  47. portIndex: 0
  48. """;
  49. [Fact]
  50. public async Task Invalid_Import_Does_Not_Change_Stored_Discovery_Names_Or_References() {
  51. HttpClient client = CreateClient(true);
  52. (var id, var placeholder, var servicePlaceholder) = CreatePlaceholderNames();
  53. var initial = PlaceholderInventoryYaml(id, placeholder, servicePlaceholder);
  54. HttpResponseMessage seed = await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  55. Assert.Equal(HttpStatusCode.OK, seed.StatusCode);
  56. var configPath = Path.Combine(TempDir, "config.yaml");
  57. var persistedBefore = await File.ReadAllTextAsync(configPath);
  58. var duplicateImport = $$"""
  59. resources:
  60. - kind: System
  61. name: forgejo
  62. discoveryId: {{id}}
  63. - kind: Server
  64. name: forgejo
  65. """;
  66. HttpResponseMessage response = await client.PostAsJsonAsync(
  67. "/api/inventory", new { yaml = duplicateImport });
  68. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
  69. using JsonDocument doc = await JsonDocument.ParseAsync(
  70. await response.Content.ReadAsStreamAsync());
  71. Assert.Contains("Duplicate resource name", doc.RootElement.GetProperty("error").GetString());
  72. using JsonDocument inventory = await JsonDocument.ParseAsync(
  73. await (await client.GetAsync("/api/inventory")).Content.ReadAsStreamAsync());
  74. JsonElement resources = inventory.RootElement.GetProperty("resources");
  75. Assert.Contains(resources.EnumerateArray(), resource =>
  76. resource.GetProperty("name").GetString() == placeholder);
  77. Assert.Contains(resources.EnumerateArray(), resource =>
  78. resource.GetProperty("name").GetString() == servicePlaceholder
  79. && resource.GetProperty("runsOn")[0].GetString() == placeholder);
  80. Assert.Equal(placeholder,
  81. inventory.RootElement.GetProperty("connections")[0].GetProperty("a")
  82. .GetProperty("resource").GetString());
  83. Assert.Equal(persistedBefore, await File.ReadAllTextAsync(configPath));
  84. }
  85. [Fact]
  86. public async Task Dry_Run_And_Apply_Report_The_Same_Discovery_Rename_And_References() {
  87. HttpClient client = CreateClient(true);
  88. (var id, var placeholder, var servicePlaceholder) = CreatePlaceholderNames();
  89. var initial = PlaceholderInventoryYaml(id, placeholder, servicePlaceholder);
  90. HttpResponseMessage seed = await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  91. Assert.Equal(HttpStatusCode.OK, seed.StatusCode);
  92. var update = $$"""
  93. resources:
  94. - kind: System
  95. name: forgejo
  96. discoveryId: {{id}}
  97. """;
  98. HttpResponseMessage previewResponse = await client.PostAsJsonAsync(
  99. "/api/inventory", new { yaml = update, dryRun = true });
  100. Assert.Equal(HttpStatusCode.OK, previewResponse.StatusCode);
  101. ImportYamlResponse? preview = await previewResponse.Content.ReadFromJsonAsync<ImportYamlResponse>();
  102. Assert.Equal("forgejo", preview!.Renamed[placeholder]);
  103. Assert.Equal("forgejo-ssh", preview.Renamed[servicePlaceholder]);
  104. Assert.Contains("forgejo-ssh", preview.Updated);
  105. Assert.Contains("runsOn:\n- forgejo", preview.NewYaml["forgejo-ssh"]);
  106. Assert.Contains(preview.ConnectionsRemoved, connection => connection.Contains(placeholder));
  107. Assert.Contains(preview.ConnectionsAdded, connection => connection.Contains("forgejo"));
  108. using (JsonDocument beforeApply = await JsonDocument.ParseAsync(
  109. await (await client.GetAsync("/api/inventory")).Content.ReadAsStreamAsync())) {
  110. Assert.Contains(beforeApply.RootElement.GetProperty("resources").EnumerateArray(), resource =>
  111. resource.GetProperty("name").GetString() == placeholder);
  112. }
  113. HttpResponseMessage applyResponse = await client.PostAsJsonAsync(
  114. "/api/inventory", new { yaml = update });
  115. Assert.Equal(HttpStatusCode.OK, applyResponse.StatusCode);
  116. ImportYamlResponse? applied = await applyResponse.Content.ReadFromJsonAsync<ImportYamlResponse>();
  117. Assert.Equal(preview.Renamed, applied!.Renamed);
  118. Assert.Equal(preview.Updated, applied.Updated);
  119. Assert.Equal(preview.OldYaml, applied.OldYaml);
  120. Assert.Equal(preview.NewYaml, applied.NewYaml);
  121. Assert.Equal(preview.ConnectionsAdded, applied.ConnectionsAdded);
  122. Assert.Equal(preview.ConnectionsRemoved, applied.ConnectionsRemoved);
  123. using JsonDocument afterApply = await JsonDocument.ParseAsync(
  124. await (await client.GetAsync("/api/inventory")).Content.ReadAsStreamAsync());
  125. JsonElement finalResources = afterApply.RootElement.GetProperty("resources");
  126. Assert.Contains(finalResources.EnumerateArray(), resource =>
  127. resource.GetProperty("name").GetString() == "forgejo");
  128. Assert.Contains(finalResources.EnumerateArray(), resource =>
  129. resource.GetProperty("name").GetString() == "forgejo-ssh"
  130. && resource.GetProperty("runsOn")[0].GetString() == "forgejo");
  131. Assert.Equal("forgejo", afterApply.RootElement.GetProperty("connections")[0]
  132. .GetProperty("a").GetProperty("resource").GetString());
  133. }
  134. [Fact]
  135. public void Replacing_Inventory_publishes_resources_and_connections_as_one_snapshot() {
  136. var collection = new ResourceCollection();
  137. collection.ReplaceInventory(
  138. [new SystemResource { Name = "old-host" }],
  139. [new Connection {
  140. A = new PortReference { Resource = "old-host" },
  141. B = new PortReference { Resource = "switch" }
  142. }]);
  143. (List<RackPeek.Domain.Resources.Resource> resources, List<Connection> connections) =
  144. collection.GetInventorySnapshot();
  145. collection.ReplaceInventory(
  146. [new SystemResource { Name = "new-host" }],
  147. [new Connection {
  148. A = new PortReference { Resource = "new-host" },
  149. B = new PortReference { Resource = "switch" }
  150. }]);
  151. (List<RackPeek.Domain.Resources.Resource> currentResources, List<Connection> currentConnections) =
  152. collection.GetInventorySnapshot();
  153. Assert.Equal("old-host", resources.Single().Name);
  154. Assert.Equal("old-host", connections.Single().A.Resource);
  155. Assert.Equal("new-host", currentResources.Single().Name);
  156. Assert.Equal("new-host", currentConnections.Single().A.Resource);
  157. }
  158. [Fact]
  159. public async Task DryRun_Add_New_Resource_Does_Not_Persist() {
  160. HttpClient client = CreateClient(true);
  161. var yaml = """
  162. resources:
  163. - name: example-server
  164. kind: Server
  165. """;
  166. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  167. new {
  168. yaml,
  169. dryRun = true
  170. });
  171. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  172. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  173. Assert.Single(result!.Added);
  174. Assert.Contains("example-server", result.Added);
  175. // Call again — still should be "added" because dry run did not persist
  176. HttpResponseMessage response2 = await client.PostAsJsonAsync("/api/inventory",
  177. new {
  178. yaml,
  179. dryRun = true
  180. });
  181. ImportYamlResponse? result2 = await response2.Content.ReadFromJsonAsync<ImportYamlResponse>();
  182. Assert.Single(result2!.Added);
  183. }
  184. [Fact]
  185. public async Task Merge_Add_New_Resource_Persists() {
  186. HttpClient client = CreateClient(true);
  187. var yaml = """
  188. version: 2
  189. resources:
  190. - kind: Server
  191. name: server-merge
  192. """;
  193. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  194. new {
  195. Yaml = yaml,
  196. mode = "Merge"
  197. });
  198. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  199. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  200. Assert.Single(result!.Added);
  201. // Now second call should detect no change
  202. HttpResponseMessage response2 = await client.PostAsJsonAsync("/api/inventory",
  203. new {
  204. yaml,
  205. dryRun = true
  206. });
  207. ImportYamlResponse? result2 = await response2.Content.ReadFromJsonAsync<ImportYamlResponse>();
  208. Assert.Empty(result2!.Added);
  209. Assert.Empty(result2.Updated);
  210. Assert.Empty(result2.Replaced);
  211. }
  212. [Fact]
  213. public async Task Merge_Updates_Existing_Resource() {
  214. HttpClient client = CreateClient(true);
  215. var initial = """
  216. version: 2
  217. resources:
  218. - kind: Server
  219. name: server-update
  220. ipmi: true
  221. """;
  222. await client.PostAsJsonAsync("/api/inventory",
  223. new { Yaml = initial });
  224. var update = """
  225. version: 3
  226. resources:
  227. - kind: Server
  228. name: server-update
  229. ipmi: false
  230. """;
  231. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  232. new {
  233. Yaml = update,
  234. mode = "Merge"
  235. });
  236. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  237. Assert.Single(result!.Updated);
  238. Assert.Contains("server-update", result.Updated);
  239. }
  240. [Fact]
  241. public async Task Replace_Replaces_Existing_Resource() {
  242. HttpClient client = CreateClient(true);
  243. var initial = """
  244. resources:
  245. - kind: Server
  246. name: server-replace
  247. ipmi: true
  248. """;
  249. await client.PostAsJsonAsync("/api/inventory",
  250. new { yaml = initial });
  251. var replace = """
  252. resources:
  253. - kind: Server
  254. name: server-replace
  255. """;
  256. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  257. new {
  258. yaml = replace,
  259. mode = "Replace"
  260. });
  261. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  262. Assert.Single(result!.Replaced);
  263. Assert.Contains("server-replace", result.Replaced);
  264. }
  265. [Fact]
  266. public async Task Invalid_Yaml_Returns_400() {
  267. HttpClient client = CreateClient(true);
  268. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  269. new {
  270. yaml = "not: valid: yaml:"
  271. });
  272. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
  273. }
  274. [Fact]
  275. public async Task Missing_Resources_Section_Returns_400() {
  276. HttpClient client = CreateClient(true);
  277. var yaml = """
  278. somethingElse:
  279. - name: test
  280. """;
  281. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  282. new { yaml });
  283. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
  284. }
  285. [Fact]
  286. public async Task Accepts_Json_Root_Input() {
  287. HttpClient client = CreateClient(true);
  288. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  289. new {
  290. json = new {
  291. version = 1,
  292. resources = new[]
  293. {
  294. new { kind = "Server", name = "json-server" }
  295. }
  296. }
  297. });
  298. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  299. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  300. Assert.Single(result!.Added);
  301. Assert.Contains("json-server", result.Added);
  302. }
  303. [Fact]
  304. public async Task Requires_Api_Key() {
  305. HttpClient client = CreateClient();
  306. var yaml = """
  307. resources:
  308. - name: no-auth
  309. kind: Server
  310. """;
  311. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  312. new { yaml });
  313. Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
  314. }
  315. [Fact]
  316. public async Task Import_Full_Config_Works() {
  317. HttpClient client = CreateClient(true);
  318. var yaml = await File.ReadAllTextAsync("TestConfigs/v2/11-demo-config.yaml");
  319. // Put your big sample YAML in TestData folder
  320. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  321. new { yaml });
  322. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  323. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  324. Assert.True(result!.Added.Count > 10);
  325. Assert.Empty(result.Updated);
  326. Assert.Empty(result.Replaced);
  327. }
  328. [Fact]
  329. public async Task Import_Full_Config_Twice_Is_Idempotent() {
  330. HttpClient client = CreateClient(true);
  331. var yaml = await File.ReadAllTextAsync("TestConfigs/v2/11-demo-config.yaml");
  332. await client.PostAsJsonAsync("/api/inventory", new { yaml });
  333. HttpResponseMessage response2 = await client.PostAsJsonAsync("/api/inventory",
  334. new { yaml, dryRun = true });
  335. ImportYamlResponse? result2 = await response2.Content.ReadFromJsonAsync<ImportYamlResponse>();
  336. Assert.Empty(result2!.Added);
  337. Assert.Empty(result2.Updated);
  338. Assert.Empty(result2.Replaced);
  339. }
  340. [Fact]
  341. public async Task Merge_Updates_Nested_Object() {
  342. HttpClient client = CreateClient(true);
  343. var initial = """
  344. version: 2
  345. resources:
  346. - kind: Server
  347. name: nested-test
  348. ram:
  349. size: 64
  350. mts: 2666
  351. """;
  352. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  353. var update = """
  354. version: 3
  355. resources:
  356. - kind: Server
  357. name: nested-test
  358. ram:
  359. size: 128
  360. """;
  361. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  362. new { yaml = update, mode = "Merge" });
  363. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  364. Assert.Single(result!.Updated);
  365. }
  366. [Fact]
  367. public async Task Merge_Does_Not_Clear_List_When_Empty() {
  368. HttpClient client = CreateClient(true);
  369. var initial = """
  370. resources:
  371. - kind: Server
  372. name: drive-test
  373. drives:
  374. - type: ssd
  375. size: 1024
  376. """;
  377. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  378. var update = """
  379. resources:
  380. - kind: Server
  381. name: drive-test
  382. drives: []
  383. """;
  384. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  385. new { yaml = update, mode = "Merge" });
  386. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  387. // Should NOT count as update because empty list ignored
  388. Assert.Empty(result!.Updated);
  389. }
  390. [Fact]
  391. public async Task Replace_Clears_List() {
  392. HttpClient client = CreateClient(true);
  393. var initial = """
  394. resources:
  395. - kind: Server
  396. name: replace-drive-test
  397. drives:
  398. - type: ssd
  399. size: 1024
  400. """;
  401. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  402. var replace = """
  403. resources:
  404. - kind: Server
  405. name: replace-drive-test
  406. drives: []
  407. """;
  408. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  409. new { yaml = replace, mode = "Replace" });
  410. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  411. Assert.Single(result!.Replaced);
  412. }
  413. [Fact]
  414. public async Task Type_Change_Forces_Replace() {
  415. HttpClient client = CreateClient(true);
  416. var initial = """
  417. version: 2
  418. resources:
  419. - kind: Server
  420. name: polymorph-test
  421. """;
  422. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  423. var update = """
  424. version: 3
  425. resources:
  426. - kind: Firewall
  427. name: polymorph-test
  428. """;
  429. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  430. new { yaml = update, mode = "Merge" });
  431. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  432. Assert.Single(result!.Replaced);
  433. }
  434. [Fact]
  435. public async Task Name_Matching_Is_Case_Insensitive() {
  436. HttpClient client = CreateClient(true);
  437. var initial = """
  438. resources:
  439. - kind: Server
  440. name: CaseTest
  441. """;
  442. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  443. var update = """
  444. resources:
  445. - kind: Server
  446. name: casetest
  447. ipmi: true
  448. """;
  449. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  450. new { yaml = update });
  451. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  452. Assert.Single(result!.Updated);
  453. }
  454. [Fact]
  455. public async Task Multiple_Resources_Are_Processed() {
  456. HttpClient client = CreateClient(true);
  457. var yaml = """
  458. resources:
  459. - kind: Server
  460. name: multi-1
  461. - kind: Firewall
  462. name: multi-2
  463. """;
  464. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  465. new { yaml });
  466. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  467. Assert.Equal(2, result!.Added.Count);
  468. }
  469. [Fact]
  470. public async Task DryRun_Replace_Does_Not_Persist() {
  471. HttpClient client = CreateClient(true);
  472. var initial = """
  473. resources:
  474. - kind: Server
  475. name: dry-replace
  476. ipmi: true
  477. """;
  478. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  479. var replace = """
  480. resources:
  481. - kind: Server
  482. name: dry-replace
  483. """;
  484. await client.PostAsJsonAsync("/api/inventory",
  485. new { yaml = replace, mode = "Replace", dryRun = true });
  486. HttpResponseMessage check = await client.PostAsJsonAsync("/api/inventory",
  487. new { yaml = replace, mode = "Replace", dryRun = true });
  488. ImportYamlResponse? result = await check.Content.ReadFromJsonAsync<ImportYamlResponse>();
  489. Assert.Single(result!.Replaced);
  490. }
  491. [Fact]
  492. public async Task Providing_Both_Yaml_And_Json_Returns_400() {
  493. HttpClient client = CreateClient(true);
  494. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  495. new {
  496. yaml = "resources: []",
  497. json = new { resources = Array.Empty<object>() }
  498. });
  499. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
  500. }
  501. [Fact]
  502. public async Task Empty_Request_Returns_400() {
  503. HttpClient client = CreateClient(true);
  504. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory", new { });
  505. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
  506. }
  507. [Fact]
  508. public async Task Version_1_Config_Is_Accepted() {
  509. HttpClient client = CreateClient(true);
  510. var yaml = """
  511. version: 1
  512. resources:
  513. - kind: Server
  514. name: v1-server
  515. """;
  516. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory", new { yaml });
  517. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  518. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  519. Assert.Single(result!.Added);
  520. }
  521. [Fact]
  522. public async Task Replace_Removes_Existing_Fields() {
  523. HttpClient client = CreateClient(true);
  524. var initial = """
  525. resources:
  526. - kind: Server
  527. name: destructive-test
  528. ipmi: true
  529. """;
  530. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  531. var replace = """
  532. resources:
  533. - kind: Server
  534. name: destructive-test
  535. """;
  536. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  537. new { yaml = replace, mode = "Replace" });
  538. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  539. Assert.Single(result!.Replaced);
  540. Assert.Contains("destructive-test", result.OldYaml.Keys);
  541. Assert.Contains("destructive-test", result.NewYaml.Keys);
  542. }
  543. [Fact]
  544. public async Task Merge_Does_Not_Affect_Unspecified_Resources() {
  545. HttpClient client = CreateClient(true);
  546. var full = await File.ReadAllTextAsync("TestConfigs/v2/11-demo-config.yaml");
  547. await client.PostAsJsonAsync("/api/inventory", new { yaml = full });
  548. var update = """
  549. resources:
  550. - kind: Server
  551. name: proxmox-node01
  552. ipmi: false
  553. """;
  554. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  555. new { yaml = update, mode = "Merge" });
  556. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  557. Assert.Single(result!.Updated);
  558. Assert.DoesNotContain("proxmox-node02", result.Updated);
  559. }
  560. [Fact]
  561. public async Task Json_Input_Resolves_Polymorphic_Resource() {
  562. HttpClient client = CreateClient(true);
  563. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  564. new {
  565. json = new {
  566. version = 2,
  567. resources = new[]
  568. {
  569. new { kind = "Firewall", name = "json-fw", model = "Test" }
  570. }
  571. }
  572. });
  573. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  574. Assert.Single(result!.Added);
  575. Assert.Contains("json-fw", result.Added);
  576. }
  577. [Fact]
  578. public async Task Large_Config_Is_Fully_Idempotent() {
  579. HttpClient client = CreateClient(true);
  580. var yaml = await File.ReadAllTextAsync("TestConfigs/v2/11-demo-config.yaml");
  581. await client.PostAsJsonAsync("/api/inventory", new { yaml });
  582. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  583. new { yaml });
  584. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  585. Assert.Empty(result!.Added);
  586. Assert.Empty(result.Updated);
  587. Assert.Empty(result.Replaced);
  588. }
  589. [Fact]
  590. public async Task Unknown_Kind_Returns_400() {
  591. HttpClient client = CreateClient(true);
  592. var yaml = """
  593. resources:
  594. - kind: UnknownThing
  595. name: mystery
  596. """;
  597. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory", new { yaml });
  598. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
  599. }
  600. [Fact]
  601. public async Task DryRun_Does_Not_Persist_Snapshots() {
  602. HttpClient client = CreateClient(true);
  603. var yaml = """
  604. resources:
  605. - kind: Server
  606. name: dry-snapshot
  607. """;
  608. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  609. new { yaml, dryRun = true });
  610. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  611. Assert.Empty(result!.OldYaml);
  612. }
  613. [Fact]
  614. public async Task Reordering_List_Does_Not_Count_As_Update() {
  615. HttpClient client = CreateClient(true);
  616. var initial = """
  617. resources:
  618. - kind: Server
  619. name: order-test
  620. drives:
  621. - type: ssd
  622. size: 1024
  623. - type: hdd
  624. size: 4096
  625. """;
  626. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  627. var reordered = """
  628. resources:
  629. - kind: Server
  630. name: order-test
  631. drives:
  632. - type: hdd
  633. size: 4096
  634. - type: ssd
  635. size: 1024
  636. """;
  637. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  638. new { yaml = reordered });
  639. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  640. Assert.Single(result!.Updated);
  641. Assert.Contains("order-test", result.Updated);
  642. }
  643. [Fact]
  644. public async Task Duplicate_Names_In_Same_Request_Returns_400() {
  645. HttpClient client = CreateClient(true);
  646. var yaml = """
  647. resources:
  648. - kind: Server
  649. name: dup
  650. - kind: Server
  651. name: dup
  652. """;
  653. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory", new { yaml });
  654. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
  655. }
  656. [Fact]
  657. public async Task Health_Endpoint_Is_Anonymous_And_Returns_rackpeek() {
  658. HttpClient client = CreateClient();
  659. HttpResponseMessage response = await client.GetAsync("/health");
  660. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  661. Assert.Equal("text/plain", response.Content.Headers.ContentType?.MediaType);
  662. Assert.Equal("rackpeek", await response.Content.ReadAsStringAsync());
  663. }
  664. [Fact]
  665. public async Task Wrong_Api_Key_Returns_401() {
  666. HttpClient client = Factory.CreateClient();
  667. client.DefaultRequestHeaders.Add("X-Api-Key", "definitely-wrong");
  668. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  669. new { yaml = "resources:\n - kind: Server\n name: x" });
  670. Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
  671. }
  672. [Fact]
  673. public async Task Bad_Request_Body_Contains_Error_Field() {
  674. HttpClient client = CreateClient(true);
  675. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory", new { });
  676. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
  677. Dictionary<string, string>? body =
  678. await response.Content.ReadFromJsonAsync<Dictionary<string, string>>();
  679. Assert.NotNull(body);
  680. Assert.True(body!.ContainsKey("error"));
  681. Assert.False(string.IsNullOrWhiteSpace(body["error"]));
  682. }
  683. [Fact]
  684. public async Task Added_Resource_Has_No_OldYaml_Entry() {
  685. HttpClient client = CreateClient(true);
  686. var yaml = """
  687. resources:
  688. - kind: Server
  689. name: fresh-server
  690. """;
  691. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory", new { yaml });
  692. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  693. Assert.Contains("fresh-server", result!.Added);
  694. Assert.DoesNotContain("fresh-server", result.OldYaml.Keys);
  695. Assert.Contains("fresh-server", result.NewYaml.Keys);
  696. }
  697. [Fact]
  698. public async Task Merge_Replaces_Tags_Wholesale() {
  699. HttpClient client = CreateClient(true);
  700. var initial = """
  701. resources:
  702. - kind: Server
  703. name: tag-merge
  704. tags:
  705. - alpha
  706. - beta
  707. """;
  708. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  709. var update = """
  710. resources:
  711. - kind: Server
  712. name: tag-merge
  713. tags:
  714. - gamma
  715. """;
  716. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  717. new { yaml = update, mode = "Merge" });
  718. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  719. Assert.Contains("tag-merge", result!.Updated);
  720. var newYaml = result.NewYaml["tag-merge"];
  721. Assert.Contains("gamma", newYaml);
  722. Assert.DoesNotContain("alpha", newYaml);
  723. Assert.DoesNotContain("beta", newYaml);
  724. }
  725. [Theory]
  726. [InlineData("Server")]
  727. [InlineData("Switch")]
  728. [InlineData("Router")]
  729. [InlineData("Firewall")]
  730. [InlineData("AccessPoint")]
  731. [InlineData("Ups")]
  732. [InlineData("Desktop")]
  733. [InlineData("Laptop")]
  734. [InlineData("Service")]
  735. [InlineData("System")]
  736. public async Task Documented_Kind_Discriminator_Values_Are_Accepted(string kind) {
  737. // The inventory-api doc lists the exact set of valid kind discriminator
  738. // values. Every one must be accepted as-is so the doc and runtime stay
  739. // in lockstep.
  740. HttpClient client = CreateClient(true);
  741. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  742. new {
  743. json = new {
  744. version = 3,
  745. resources = new[]
  746. {
  747. new { kind, name = $"kind-probe-{kind.ToLowerInvariant()}" }
  748. }
  749. }
  750. });
  751. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  752. }
  753. [Fact]
  754. public async Task Lowercase_Kind_Is_Rejected() {
  755. // The discriminator is case-sensitive — the doc must use exact casing
  756. // or users hit 400. This test pins that contract so a future refactor
  757. // making the kind case-insensitive would surface here and prompt a
  758. // doc update.
  759. HttpClient client = CreateClient(true);
  760. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  761. new {
  762. json = new {
  763. version = 3,
  764. resources = new[]
  765. {
  766. new { kind = "server", name = "lowercase-probe" }
  767. }
  768. }
  769. });
  770. Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
  771. }
  772. [Fact]
  773. public async Task Merge_Preserves_Labels_Not_In_Incoming() {
  774. HttpClient client = CreateClient(true);
  775. var initial = """
  776. resources:
  777. - kind: Server
  778. name: label-merge
  779. labels:
  780. env: production
  781. team: backend
  782. """;
  783. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial });
  784. var update = """
  785. resources:
  786. - kind: Server
  787. name: label-merge
  788. labels:
  789. env: staging
  790. """;
  791. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  792. new { yaml = update, mode = "Merge" });
  793. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  794. Assert.Contains("label-merge", result!.Updated);
  795. var newYaml = result.NewYaml["label-merge"];
  796. Assert.Contains("env: staging", newYaml);
  797. Assert.Contains("team: backend", newYaml);
  798. Assert.DoesNotContain("env: production", newYaml);
  799. }
  800. [Fact]
  801. public async Task Import_Persists_And_Updates_Connections() {
  802. HttpClient client = CreateClient(true);
  803. var initial = """
  804. version: 3
  805. resources:
  806. - kind: Switch
  807. ports:
  808. - type: rj45
  809. speed: 1
  810. count: 8
  811. name: switch1
  812. - kind: Server
  813. ports:
  814. - type: rj45
  815. speed: 1
  816. count: 1
  817. name: server1
  818. connections:
  819. - a:
  820. resource: server1
  821. portGroup: 0
  822. portIndex: 0
  823. b:
  824. resource: switch1
  825. portGroup: 0
  826. portIndex: 0
  827. """;
  828. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  829. new { yaml = initial, mode = "Merge" });
  830. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  831. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  832. Assert.Single(result!.ConnectionsAdded);
  833. Assert.Empty(result.ConnectionsRemoved);
  834. // Re-importing the same config is idempotent
  835. HttpResponseMessage response2 = await client.PostAsJsonAsync("/api/inventory",
  836. new { yaml = initial, dryRun = true, mode = "Merge" });
  837. ImportYamlResponse? result2 = await response2.Content.ReadFromJsonAsync<ImportYamlResponse>();
  838. Assert.Empty(result2!.ConnectionsAdded);
  839. Assert.Empty(result2.ConnectionsRemoved);
  840. // Adjusting the switch port replaces the old connection (#308)
  841. var adjusted = initial.Replace(
  842. """
  843. resource: switch1
  844. portGroup: 0
  845. portIndex: 0
  846. """,
  847. """
  848. resource: switch1
  849. portGroup: 0
  850. portIndex: 3
  851. """);
  852. HttpResponseMessage response3 = await client.PostAsJsonAsync("/api/inventory",
  853. new { yaml = adjusted, mode = "Merge" });
  854. ImportYamlResponse? result3 = await response3.Content.ReadFromJsonAsync<ImportYamlResponse>();
  855. Assert.Single(result3!.ConnectionsAdded);
  856. Assert.Contains("switch1[0.3]", result3.ConnectionsAdded[0]);
  857. Assert.Single(result3.ConnectionsRemoved);
  858. Assert.Contains("switch1[0.0]", result3.ConnectionsRemoved[0]);
  859. // And the adjusted state is now stable
  860. HttpResponseMessage response4 = await client.PostAsJsonAsync("/api/inventory",
  861. new { yaml = adjusted, dryRun = true, mode = "Merge" });
  862. ImportYamlResponse? result4 = await response4.Content.ReadFromJsonAsync<ImportYamlResponse>();
  863. Assert.Empty(result4!.ConnectionsAdded);
  864. Assert.Empty(result4.ConnectionsRemoved);
  865. }
  866. [Fact]
  867. public async Task Import_Without_Connections_Section_Keeps_Existing_Connections() {
  868. HttpClient client = CreateClient(true);
  869. var initial = """
  870. version: 3
  871. resources:
  872. - kind: Switch
  873. ports:
  874. - type: rj45
  875. speed: 1
  876. count: 8
  877. name: sw-keep
  878. - kind: Server
  879. ports:
  880. - type: rj45
  881. speed: 1
  882. count: 1
  883. name: srv-keep
  884. connections:
  885. - a:
  886. resource: srv-keep
  887. portGroup: 0
  888. portIndex: 0
  889. b:
  890. resource: sw-keep
  891. portGroup: 0
  892. portIndex: 0
  893. """;
  894. await client.PostAsJsonAsync("/api/inventory", new { yaml = initial, mode = "Merge" });
  895. // An import that says nothing about connections must not drop them
  896. var resourcesOnly = """
  897. resources:
  898. - kind: Server
  899. name: srv-keep
  900. notes: updated
  901. """;
  902. await client.PostAsJsonAsync("/api/inventory", new { yaml = resourcesOnly, mode = "Merge" });
  903. // The original connection still exists: re-importing the initial
  904. // config reports no connection changes.
  905. HttpResponseMessage check = await client.PostAsJsonAsync("/api/inventory",
  906. new { yaml = initial, dryRun = true, mode = "Merge" });
  907. ImportYamlResponse? result = await check.Content.ReadFromJsonAsync<ImportYamlResponse>();
  908. Assert.Empty(result!.ConnectionsAdded);
  909. Assert.Empty(result.ConnectionsRemoved);
  910. }
  911. [Fact]
  912. public async Task Merge_Other_Hardware_Persists() {
  913. HttpClient client = CreateClient(true);
  914. var yaml = """
  915. resources:
  916. - kind: Other
  917. name: radio-merge
  918. model: Building Bridge XG
  919. description: Microwave radio bridge
  920. """;
  921. HttpResponseMessage response = await client.PostAsJsonAsync("/api/inventory",
  922. new {
  923. Yaml = yaml,
  924. mode = "Merge"
  925. });
  926. Assert.Equal(HttpStatusCode.OK, response.StatusCode);
  927. ImportYamlResponse? result = await response.Content.ReadFromJsonAsync<ImportYamlResponse>();
  928. Assert.Contains("radio-merge", result!.Added);
  929. var update = """
  930. resources:
  931. - kind: Other
  932. name: radio-merge
  933. description: Site-to-site connectivity
  934. """;
  935. HttpResponseMessage response2 = await client.PostAsJsonAsync("/api/inventory",
  936. new { yaml = update, mode = "Merge" });
  937. Assert.Equal(HttpStatusCode.OK, response2.StatusCode);
  938. ImportYamlResponse? result2 = await response2.Content.ReadFromJsonAsync<ImportYamlResponse>();
  939. Assert.Contains("radio-merge", result2!.Updated);
  940. var newYaml = result2.NewYaml["radio-merge"];
  941. Assert.Contains("model: Building Bridge XG", newYaml);
  942. Assert.Contains("description: Site-to-site connectivity", newYaml);
  943. }
  944. [Fact]
  945. public async Task Inventory_api_round_trips_all_service_endpoints() {
  946. HttpClient client = CreateClient(true);
  947. var yaml = """
  948. version: 5
  949. resources:
  950. - kind: Service
  951. name: multi-endpoint
  952. network:
  953. ip: 192.168.1.10
  954. port: 8080
  955. protocol: TCP
  956. endpoints:
  957. - ip: 192.168.1.10
  958. port: 8080
  959. protocol: TCP
  960. - ip: 192.168.1.11
  961. port: 8443
  962. protocol: UDP
  963. """;
  964. HttpResponseMessage upsert = await client.PostAsJsonAsync("/api/inventory", new { yaml });
  965. Assert.Equal(HttpStatusCode.OK, upsert.StatusCode);
  966. using JsonDocument response = await JsonDocument.ParseAsync(
  967. await (await client.GetAsync("/api/inventory")).Content.ReadAsStreamAsync());
  968. JsonElement endpoints = response.RootElement.GetProperty("resources")
  969. .EnumerateArray()
  970. .Single(resource => resource.GetProperty("name").GetString() == "multi-endpoint")
  971. .GetProperty("endpoints");
  972. Assert.Equal(2, endpoints.GetArrayLength());
  973. Assert.Equal(8443, endpoints[1].GetProperty("port").GetInt32());
  974. Assert.Equal("UDP", endpoints[1].GetProperty("protocol").GetString());
  975. }
  976. [Fact]
  977. public async Task Inventory_api_migrates_a_legacy_service_network_to_one_endpoint() {
  978. HttpClient client = CreateClient(true);
  979. var yaml = """
  980. version: 4
  981. resources:
  982. - kind: Service
  983. name: legacy-service
  984. network:
  985. ip: 192.168.1.20
  986. port: 8096
  987. protocol: TCP
  988. """;
  989. HttpResponseMessage upsert = await client.PostAsJsonAsync("/api/inventory", new { yaml });
  990. Assert.Equal(HttpStatusCode.OK, upsert.StatusCode);
  991. using JsonDocument response = await JsonDocument.ParseAsync(
  992. await (await client.GetAsync("/api/inventory")).Content.ReadAsStreamAsync());
  993. JsonElement service = response.RootElement.GetProperty("resources")
  994. .EnumerateArray()
  995. .Single(resource => resource.GetProperty("name").GetString() == "legacy-service");
  996. Assert.Equal(8096, service.GetProperty("network").GetProperty("port").GetInt32());
  997. JsonElement endpoint = Assert.Single(service.GetProperty("endpoints").EnumerateArray());
  998. Assert.Equal(8096, endpoint.GetProperty("port").GetInt32());
  999. }
  1000. }