1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
|
module SomhairlesDream.Server.Tests.ApiTests
open System
open System.IO
open System.Net
open System.Net.Http
open System.Text
open System.Text.Json
open System.Threading
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.AspNetCore.TestHost
open Xunit
open SomhairlesDream.Modeling
open SomhairlesDream.Server
open SomhairlesDream.Shared
let private ids : RunIds =
{ ProjectId = "heritage-001"
RunId = "run-api-001"
BaseId = "base-000"
TargetId = "target-003" }
let private withTempDirectory action =
let path = Path.Combine(Path.GetTempPath(), "somhairles-dream-api-" + Guid.NewGuid().ToString("N"))
Directory.CreateDirectory(path) |> ignore
try
action path
finally
if Directory.Exists(path) then
Directory.Delete(path, true)
type private TestBridge() =
interface IArtifactBridge with
member _.Export(request, _) =
File.WriteAllBytes(request.GlbPath, [| 0x67uy; 0x6Cuy; 0x54uy; byte request.Step.Index |])
Directory.CreateDirectory(Path.GetDirectoryName(request.LogPath)) |> ignore
File.WriteAllText(request.LogPath, $"bridge log for {request.Step.StepId}")
Ok
{ BlenderVersion = "5.0.1"
ExportedAt = DateTimeOffset.Parse("2026-09-20T12:00:05Z")
ObjectIds = request.Step.ObjectIds
VerifiedObjectIds = request.Step.ObjectIds
GlbBytes = 4L
RenderPath = None
RenderedAt = None }
type private BlockingBridge(gate: ManualResetEventSlim) =
interface IArtifactBridge with
member _.Export(request, _) =
gate.Wait()
(TestBridge() :> IArtifactBridge).Export(request, fun () -> ())
type private StepGatedBridge(gate: ManualResetEventSlim) =
interface IArtifactBridge with
member _.Export(request, _) =
if request.Step.Index > 0 then
gate.Wait()
(TestBridge() :> IArtifactBridge).Export(request, fun () -> ())
let private requestBody runId =
$"{{\"projectId\":\"{ids.ProjectId}\",\"runId\":\"{runId}\",\"baseId\":\"{ids.BaseId}\",\"targetId\":\"{ids.TargetId}\"}}"
let private withAppUsing (bridgeFactory: unit -> IArtifactBridge) action =
withTempDirectory (fun root ->
let clock () = DateTimeOffset.Parse("2026-09-20T12:00:00Z")
let artifactRoot = Path.Combine(root, "artifacts")
Directory.CreateDirectory(artifactRoot) |> ignore
let coordinator =
ArtifactRunCoordinator(
artifactRoot,
bridgeFactory,
clock,
TimeSpan.FromSeconds 15.
)
let builder = WebApplication.CreateBuilder([||])
builder.WebHost.UseTestServer() |> ignore
let app = builder.Build()
ArtifactRunApi.register
app
{ Coordinator = coordinator
Clock = clock
JsonOptions = JsonSerializerOptions(JsonSerializerDefaults.Web) }
app.StartAsync().GetAwaiter().GetResult()
try
action (app.GetTestClient()) coordinator
finally
app.StopAsync().GetAwaiter().GetResult()
app.DisposeAsync().AsTask().GetAwaiter().GetResult())
let private withApp action = withAppUsing (fun () -> TestBridge() :> IArtifactBridge) action
let private waitFor predicate =
let deadline = DateTime.UtcNow.AddSeconds(5.)
let mutable matched = predicate ()
while not matched && DateTime.UtcNow < deadline do
Thread.Sleep(10)
matched <- predicate ()
matched
[<Fact>]
let ``start endpoint accepts a run and conflicts on its second start`` () =
withApp (fun client _ ->
let first =
use content = new StringContent(requestBody ids.RunId, Encoding.UTF8, "application/json")
client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, first.StatusCode)
let firstSnapshot =
first.Content.ReadAsStringAsync().GetAwaiter().GetResult()
|> fun body -> JsonSerializer.Deserialize<RunSnapshot>(body, JsonSerializerOptions(JsonSerializerDefaults.Web))
Assert.Equal(ids.ProjectId, firstSnapshot.ProjectId)
Assert.Equal(ids.RunId, firstSnapshot.RunId)
use duplicateContent = new StringContent(requestBody ids.RunId, Encoding.UTF8, "application/json")
let duplicate = client.PostAsync("/api/runs/start", duplicateContent).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Conflict, duplicate.StatusCode))
[<Fact>]
let ``start endpoint rejects invalid resource ids before creating a run`` () =
withApp (fun client coordinator ->
let body = requestBody "../outside"
use content = new StringContent(body, Encoding.UTF8, "application/json")
let response = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode)
Assert.True(coordinator.TryFind(ids.ProjectId, "../outside").IsNone))
[<Fact>]
let ``manifest and artifact endpoints expose a completed run and reject traversal`` () =
withApp (fun client coordinator ->
let runId = "run-api-complete"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
let completed =
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store -> store.Snapshot().Status = "complete"))
Assert.True(completed)
let manifest =
client
.GetAsync($"/api/artifacts/manifest?projectId={ids.ProjectId}&runId={runId}")
.GetAwaiter()
.GetResult()
Assert.Equal(HttpStatusCode.OK, manifest.StatusCode)
let manifestBody = manifest.Content.ReadAsStringAsync().GetAwaiter().GetResult()
Assert.Contains("\"schemaVersion\":1", manifestBody)
let glbPath = Uri.EscapeDataString("steps/01-foundation.glb")
let artifact =
client
.GetAsync($"/api/artifacts/file?projectId={ids.ProjectId}&runId={runId}&path={glbPath}")
.GetAwaiter()
.GetResult()
Assert.Equal(HttpStatusCode.OK, artifact.StatusCode)
let traversalPath = Uri.EscapeDataString("../manifest.json")
let traversal =
client
.GetAsync($"/api/artifacts/file?projectId={ids.ProjectId}&runId={runId}&path={traversalPath}")
.GetAwaiter()
.GetResult()
Assert.Equal(HttpStatusCode.BadRequest, traversal.StatusCode))
[<Fact>]
let ``manifest endpoint reports active runs as conflicts`` () =
let gate = new ManualResetEventSlim(false)
try
withAppUsing
(fun () -> BlockingBridge(gate) :> IArtifactBridge)
(fun client coordinator ->
let runId = "run-api-active"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
let manifest =
client
.GetAsync($"/api/artifacts/manifest?projectId={ids.ProjectId}&runId={runId}")
.GetAwaiter()
.GetResult()
Assert.Equal(HttpStatusCode.Conflict, manifest.StatusCode)
gate.Set()
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store -> store.Snapshot().Status = "complete")))
)
finally
gate.Set()
gate.Dispose()
[<Fact>]
let ``step artifacts stream while a run is still active`` () =
let gate = new ManualResetEventSlim(false)
try
withAppUsing
(fun () -> StepGatedBridge(gate) :> IArtifactBridge)
(fun client coordinator ->
let runId = "run-api-steps"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store ->
let snapshot = store.Snapshot()
snapshot.Status = "running" && snapshot.CompletedSteps.Length = 1)))
let glbPath = Uri.EscapeDataString("steps/01-foundation.glb")
let stepsUrl = $"/api/artifacts/steps?projectId={ids.ProjectId}&runId={runId}&path={glbPath}"
let stepArtifact =
client.GetAsync(stepsUrl).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.OK, stepArtifact.StatusCode)
Assert.Equal("model/gltf-binary", stepArtifact.Content.Headers.ContentType.MediaType)
let traversalPath = Uri.EscapeDataString("../manifest.json")
let traversalUrl = $"/api/artifacts/steps?projectId={ids.ProjectId}&runId={runId}&path={traversalPath}"
let traversal =
client.GetAsync(traversalUrl).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.BadRequest, traversal.StatusCode)
let missingPath = Uri.EscapeDataString("steps/03-cabin.glb")
let missingUrl = $"/api/artifacts/steps?projectId={ids.ProjectId}&runId={runId}&path={missingPath}"
let missing =
client.GetAsync(missingUrl).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.NotFound, missing.StatusCode)
gate.Set()
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store -> store.Snapshot().Status = "complete")))
)
finally
gate.Set()
gate.Dispose()
let private glbBytes (index: byte) = [| 0x67uy; 0x6Cuy; 0x54uy; index |]
let private runDirectory (coordinator: ArtifactRunCoordinator) (runId: string) =
Path.Combine(coordinator.ArtifactRoot, ids.ProjectId, runId)
let private getArtifact (client: HttpClient) endpoint runId relativePath =
let encoded = Uri.EscapeDataString(relativePath)
client
.GetAsync($"/api/artifacts/{endpoint}?projectId={ids.ProjectId}&runId={runId}&path={encoded}")
.GetAwaiter()
.GetResult()
let private waitForTerminal (coordinator: ArtifactRunCoordinator) runId =
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store ->
let status = store.Snapshot().Status
status = "complete" || status = "failed"))
)
let private fdCount () =
if Directory.Exists("/proc/self/fd") then
Directory.GetFiles("/proc/self/fd").Length
else
-1
let private copyDirectory (source: string) (destination: string) =
Directory.CreateDirectory(destination) |> ignore
for directory in Directory.GetDirectories(source, "*", SearchOption.AllDirectories) do
Directory.CreateDirectory(Path.Combine(destination, directory.Substring(source.Length + 1)))
|> ignore
for file in Directory.GetFiles(source, "*", SearchOption.AllDirectories) do
let relative = file.Substring(source.Length + 1)
let target = Path.Combine(destination, relative)
Directory.CreateDirectory(Path.GetDirectoryName(target)) |> ignore
File.Copy(file, target)
let private getManifest (client: HttpClient) runId =
client
.GetAsync($"/api/artifacts/manifest?projectId={ids.ProjectId}&runId={runId}")
.GetAwaiter()
.GetResult()
let private assertArtifactServed (client: HttpClient) runId =
let glbResponse = getArtifact client "file" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.OK, glbResponse.StatusCode)
let stepResponse = getArtifact client "steps" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.OK, stepResponse.StatusCode)
let manifestResponse = getManifest client runId
Assert.Equal(HttpStatusCode.OK, manifestResponse.StatusCode)
let private assertArtifactRejected (client: HttpClient) runId =
let glbResponse = getArtifact client "file" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.BadRequest, glbResponse.StatusCode)
let stepResponse = getArtifact client "steps" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.BadRequest, stepResponse.StatusCode)
let manifestResponse = getManifest client runId
Assert.Equal(HttpStatusCode.BadRequest, manifestResponse.StatusCode)
let private outsideDirectory (coordinator: ArtifactRunCoordinator) name =
Path.Combine(Directory.GetParent(coordinator.ArtifactRoot).FullName, name)
let private replaceWithSymlink (source: string) (target: string) =
if File.Exists(source) then
File.Delete(source)
else
Directory.Delete(source, true)
Directory.CreateSymbolicLink(source, target) |> ignore
[<Fact>]
let ``file endpoint serves only published manifest members`` () =
withApp (fun client coordinator ->
let runId = "run-api-scope"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store -> store.Snapshot().Status = "complete"))
)
let glbResponse = getArtifact client "file" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.OK, glbResponse.StatusCode)
Assert.Equal("model/gltf-binary", glbResponse.Content.Headers.ContentType.MediaType)
let bytes = glbResponse.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult()
Assert.True((glbBytes 0uy = bytes), "file endpoint should serve the published glb bytes")
let stepResponse = getArtifact client "steps" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.OK, stepResponse.StatusCode)
let logResponse = getArtifact client "file" runId "logs/01-foundation.log"
Assert.Equal(HttpStatusCode.NotFound, logResponse.StatusCode)
let manifestResponse = getArtifact client "file" runId "manifest.json"
Assert.Equal(HttpStatusCode.NotFound, manifestResponse.StatusCode)
File.WriteAllText(Path.Combine(runDirectory coordinator runId, "extra-secret.txt"), "hidden")
let extraResponse = getArtifact client "file" runId "extra-secret.txt"
Assert.Equal(HttpStatusCode.NotFound, extraResponse.StatusCode))
[<Fact>]
let ``file endpoint rejects tampered published artifacts`` () =
withApp (fun client coordinator ->
let runId = "run-api-tampered"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store -> store.Snapshot().Status = "complete"))
)
let glbPath = Path.Combine(runDirectory coordinator runId, "steps", "01-foundation.glb")
File.WriteAllBytes(glbPath, glbBytes 0x09uy)
let response = getArtifact client "file" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode))
[<Fact>]
let ``file endpoint rejects file symlink escapes`` () =
withApp (fun client coordinator ->
let runId = "run-api-filelink"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store -> store.Snapshot().Status = "complete"))
)
let glbPath = Path.Combine(runDirectory coordinator runId, "steps", "01-foundation.glb")
let original = File.ReadAllBytes(glbPath)
let escapeTarget = Path.Combine(coordinator.ArtifactRoot, "escape-target.glb")
File.WriteAllBytes(escapeTarget, original)
File.Delete(glbPath)
File.CreateSymbolicLink(glbPath, escapeTarget) |> ignore
let response = getArtifact client "file" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode))
[<Fact>]
let ``file endpoint rejects intermediate directory symlink escapes`` () =
withApp (fun client coordinator ->
let runId = "run-api-dirlink"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store -> store.Snapshot().Status = "complete"))
)
let glbPath = Path.Combine(runDirectory coordinator runId, "steps", "01-foundation.glb")
let original = File.ReadAllBytes(glbPath)
let escapeDirectory = Path.Combine(coordinator.ArtifactRoot, "escape-steps")
Directory.CreateDirectory(escapeDirectory) |> ignore
File.WriteAllBytes(Path.Combine(escapeDirectory, "01-foundation.glb"), original)
let stepsPath = Path.Combine(runDirectory coordinator runId, "steps")
Directory.Delete(stepsPath, true)
Directory.CreateSymbolicLink(stepsPath, escapeDirectory) |> ignore
let response = getArtifact client "file" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode))
[<Fact>]
let ``step endpoint rejects uncheckpointed glb files while running`` () =
let gate = new ManualResetEventSlim(false)
try
withAppUsing
(fun () -> StepGatedBridge(gate) :> IArtifactBridge)
(fun client coordinator ->
let runId = "run-api-rogue"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store ->
let snapshot = store.Snapshot()
snapshot.Status = "running" && snapshot.CompletedSteps.Length = 1))
)
let glbPath = Path.Combine(runDirectory coordinator runId, "steps", "01-foundation.glb")
File.Copy(glbPath, Path.Combine(runDirectory coordinator runId, "steps", "09-rogue.glb"))
let response = getArtifact client "steps" runId "steps/09-rogue.glb"
Assert.Equal(HttpStatusCode.NotFound, response.StatusCode)
gate.Set()
waitForTerminal coordinator runId)
finally
gate.Set()
gate.Dispose()
[<Fact>]
let ``step endpoint rejects tampered live checkpoint artifacts`` () =
let gate = new ManualResetEventSlim(false)
try
withAppUsing
(fun () -> StepGatedBridge(gate) :> IArtifactBridge)
(fun client coordinator ->
let runId = "run-api-livetamper"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store ->
let snapshot = store.Snapshot()
snapshot.Status = "running" && snapshot.CompletedSteps.Length = 1))
)
let glbPath = Path.Combine(runDirectory coordinator runId, "steps", "01-foundation.glb")
File.WriteAllBytes(glbPath, glbBytes 0x09uy)
let response = getArtifact client "steps" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode)
gate.Set()
waitForTerminal coordinator runId)
finally
gate.Set()
gate.Dispose()
[<Fact>]
let ``step endpoint rejects symlink escapes while running`` () =
let gate = new ManualResetEventSlim(false)
try
withAppUsing
(fun () -> StepGatedBridge(gate) :> IArtifactBridge)
(fun client coordinator ->
let runId = "run-api-steplink"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store ->
let snapshot = store.Snapshot()
snapshot.Status = "running" && snapshot.CompletedSteps.Length = 1))
)
let glbPath = Path.Combine(runDirectory coordinator runId, "steps", "01-foundation.glb")
let original = File.ReadAllBytes(glbPath)
let escapeTarget = Path.Combine(coordinator.ArtifactRoot, "escape-step-target.glb")
File.WriteAllBytes(escapeTarget, original)
File.Delete(glbPath)
File.CreateSymbolicLink(glbPath, escapeTarget) |> ignore
let response = getArtifact client "steps" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode)
gate.Set()
waitForTerminal coordinator runId)
finally
gate.Set()
gate.Dispose()
[<Fact>]
let ``events endpoint streams only the selected run`` () =
withApp (fun client _ ->
let runId = "run-api-events"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
use response =
client
.GetAsync(
$"/api/runs/events?projectId={ids.ProjectId}&runId={runId}",
HttpCompletionOption.ResponseHeadersRead
)
.GetAwaiter()
.GetResult()
Assert.Equal(HttpStatusCode.OK, response.StatusCode)
use reader = new StreamReader(response.Content.ReadAsStream())
let line = reader.ReadLine()
Assert.StartsWith("data: ", line)
Assert.Contains(runId, line)
let unknown =
client
.GetAsync($"/api/runs/events?projectId={ids.ProjectId}&runId=run-api-missing")
.GetAwaiter()
.GetResult()
Assert.Equal(HttpStatusCode.NotFound, unknown.StatusCode))
[<Fact>]
let ``artifact streams dispose deterministically on repeated mismatches`` () =
let gate = new ManualResetEventSlim(false)
try
withAppUsing
(fun () -> StepGatedBridge(gate) :> IArtifactBridge)
(fun client coordinator ->
let runId = "run-api-dispose"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store ->
let snapshot = store.Snapshot()
snapshot.Status = "running" && snapshot.CompletedSteps.Length = 1))
)
let glbPath = Path.Combine(runDirectory coordinator runId, "steps", "01-foundation.glb")
File.WriteAllBytes(glbPath, glbBytes 0x09uy)
let baseline = fdCount ()
let assertNoLeak () =
if baseline >= 0 then
Assert.True(
fdCount () <= baseline + 2,
"failed artifact opens should not leak file handles"
)
for _ in 1..20 do
match coordinator.StepArtifact(ids.ProjectId, runId, "steps/01-foundation.glb") with
| Error(ArtifactMismatch _) -> ()
| other -> failwith $"expected ArtifactMismatch, got {other}"
assertNoLeak ()
for _ in 1..10 do
let response = getArtifact client "steps" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode)
File.WriteAllBytes(glbPath, [| 0x01uy; 0x02uy; 0x03uy; 0x04uy; 0x05uy |])
for _ in 1..20 do
match coordinator.StepArtifact(ids.ProjectId, runId, "steps/01-foundation.glb") with
| Error(ArtifactMismatch _) -> ()
| other -> failwith $"expected ArtifactMismatch, got {other}"
assertNoLeak ()
for _ in 1..10 do
let response = getArtifact client "steps" runId "steps/01-foundation.glb"
Assert.Equal(HttpStatusCode.Conflict, response.StatusCode)
gate.Set()
waitForTerminal coordinator runId)
finally
gate.Set()
gate.Dispose()
[<Fact>]
let ``artifact serving rejects symlinked project directories`` () =
withApp (fun client coordinator ->
let runId = "run-api-projlink"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store -> store.Snapshot().Status = "complete"))
)
assertArtifactServed client runId
let projectDirectory = Path.Combine(coordinator.ArtifactRoot, ids.ProjectId)
let escapeDirectory = outsideDirectory coordinator "escape-project"
copyDirectory projectDirectory escapeDirectory
replaceWithSymlink projectDirectory escapeDirectory
assertArtifactRejected client runId)
[<Fact>]
let ``artifact serving rejects symlinked run directories`` () =
withApp (fun client coordinator ->
let runId = "run-api-runlink"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store -> store.Snapshot().Status = "complete"))
)
assertArtifactServed client runId
let escapeDirectory = outsideDirectory coordinator "escape-run"
copyDirectory (runDirectory coordinator runId) escapeDirectory
replaceWithSymlink (runDirectory coordinator runId) escapeDirectory
assertArtifactRejected client runId)
[<Fact>]
let ``artifact serving rejects links introduced during an active run`` () =
let gate = new ManualResetEventSlim(false)
try
withAppUsing
(fun () -> StepGatedBridge(gate) :> IArtifactBridge)
(fun client coordinator ->
let runId = "run-api-midlink"
use content = new StringContent(requestBody runId, Encoding.UTF8, "application/json")
let start = client.PostAsync("/api/runs/start", content).GetAwaiter().GetResult()
Assert.Equal(HttpStatusCode.Accepted, start.StatusCode)
Assert.True(
waitFor (fun () ->
coordinator.TryFind(ids.ProjectId, runId)
|> Option.exists (fun store ->
let snapshot = store.Snapshot()
snapshot.Status = "running" && snapshot.CompletedSteps.Length = 1))
)
let escapeDirectory = outsideDirectory coordinator "escape-midrun"
copyDirectory (runDirectory coordinator runId) escapeDirectory
replaceWithSymlink (runDirectory coordinator runId) escapeDirectory
gate.Set()
waitForTerminal coordinator runId
assertArtifactRejected client runId)
finally
gate.Set()
gate.Dispose()
|