-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCWorkerOrchestrator.swift
More file actions
1401 lines (1322 loc) · 70.8 KB
/
Copy pathCWorkerOrchestrator.swift
File metadata and controls
1401 lines (1322 loc) · 70.8 KB
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Darwin
import Foundation
/*
* CWorkerOrchestrator — host-side wiring that runs a single specimen
* through the runner's C code path: pw-probe-runner for attempts +
* sb_api_validator --batch for sandbox_check verdicts, joined into
* one PWRunnerRunResult envelope.
*
* The orchestrator owns:
* 1. Request → driver inputs translation:
* - probe_plan → [CWorkerSlotInput] (worker attempts)
* - probe_plan → [ValidatorProbe] (validator queries),
* skipping (op, filter) pairs in
* ProbeRunner.predictionUnavailableOpFilters
* - policy.params → [CWorkerParam]
* 2. Driver invocation:
* - runCWorker(...) with a postApplied hook that runs
* runValidator against the sandboxed worker_pid
* 3. Driver outputs → per-step PWRunnerStepResult:
* - sandbox_check from validator verdict OR synthesized
* prediction_unavailable result for skipped pairs
* - attempt from CWorker slot result
* - comparison records submitted scope, derivation and known limits;
* drift projects supported agreement to false; current evidence
* cannot establish disagreement even when query order is known
* 4. Classifier:
* - normalized_outcome from C-worker disposition +
* validator disposition + per-slot completed/done state
*
* Validation, libsandbox-availability checks, and policy-hash
* computation are PWRunnerService.runSpecimen's responsibility.
* The orchestrator only sees a request that has already passed
* those gates.
*/
public enum CWorkerOrchestrator {
// ---- entry point -----------------------------------------------------
public static func run(
parsed: PWRunnerRunSpec,
policyHash: String,
bundleId: String?,
workerExecutablePath: String,
validatorExecutablePath: String
) -> PWRunnerRunResult {
run(parsed: parsed, policyHash: policyHash, bundleId: bundleId,
workerExecutablePath: workerExecutablePath, validatorExecutablePath: validatorExecutablePath,
validatorSpawn: nativeValidatorSpawn)
}
// Tests substitute only the native validator launch; worker orchestration,
// classification, evidence assembly and reply encoding remain production.
static func run(
parsed: PWRunnerRunSpec,
policyHash: String,
bundleId: String?,
workerExecutablePath: String,
validatorExecutablePath: String,
validatorSpawn: @escaping ValidatorSpawnCall
) -> PWRunnerRunResult {
if let refused = admissionFailure(for: parsed) {
return admissionRefusalReply(parsed: parsed, refused: refused, bundleId: bundleId, policyHash: policyHash)
}
// ---- translation: request → driver inputs ------------------------
let workerSlots = workerSlotsFromProbePlan(parsed.probe_plan)
let workerParams = workerParamsFromPolicy(parsed.policy)
let queryPlan = planValidatorQueries(parsed.probe_plan)
let validatorProbes = queryPlan.compactMap { $0.probe }
// _test_overrides.worker_timeout_ms drives the sentinel
// deadline on the C-worker path. Floored at 50 ms because a
// smaller deadline fires before any real worker can complete
// its post-apply work and would just generate spurious
// runner_timeouts.
let workerInput = CWorkerInput(
workerExecutablePath: workerExecutablePath,
policy: parsed.policy.sbpl_source ?? "",
params: workerParams,
slots: workerSlots,
sentinelTimeoutMs: timeoutMsForCWorker(
override: parsed._test_overrides?.worker_timeout_ms
),
postApplyHangMs: parsed._test_overrides?.worker_post_apply_hang_ms,
postApplyKillSignal: parsed._test_overrides?.worker_post_apply_kill_signal,
preReadyHangMs: parsed._test_overrides?.worker_pre_ready_hang_ms,
captureAppliedProfile: parsed.policy.capture_applied_profile == true,
captureNonce: parsed.policy.capture_nonce
)
// ---- run worker + validator together via postApplied hook --------
var validatorResult: ValidatorClientResult? = nil
let workerResult = runCWorker(workerInput) { workerPid in
// Skip validator entirely when every step's (op, filter) is
// in the prediction_unavailable set: no probes to send means
// no useful validator work. Avoids spawning a child only to
// immediately reap it.
if validatorProbes.isEmpty { return }
let vInput = ValidatorClientInput(
executablePath: validatorExecutablePath,
targetPid: workerPid,
probes: validatorProbes,
verdictReadTimeoutMs: timeoutMsForValidator(override: parsed._test_overrides?.validator_io_timeout_ms)
)
validatorResult = runValidator(vInput, processCalls: ChildProcessCalls(), spawn: validatorSpawn)
}
// ---- assemble + classify -----------------------------------------
let workerOutput = unwrapWorkerOutput(workerResult)
let disposition = workerOutput.map { resolveDisposition($0, plan: parsed.probe_plan) }
let runOutcome = classify(
workerResult: workerResult,
validatorResult: validatorResult,
expectedVerdictCount: validatorProbes.count,
disposition: disposition
)
let validatorOutput = unwrapValidatorOutput(validatorResult)
let ordering = workerOutput.map {
buildOrdering($0, validatorOutput: validatorOutput, hasQueries: !validatorProbes.isEmpty)
}
// A pre-spawn refusal is a bad_request like the service's own: the
// reply carries the refusal record and no steps (see isPreSpawnRefusal).
let stepResults: [PWRunnerStepResult]
if case .failure(let error, nil) = workerResult, error.isPreSpawnRefusal {
stepResults = []
} else {
stepResults = buildStepResults(
probePlan: parsed.probe_plan,
queryPlan: queryPlan,
workerOutput: workerOutput,
validatorOutput: validatorOutput, ordering: ordering,
disposition: disposition
)
}
let admissionFailure: PWRunnerAdmissionFailure?
if case .failure(.admissionFailed(let record), _) = workerResult { admissionFailure = record }
else { admissionFailure = nil }
let topPid: Int = workerOutput.map { Int($0.workerPid) } ?? Int(getpid())
var runnerSubprocess = workerOutput.map { buildWorkerSubprocess($0, disposition: disposition) }
runnerSubprocess?.ordering = ordering
let validatorSubprocess = validatorOutput.map(buildValidatorSubprocess)
let validatorSpawnFailure: PWRunnerSpawnFailure?
if case .failure(.spawnFailed(let failure), _) = validatorResult { validatorSpawnFailure = failure }
else { validatorSpawnFailure = nil }
return PWRunnerRunResult(
specimen_id: parsed.specimen_id,
run_kind: parsed.run_kind,
rc: runOutcome.rc,
normalized_outcome: runOutcome.outcome,
error: runOutcome.error,
pid: topPid,
bundle_id: bundleId,
policy_format: parsed.policy.format,
policy_sha256: policyHash,
sandboxed_after_apply: workerOutput?.applied,
deny_signal_total: nil,
steps: stepResults,
runner_subprocess: runnerSubprocess,
validator_subprocess: validatorSubprocess,
test_overrides: parsed._test_overrides,
applied_profile: workerOutput?.profileCapture,
admission_failure: admissionFailure,
validator_spawn_failure: validatorSpawnFailure
)
}
// ---- bundle path resolution -----------------------------------------
/// pw-probe-runner lives at `<this xpc service>/Contents/MacOS/pw-probe-runner`.
/// The XPC service binary itself lives at
/// `<this xpc service>/Contents/MacOS/<service-name>` — Bundle.main
/// resolves to the service bundle. Sibling resolution.
public static func defaultWorkerExecutablePath() -> String {
let bundleURL = Bundle.main.bundleURL
return bundleURL
.appendingPathComponent("Contents/MacOS/pw-probe-runner")
.path
}
/// sb_api_validator is embedded both bundle-local (alongside
/// pw-probe-runner inside each XPC service) AND at the app's
/// top-level. The bundle-local copy is preferred so BYOXPC
/// runners — which live outside any app bundle — still find a
/// validator. The app-level path is the fallback for older
/// layouts where the bundle-local copy may be missing.
public static func defaultValidatorExecutablePath() -> String {
let bundleURL = Bundle.main.bundleURL
let bundleLocal = bundleURL
.appendingPathComponent("Contents/MacOS/sb_api_validator")
.path
if FileManager.default.isExecutableFile(atPath: bundleLocal) {
return bundleLocal
}
let appURL = bundleURL
.deletingLastPathComponent() // XPCServices/
.deletingLastPathComponent() // Contents/
.deletingLastPathComponent() // <app>.app/
return appURL
.appendingPathComponent("Contents/MacOS/sb_api_validator")
.path
}
// ---- validation -----------------------------------------------------
/// Every capacity refusal, decided from the decoded request alone. The
/// service runs this before semantic validation so that no later
/// diagnostic can echo an unbounded string: top-level strings first, then
/// the worker's shared-memory bounds in plan order, then the host-only
/// query strings and labels. Both service and direct orchestration use this
/// gate; the driver also retains its checks local to the ABI writer.
public static func admissionFailure(for parsed: PWRunnerRunSpec) -> PWRunnerAdmissionFailure? {
if let refused = requestAdmissionFailure(parsed) { return refused }
// Count checks precede translating an unbounded plan or sorting params.
if parsed.probe_plan.count > PWShmLayout.maxSteps {
return PWRunnerAdmissionFailure(field: "probe_plan", actual: parsed.probe_plan.count,
maximum: PWShmLayout.maxSteps, unit: "items")
}
if let count = parsed.policy.params?.count, count > PWShmLayout.maxParams {
return PWRunnerAdmissionFailure(field: "policy.params", actual: count,
maximum: PWShmLayout.maxParams, unit: "items")
}
let capacity = CWorkerInput(workerExecutablePath: "", policy: parsed.policy.sbpl_source ?? "",
params: workerParamsFromPolicy(parsed.policy), slots: workerSlotsFromProbePlan(parsed.probe_plan))
if let refused = workerAdmissionFailure(capacity) { return refused }
return queryAdmissionFailure(parsed.probe_plan)
}
/// Pre-spawn validation specific to the C-worker code path.
/// Returns a human-readable error string when the plan is
/// malformed; nil when it's safe to orchestrate. Callers map a
/// non-nil return to bad_request.
///
/// Only one plan-killing check today: step_ids must be unique.
/// The orchestrator joins the worker's per-slot outputs and the
/// validator's verdicts back to steps by step_id; a duplicate
/// would crash the Dictionary(uniqueKeysWithValues:) constructor
/// and kill the XPC service.
///
/// Unsupported (attempt.kind, attempt.action) combos are NOT
/// plan-killers — they downgrade to per-step
/// `attempt.outcome = "unsupported"` in the step builder,
/// mirroring the per-step skip behavior for unknown filter
/// kinds. The slot is mapped to PW_ATTEMPT_NONE so the C worker
/// no-ops it; the validator's sandbox_check verdict for that
/// step still runs.
public static func validateProbePlanForCWorker(_ plan: [PWRunnerProbeStep]) -> String? {
var seenStepIds: Set<String> = []
seenStepIds.reserveCapacity(plan.count)
for step in plan {
if !seenStepIds.insert(step.step_id).inserted {
return "duplicate step_id '\(step.step_id)' in probe_plan"
}
}
return nil
}
}
// MARK: - Helpers
/// Resolve the sentinel-timeout for the C worker from the request's
/// `_test_overrides.worker_timeout_ms`. Floor at 50 ms because a
/// smaller deadline fires before any real worker can complete its
/// post-apply work. nil/absent → CWorkerInput default (120s, the worker
/// window; the separate C exec budget leaves a nominal publication margin,
/// not a guarantee against blocking native calls; see docs/LIMITS.md).
func timeoutMsForCWorker(override: Int?) -> Int {
let cWorkerDefault = CWorkerInput.defaultSentinelTimeoutMs
guard let v = override else { return cWorkerDefault }
return max(50, v)
}
// Configuration allowance for observation, setup, decode and scheduling;
// the nominal relation covers defaults, not fault-injection overrides. It is
// not an enforced bound on final reap or host descheduling.
let validatorReleaseMarginMs = 5_000
func timeoutMsForValidator(override: Int?) -> Int {
// Intentionally uncapped: tests may hold collection beyond worker expiry.
override.map { max(50, $0) } ?? 30_000
}
// MARK: - Translation: request → driver inputs
private func workerSlotsFromProbePlan(_ plan: [PWRunnerProbeStep]) -> [CWorkerSlotInput] {
var slots: [CWorkerSlotInput] = []
slots.reserveCapacity(plan.count)
for step in plan {
let slot = makeWorkerSlot(stepID: step.step_id, attempt: step.attempt)
slots.append(slot)
}
return slots
}
private func makeWorkerSlot(stepID: String, attempt: PWRunnerAttempt) -> CWorkerSlotInput {
// Exec attempts pass argv[1..N] via attempt.args; other kinds
// ignore the field. Defensive: only thread the args when the
// resolved attempt kind is .execSpawn so a caller that
// mistakenly populates args on a file probe doesn't pay the
// shm-write cost for ignored bytes.
let kind = mapAttemptKind(attempt)
let args: [String] = (kind == .execSpawn) ? (attempt.args ?? []) : []
return CWorkerSlotInput(
stepId: stepID,
attemptKind: kind,
target: attempt.target,
args: args
)
}
/// (kind, action) → C-worker PWAttemptKind. Returns nil for any
/// combo the C worker can't execute. The orchestrator falls back
/// to PW_ATTEMPT_NONE (worker no-ops the slot) and the step builder
/// then emits `attempt.outcome = "unsupported"` so the rc=0 slot
/// isn't misread as a successful observation.
// `internal` (not `private`) so AttemptOutcomeMappingTests can assert the
// Layer-1 routing table agrees with buildAttemptResult's outcome switch.
func mapAttemptKindOrNil(_ attempt: PWRunnerAttempt) -> PWAttemptKind? {
switch (attempt.kind, attempt.action) {
case (PWRunnerWire.attemptKindFile, PWRunnerWire.attemptActionOpenRead):
return .fileOpenRead
case (PWRunnerWire.attemptKindFile, PWRunnerWire.attemptActionOpenWrite):
return .fileOpenWrite
case (PWRunnerWire.attemptKindFile, PWRunnerWire.attemptActionCreate):
return .fileCreate
case (PWRunnerWire.attemptKindFile, PWRunnerWire.attemptActionUnlink):
return .fileUnlink
case (PWRunnerWire.attemptKindFile, PWRunnerWire.attemptActionAccess):
return .fileAccess
case (PWRunnerWire.attemptKindMachLookup, PWRunnerWire.attemptActionMachLookup):
return .machLookup
case (PWRunnerWire.attemptKindSysctl, PWRunnerWire.attemptActionRead):
return .sysctlRead
case (PWRunnerWire.attemptKindExec, PWRunnerWire.attemptActionSpawn):
return .execSpawn
default:
return nil
}
}
/// Fallback variant used for the shm slot. Unsupported attempts map to
/// PW_ATTEMPT_NONE so the worker no-ops the slot; buildAttemptResult
/// later surfaces the per-step `unsupported` outcome.
private func mapAttemptKind(_ attempt: PWRunnerAttempt) -> PWAttemptKind {
return mapAttemptKindOrNil(attempt) ?? .none
}
private func workerParamsFromPolicy(_ policy: PWRunnerPolicySpec) -> [CWorkerParam] {
guard let dict = policy.params, !dict.isEmpty else { return [] }
// Sort by key for a stable order — easier to debug, and the
// C worker iterates the array in order so deterministic param
// ordering helps when comparing runs.
return dict.keys.sorted().map { CWorkerParam(key: $0, value: dict[$0] ?? "") }
}
/// Snapshot the host's query decision before any worker attempt can change paths.
struct ValidatorQueryDecision {
let stepId: String
let probe: ValidatorProbe?
let exclusionReason: String?
var exclusionCode: String? = nil
}
/// Admission bounds for request strings the worker never carries.
/// `sandbox_check.operation` and `sandbox_check.filter.value` go to the
/// validator as one JSON line per probe and come back echoed in every step of
/// the reply; neither enters shared memory, so `workerAdmissionFailure` cannot
/// bound them. Left unbounded, an admitted 256-step plan can outgrow the
/// controller's reply capture after every attempt has already run, and one
/// probe can exceed the validator's line buffer and lose its prediction while
/// its attempt still runs. Bounded, a fully escaped probe line stays a few KiB
/// and the per-step reply overhead is a sum of documented limits. The values
/// match the attempt target (511) and the parameter key (127); no libsandbox
/// operation name approaches 127 bytes and filter values are paths or names.
/// Units are UTF-8 bytes excluding any terminating NUL, like the worker bounds.
let sandboxCheckOperationMaxBytes = 127
let sandboxCheckFilterValueMaxBytes = 511
// Unknown labels remain supported as per-step unavailable/unsupported results
// within this bound. They are echoed verbatim, sometimes in several fields.
let probePlanLabelMaxBytes = 127
/// Host-only capacity check for the sandbox_check strings, using the same
/// record as the driver's shared-memory bounds. The value is bounded for every
/// filter kind, including `none` and unrecognized kinds, because the reply
/// echoes whatever was supplied. Filter kind and attempt labels also stay on
/// the host and are echoed even when unrecognized. Checks run in plan order,
/// operation then value then labels within a step, and report the first excess.
func queryAdmissionFailure(_ plan: [PWRunnerProbeStep]) -> PWRunnerAdmissionFailure? {
for (position, step) in plan.enumerated() {
let fields: [(AdmissionStringRule, String?)] = [
(AdmissionStringRule(field: "sandbox_check.operation", maximum: sandboxCheckOperationMaxBytes, requiresCString: true), step.sandbox_check.operation),
(AdmissionStringRule(field: "sandbox_check.filter.value", maximum: sandboxCheckFilterValueMaxBytes, requiresCString: true), step.sandbox_check.filter.value),
(AdmissionStringRule(field: "sandbox_check.filter.kind", maximum: probePlanLabelMaxBytes), step.sandbox_check.filter.kind),
(AdmissionStringRule(field: "attempt.kind", maximum: probePlanLabelMaxBytes), step.attempt.kind),
(AdmissionStringRule(field: "attempt.action", maximum: probePlanLabelMaxBytes), step.attempt.action),
]
for (rule, value) in fields {
if var refused = rule.failure(value) {
refused.step_id = stepIdAdmission.safeEcho(step.step_id)
refused.step_index = position
return refused
}
}
}
return nil
}
/// Bounds for the request strings echoed once per reply rather than per step:
/// the specimen ID, the run kind and policy format labels, and the test-seam
/// executable paths mirrored back in `test_overrides` and named in dlopen and
/// spawn diagnostics. Amplification is one, so these matter only for a request
/// about as large as the reply cap; they complete the rule that every echoed
/// request string is admission-bounded. PATH_MAX is 1024 including the NUL.
let specimenIdMaxBytes = 255
let requestLabelMaxBytes = 63
let testOverridePathMaxBytes = 1023
// The same rules select refusals and decide which metadata may be echoed.
// Adding a field requires an entry here and an explicit projection below.
let specimenIdAdmission = AdmissionStringRule(field: "specimen_id", maximum: specimenIdMaxBytes)
let runKindAdmission = AdmissionStringRule(field: "run_kind", maximum: requestLabelMaxBytes)
let policyFormatAdmission = AdmissionStringRule(field: "policy.format", maximum: requestLabelMaxBytes)
let overridePathAdmissions: [(key: WritableKeyPath<PWRunnerTestOverrides, String?>, rule: AdmissionStringRule)] = [
(\.libsandbox_path, AdmissionStringRule(field: "_test_overrides.libsandbox_path", maximum: testOverridePathMaxBytes, requiresCString: true)),
(\.worker_executable_path, AdmissionStringRule(field: "_test_overrides.worker_executable_path", maximum: testOverridePathMaxBytes, requiresCString: true)),
(\.validator_executable_path, AdmissionStringRule(field: "_test_overrides.validator_executable_path", maximum: testOverridePathMaxBytes, requiresCString: true)),
]
func requestAdmissionFailure(_ parsed: PWRunnerRunSpec) -> PWRunnerAdmissionFailure? {
for (rule, value) in [(specimenIdAdmission, parsed.specimen_id),
(runKindAdmission, parsed.run_kind), (policyFormatAdmission, parsed.policy.format)] {
if let refused = rule.failure(value) { return refused }
}
if let overrides = parsed._test_overrides {
for (key, rule) in overridePathAdmissions {
if let refused = rule.failure(overrides[keyPath: key]) { return refused }
}
}
return nil
}
/// Failure selection and safe echo are independent: every metadata field is
/// checked even when a different field won admission precedence. No rejected
/// value is shortened into an apparent submitted identity.
func admissionRefusalReply(parsed: PWRunnerRunSpec, refused: PWRunnerAdmissionFailure,
bundleId: String?, policyHash: String? = nil) -> PWRunnerRunResult {
var mirrored = parsed._test_overrides
if var overrides = mirrored {
for (key, rule) in overridePathAdmissions {
overrides[keyPath: key] = rule.safeEcho(overrides[keyPath: key])
}
mirrored = overrides
}
var record = refused
record.step_id = stepIdAdmission.safeEcho(record.step_id)
record.parameter_key = parameterKeyAdmission.safeEcho(record.parameter_key)
return PWRunnerRunResult(
specimen_id: specimenIdAdmission.safeEcho(parsed.specimen_id) ?? "<admission_refused>",
run_kind: runKindAdmission.safeEcho(parsed.run_kind), rc: 1,
normalized_outcome: NormalizedOutcome.badRequest,
error: CWorkerRunError.admissionFailed(record).description, pid: Int(getpid()),
bundle_id: bundleId, policy_format: policyFormatAdmission.safeEcho(parsed.policy.format) ?? "unknown",
policy_sha256: policyHash, steps: [], test_overrides: mirrored, admission_failure: record)
}
func planValidatorQueries(_ plan: [PWRunnerProbeStep]) -> [ValidatorQueryDecision] {
plan.map { step in
let check = step.sandbox_check
let kind = check.filter.kind
let reason: String?
let code: String?
if predictionUnavailableOpFilters.contains(PredictionUnavailablePair(operation: check.operation, filterKind: kind)) {
reason = "prediction unavailable for this operation and filter"
code = "prediction_unavailable_pair"
} else if !knownFilterKinds.contains(kind) {
reason = "prediction unavailable for unrecognized filter kind"
code = "unrecognized_filter_kind"
} else if pathFilterIsUnresolvable(kind, check.filter.value) {
reason = "target path \(check.filter.value ?? "") did not resolve on the host when the query was planned"
code = "path_unresolved_at_planning"
} else { reason = nil; code = nil }
return ValidatorQueryDecision(stepId: step.step_id,
probe: reason == nil ? ValidatorProbe(stepId: step.step_id, operation: check.operation,
filterType: mapFilterKindToValidator(kind),
filterValue: kind == PWRunnerWire.sandboxFilterNone ? nil : check.filter.value) : nil,
exclusionReason: reason, exclusionCode: code)
}
}
/// True when the step's filter is a path whose value does not
/// resolve on the host via realpath. The kernel's file-op vectors
/// (open, access, …) ENOENT before they reach the sandbox layer for
/// absent paths, so a libsandbox verdict for such a path is a
/// userland artifact, not a kernel prediction. We skip the
/// validator probe and synthesize prediction_unavailable for these
/// steps; the attempt channel still runs and carries the real
/// observation. NONE-filter and resolvable paths are unaffected.
private func pathFilterIsUnresolvable(_ kind: String, _ value: String?) -> Bool {
guard kind == PWRunnerWire.sandboxFilterPath else { return false }
guard let v = value, !v.isEmpty else { return false }
return canonicalizePath(v).resolved == nil
}
private func mapFilterKindToValidator(_ wireKind: String) -> String {
switch wireKind {
case PWRunnerWire.sandboxFilterNone: return "NONE"
case PWRunnerWire.sandboxFilterPath: return "PATH"
case PWRunnerWire.sandboxFilterGlobalName: return "GLOBAL_NAME"
case PWRunnerWire.sandboxFilterLocalName: return "LOCAL_NAME"
case PWRunnerWire.sandboxFilterIokitRegistryEntryClass: return "IOKIT_REGISTRY_ENTRY_CLASS"
case PWRunnerWire.sandboxFilterIokitUserClientClass: return "IOKIT_USER_CLIENT_CLASS"
case PWRunnerWire.sandboxFilterSysctlName: return "SYSCTL_NAME"
default:
// validateSandboxChecks already rejected unknown kinds; this
// branch shouldn't fire. Emit the literal so a future extension
// pre-validateSandboxChecks fails loudly via the validator's
// bad_filter response.
return wireKind.uppercased()
}
}
// MARK: - Driver-result unwrapping
private func unwrapWorkerOutput(_ result: CWorkerRunResult) -> CWorkerOutput? {
switch result {
case .success(let out): return out
case .failure(_, let partial): return partial
}
}
private func unwrapValidatorOutput(_ result: ValidatorClientResult?) -> ValidatorOutput? {
guard let result else { return nil }
switch result {
case .success(let out): return out
case .failure(_, let partial): return partial // degraded evidence is still evidence
}
}
// MARK: - Step builder
func buildStepResults(
probePlan: [PWRunnerProbeStep],
queryPlan: [ValidatorQueryDecision],
workerOutput: CWorkerOutput?,
validatorOutput: ValidatorOutput?,
ordering: PWRunnerOrdering? = nil,
disposition: PWDispositionRecord? = nil
) -> [PWRunnerStepResult] {
// One resolved account for every lifecycle projection below.
let account = disposition ?? workerOutput.map { resolveDisposition($0, plan: probePlan) }
// Index outputs by step_id for the join.
let workerSlotsByStep = uniquelyAssociatedWorkerSlots(workerOutput?.slots ?? [])
let probes = queryPlan.compactMap { $0.probe }
let decisions = Dictionary(uniqueKeysWithValues: queryPlan.map { ($0.stepId, $0) })
let verdictsByStep = associateValidatorVerdicts(validatorOutput?.verdicts ?? [], expected: probes).byStep
// No worker means no PID for a worker-targeted sandbox query.
let sbCheckPid = workerOutput.map { Int($0.workerPid) }
// Join both channels for every step before any comparison. With order
// unestablished, any attempt in the run may precede any query, so the
// classifier must see the whole run's attempts, not a prefix of them.
var channels: [(step: PWRunnerProbeStep, sandboxCheck: PWRunnerSandboxCheckResult,
attempt: PWRunnerAttemptResult)] = []
channels.reserveCapacity(probePlan.count)
for (index, step) in probePlan.enumerated() {
var sandboxCheck = buildSandboxCheckResult(
step: step,
verdict: verdictsByStep[step.step_id],
sandboxCheckPid: sbCheckPid,
exclusionReason: decisions[step.step_id]?.exclusionReason
)
var attempt = buildAttemptResult(
step: step,
slot: workerSlotsByStep[step.step_id]
)
// Excluded queries are synthesized even if an unexpected validator
// record names their step. Do not attribute the synthesized result to it.
let verdict = sandboxCheck.outcome == SandboxCheckOutcome.predictionUnavailable
? nil : verdictsByStep[step.step_id]
sandboxCheck.result_source = verdict == nil ? "synthetic" : "validator"
sandboxCheck.native_rc = verdict.flatMap {
["allow", "deny", "error"].contains($0.outcome) ? $0.rc : nil
}
if verdict == nil {
sandboxCheck.missing_reason = sandboxCheck.outcome == SandboxCheckOutcome.predictionUnavailable
? "query_not_requested" : validatorOutput == nil ? "validator_not_invoked" : "validator_no_verdict"
}
let slot = workerSlotsByStep[step.step_id]
let recordStep = account?.steps.indices.contains(index) == true ? account?.steps[index] : nil
let supported = recordStep.map { $0.attempt_support == "supported" } ?? (mapAttemptKindOrNil(step.attempt) != nil)
let slotState = recordStep?.slot ?? (slot == nil ? "absent" : slot!.completed ? "completed" : "incomplete")
attempt.requested_kind = step.attempt.kind
attempt.requested_action = step.attempt.action
attempt.result_source = slotState == "completed" && supported ? "worker" : "synthetic"
// Slot rc is PW's attempt status (often 0/1), not the raw syscall
// return (e.g. an open FD). ABI 7 does not carry that native return.
attempt.native_rc = nil
if attempt.result_source == "synthetic" {
attempt.missing_reason = !supported ? "attempt_not_supported" : slotState == "absent" ? "slot_absent" : "slot_incomplete"
}
// The lifecycle object projects this step's two claims; the compatibility
// triple above is unchanged.
if let account, account.steps.indices.contains(index) {
attempt.lifecycle = attemptLifecycle(account.steps[index])
}
channels.append((step: step, sandboxCheck: sandboxCheck, attempt: attempt))
}
let runAttempts = channels.map { $0.attempt }
return channels.map { channel in
var comparison = computeComparison(sandboxCheck: channel.sandboxCheck, attempt: channel.attempt,
queryExclusionReason: decisions[channel.step.step_id]?.exclusionCode,
order: eligibleOrderedStep(stepId: channel.step.step_id, query: channel.sandboxCheck,
records: validatorOutput?.verdicts ?? [], ordering: ordering,
sandboxedAfterApply: workerOutput?.applied == true && workerOutput?.applyRC == 0,
workerPid: workerOutput.map { Int($0.workerPid) })
? .queryFirst : .unestablished, runAttempts: runAttempts)
// Exactly one lifecycle limitation for a summary other than completed. It
// never changes agreement, order, drift or sandbox attribution.
if let summary = channel.attempt.lifecycle?.summary,
let limitation = PWDisposition.limitationForSummary[summary] {
comparison.limitations.append(limitation)
}
return PWRunnerStepResult(
step_id: channel.step.step_id,
sandbox_check: channel.sandboxCheck,
attempt: channel.attempt,
deny_signal: nil,
drift: comparison.drift,
comparison: comparison
)
}
}
private func buildSandboxCheckResult(
step: PWRunnerProbeStep,
verdict: ValidatorVerdict?,
sandboxCheckPid: Int?,
exclusionReason: String?
) -> PWRunnerSandboxCheckResult {
let scope = PWRunnerWire.sandboxCheckScopePost
let kind = step.sandbox_check.filter.kind
let value = step.sandbox_check.filter.value
if let reason = exclusionReason {
return PWRunnerSandboxCheckResult(rc: -1, outcome: SandboxCheckOutcome.predictionUnavailable,
pid: sandboxCheckPid, operation: step.sandbox_check.operation, scope: scope,
filter_kind: kind, filter_value: value, error: reason)
}
// Validator didn't return a verdict for this step (validator never
// ran, or it died mid-stream and this step was past the partial
// cutoff). Surface as outcome=error so consumers see the gap.
guard let v = verdict else {
return PWRunnerSandboxCheckResult(
rc: 0,
outcome: SandboxCheckOutcome.error,
pid: sandboxCheckPid,
operation: step.sandbox_check.operation,
scope: scope,
filter_kind: kind,
filter_value: value,
filter_type_id: nil,
errno: nil,
error: "no validator verdict for this step",
path_diagnostics: nil
)
}
return PWRunnerSandboxCheckResult(
rc: v.rc ?? -1,
outcome: mapValidatorOutcomeToSandboxCheckOutcome(v.outcome),
pid: sandboxCheckPid,
operation: v.operation ?? step.sandbox_check.operation,
scope: scope,
filter_kind: kind,
filter_value: value,
filter_type_id: v.filterTypeId,
errno: v.errnoVal,
error: v.error,
path_diagnostics: nil
)
}
/// The validator emits its own outcome vocabulary (allow / deny /
/// error / unsupported_operation / parse_error / bad_filter). Map
/// to the host's SandboxCheckOutcome catalog:
/// - allow / deny → same
/// - unsupported_operation → same (distinct outcome so consumers
/// can route bare-op-name failures as per-step skips rather
/// than runtime errors; the validator's error string is
/// threaded through PWRunnerSandboxCheckResult.error)
/// - everything else (error / parse_error / bad_filter / unknown)
/// folds into SandboxCheckOutcome.error with the validator's
/// own error string in the error field via the verdict itself
/// (set upstream)
private func mapValidatorOutcomeToSandboxCheckOutcome(_ vOutcome: String) -> String {
switch vOutcome {
case "allow": return SandboxCheckOutcome.allow
case "deny": return SandboxCheckOutcome.deny
case "unsupported_operation": return SandboxCheckOutcome.unsupportedOperation
default: return SandboxCheckOutcome.error
}
}
// `internal` (not `private`) so AttemptOutcomeMappingTests can drive the
// (kind, action, slot) → AttemptOutcome mapping directly. This is the
// third host classifier alongside computeComparison/classify; the test pins
// each cell so the two stacked tables (kind routing + the rc!=0 action
// switch) can't silently drift apart.
func buildAttemptResult(
step: PWRunnerProbeStep,
slot: CWorkerSlotResult?
) -> PWRunnerAttemptResult {
// Unsupported attempt (kind, action): the orchestrator routed
// the slot to PW_ATTEMPT_NONE so the worker no-ops it; surface
// that here as outcome="unsupported" rather than letting the
// rc=0 no-op masquerade as a successful "ok" observation. The
// sandbox_check verdict for this step still runs and gets
// attached normally; drift falls out as null because the
// attempt didn't produce an allow/deny verdict.
if mapAttemptKindOrNil(step.attempt) == nil {
return PWRunnerAttemptResult(
rc: -1,
errno: nil,
outcome: AttemptOutcome.unsupported,
error: "kind='\(step.attempt.kind)', action='\(step.attempt.action)' not implemented",
requested_path: step.attempt.target,
observed_path: nil
)
}
// Missing or incomplete slots establish no completed attempt result.
// The compatibility spelling does not prove the operation never started.
guard let s = slot else {
return PWRunnerAttemptResult(
rc: -1,
errno: nil,
outcome: AttemptOutcome.notRunWorkerDied,
error: "no completed attempt result: slot unavailable",
requested_path: step.attempt.target,
observed_path: nil
)
}
if !s.completed {
return PWRunnerAttemptResult(
rc: -1,
errno: nil,
outcome: AttemptOutcome.notRunWorkerDied,
error: "no completed attempt result: slot publication incomplete",
requested_path: step.attempt.target,
observed_path: nil
)
}
// Slot completed. Map the C-worker rc/errno into the host's
// attempt outcome vocabulary. The error string the worker wrote
// already names which call failed (open / unlink / etc).
//
// Exec attempts are special: rc != 0 may mean either spawn-failed
// (child_pid == 0) or child-exited-non-zero (child_pid > 0). Both
// map to outcome=exec_failed, but the drift classifier uses
// child_pid downstream to distinguish them.
let outcome: String = {
if s.rc == 0 {
return AttemptOutcome.ok
}
// Dispatch on the attempt action rather than parsing the worker's
// error string — the requested action is authoritative.
switch step.attempt.action {
case PWRunnerWire.attemptActionOpenRead,
PWRunnerWire.attemptActionOpenWrite,
PWRunnerWire.attemptActionCreate:
return AttemptOutcome.openFailed
case PWRunnerWire.attemptActionUnlink:
return AttemptOutcome.unlinkFailed
case PWRunnerWire.attemptActionAccess:
return AttemptOutcome.accessFailed
case PWRunnerWire.attemptActionMachLookup:
return AttemptOutcome.lookupFailed
case PWRunnerWire.attemptActionRead:
return AttemptOutcome.sysctlFailed
case PWRunnerWire.attemptActionSpawn:
return AttemptOutcome.execFailed
default:
return AttemptOutcome.unsupported
}
}()
return PWRunnerAttemptResult(
rc: Int(s.rc),
errno: s.errnoVal == 0 ? nil : Int(s.errnoVal),
outcome: outcome,
error: s.error,
requested_path: step.attempt.target,
observed_path: s.observedPath,
child_pid: s.childPid.map { Int($0) },
child_exit_code: s.childExitCode.map { Int($0) },
child_term_signal: s.childTermSignal.map { Int($0) },
stdout: s.childStdout,
stderr: s.childStderr
)
}
// Only a completed worker observation supports mutation of the submitted object.
// Content writes and create-if-absent do not establish object removal/replacement.
private func reportsTargetRemoval(_ attempt: PWRunnerAttemptResult) -> Bool {
guard attempt.result_source == "worker", attempt.rc == 0 else { return false }
switch (attempt.requested_kind, attempt.requested_action, attempt.outcome) {
case ("file", "unlink", AttemptOutcome.ok): return true
default: return false
}
}
enum ComparisonOrder: String { case queryFirst = "query_first", unestablished }
enum ComparisonState { case unestablished }
enum ComparisonIdentity { case unestablished, notApplicable }
enum ComparisonAttribution { case unestablished, notRequired }
enum ComparisonMutation { case none, sameTargetUnordered, sameTargetAfterQuery }
struct ComparisonEvidence {
var order: ComparisonOrder
var state: ComparisonState = .unestablished
var identity: ComparisonIdentity
var attribution: ComparisonAttribution
var mutation: ComparisonMutation
var prediction: String
var observation: String
var basis: String
var operationRelation: String
var targetRelation: String
var otherLimitations: [String]
// No evidence for established state or runtime identity is expressible in
// response 8. In particular there is no constructible disagreement branch.
var conclusion: String {
guard operationRelation == "matched", targetRelation == "same_submitted" else { return "unavailable" }
if mutation == .sameTargetUnordered { return "unavailable" }
if observation == "succeeded", prediction == "allow" { return "agreement" }
if observation == "permission_failure", prediction == "deny" { return "directional_consistency" }
return "unavailable"
}
func renderLimitations() -> [String] {
var result: [String] = []
if order == .unestablished { result.append("query_attempt_order_unestablished") }
switch state { case .unestablished: result.append("state_stability_unestablished") }
if identity == .unestablished { result.append("runtime_target_identity_unestablished") }
if attribution == .unestablished { result.append("sandbox_attribution_unestablished") }
if mutation == .sameTargetUnordered { result.append("attempt_mutation_order_unestablished") }
return result + otherLimitations
}
var comparison: PWRunnerComparison {
PWRunnerComparison(scope: "submitted_operation_and_target", prediction: prediction,
observation: observation, observation_basis: basis, operation_relation: operationRelation,
target_relation: targetRelation, conclusion: conclusion, limitations: renderLimitations(), order: order.rawValue)
}
}
func buildOrdering(_ worker: CWorkerOutput, validatorOutput: ValidatorOutput?, hasQueries: Bool) -> PWRunnerOrdering {
let disposition = !worker.hookInvoked ? "not_invoked" : !hasQueries ? "not_needed"
: validatorOutput == nil ? "not_spawned" : validatorOutput?.reaped == true ? "reaped" : "unconfirmed"
var violations = worker.orderingProtocolViolations
if worker.proceedObserved && !worker.proceedSet { violations.append("acknowledgement_without_release") }
if worker.proceedSet && !worker.hookInvoked { violations.append("release_without_collection_closure") }
if (worker.proceedSet || worker.proceedObserved) && (!worker.applied || worker.applyRC != 0) {
violations.append("release_without_successful_application")
}
if worker.slots.contains(where: { $0.completed }) && !worker.proceedObserved {
violations.append("attempt_without_acknowledgement")
}
if worker.workerEvidence?.failure?.operation == 11 &&
(worker.proceedObserved || worker.slots.contains(where: { $0.completed })) {
violations.append("attempt_or_acknowledgement_after_proceed_failure")
}
return PWRunnerOrdering(collection_closed_before_proceed: worker.hookInvoked,
proceed_set: worker.proceedSet, proceed_observed: worker.proceedObserved,
validator_disposition: disposition, worker_lifetime_established: worker.proceedOwnershipEstablished,
protocol_violations: Array(Set(violations)).sorted())
}
func computeComparison(sandboxCheck: PWRunnerSandboxCheckResult, attempt: PWRunnerAttemptResult,
queryExclusionReason: String? = nil, order: ComparisonOrder = .unestablished,
runAttempts: [PWRunnerAttemptResult] = []) -> PWRunnerComparison {
comparisonEvidence(sandboxCheck: sandboxCheck, attempt: attempt, queryExclusionReason: queryExclusionReason,
order: order, runAttempts: runAttempts).comparison
}
// Internal for independent scenario controls. Query order alone cannot
// discharge state/identity obligations or establish drift.
// `runAttempts` is every worker-reported attempt in the run, in plan order.
// While order is unestablished the worker's attempt loop can finish before the
// validator's first query, so a same-target unlink in any step, earlier or
// later, may precede this query. The current attempt is always considered.
func comparisonEvidence(
sandboxCheck: PWRunnerSandboxCheckResult,
attempt: PWRunnerAttemptResult,
queryExclusionReason: String? = nil,
order: ComparisonOrder = .unestablished,
runAttempts: [PWRunnerAttemptResult] = []
) -> ComparisonEvidence {
var limits: [String] = []
var attribution: ComparisonAttribution = .notRequired
if let reason = queryExclusionReason { limits.append("query_plan:" + reason) }
let prediction = sandboxCheck.result_source == "validator"
&& [SandboxCheckOutcome.allow, SandboxCheckOutcome.deny].contains(sandboxCheck.outcome)
? sandboxCheck.outcome : "unavailable"
if prediction == "unavailable" {
limits.append("prediction:" + (sandboxCheck.missing_reason ?? "no_usable_verdict"))
}
var observation = "unavailable"
var basis = "no_completed_worker_result"
if attempt.result_source == "worker" {
if attempt.requested_kind == "exec", (attempt.child_pid ?? 0) > 0 {
observation = "succeeded"
basis = "spawned_child"
if attempt.rc != 0 {
limits.append("exec_result_failed_after_spawn")
attribution = .unestablished
}
} else if attempt.outcome == AttemptOutcome.ok && attempt.rc == 0 {
observation = "succeeded"
basis = "completed_worker_status"
} else if attempt.rc != 0 {
observation = "other_failure"
basis = "completed_worker_status"
if [AttemptOutcome.openFailed, AttemptOutcome.unlinkFailed,
AttemptOutcome.accessFailed, AttemptOutcome.sysctlFailed,
AttemptOutcome.execFailed].contains(attempt.outcome),
[Int(EPERM), Int(EACCES)].contains(attempt.errno ?? -1) {
observation = "permission_failure"
basis = "permission_errno"
} else if attempt.outcome == AttemptOutcome.lookupFailed,
attempt.error == "bootstrap_look_up: kr=1100" {
observation = "permission_failure"
basis = "bootstrap_permission_result"
}
}
}
if observation == "unavailable" {
limits.append("attempt:" + (attempt.missing_reason ?? "no_completed_worker_result"))
} else if observation != "succeeded" {
attribution = .unestablished
}
let operation: String?
let filter: String?
switch (attempt.requested_kind, attempt.requested_action) {
case ("file", "open_read"), ("file", "access"):
operation = "file-read-data"; filter = "path"
case ("file", "open_write"):
operation = "file-write-data"; filter = "path"
case ("file", "unlink"):
operation = "file-write-unlink"; filter = "path"
case ("mach_lookup", "bootstrap_look_up"):
operation = "mach-lookup"; filter = "global_name"
case ("sysctl", "read"):
operation = "sysctl-read"; filter = "sysctl_name"
case ("exec", "spawn"):
// The native query accepts this spelling, not bare process-exec.
// Native exec-scope controls isolate this target-admission query from
// fork/interpreter conditions. Matching it does not predict all spawn
// prerequisites; success supplies the execution observation separately.
operation = "process-exec*"; filter = "path"
limits.append("exec_query_not_full_spawn_prediction")
case ("file", "create"):
operation = nil; filter = "path"
limits.append("compound_attempt")
default:
operation = nil; filter = nil
limits.append("attempt_operation_unestablished")
}
let operationRelation: String
let matchedExecQuery = operation == "process-exec*" && sandboxCheck.operation == operation
let unresolvedBroadQuery = sandboxCheck.operation.contains("*") && !matchedExecQuery
if unresolvedBroadQuery { limits.append("broad_query_operation") }
if operation == nil || unresolvedBroadQuery {
operationRelation = "unresolved"
} else {
operationRelation = operation == sandboxCheck.operation ? "matched" : "different"
}
if operationRelation != "matched" { limits.append("operation:" + operationRelation) }
let targetRelation: String
if filter != nil && sandboxCheck.filter_kind != filter {
limits.append("query_filter_scope_unestablished")
}
if sandboxCheck.filter_value == nil || attempt.requested_path == nil {
limits.append("submitted_target_unavailable")
}
if filter == nil || sandboxCheck.filter_kind != filter
|| sandboxCheck.filter_value == nil || attempt.requested_path == nil {
targetRelation = "unresolved"
} else {
targetRelation = sandboxCheck.filter_value == attempt.requested_path
? "same_submitted" : "different_submitted"
}
if targetRelation != "same_submitted" { limits.append("target:" + targetRelation) }
let identity: ComparisonIdentity = sandboxCheck.filter_kind == "path" || filter == "path"