-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathplatform_commands.go
More file actions
2071 lines (1819 loc) · 55.5 KB
/
Copy pathplatform_commands.go
File metadata and controls
2071 lines (1819 loc) · 55.5 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
// SPDX-License-Identifier: Apache-2.0
// Copyright 2025 SentinelOps Platform Contributors
package main
import (
"bytes"
"crypto/ed25519"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"errors"
"fmt"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"time"
"github.com/spf13/cobra"
)
var (
apiBaseURL = "http://localhost:8000"
)
func init() {
if url := os.Getenv("SENTINELOPS_API_URL"); url != "" {
apiBaseURL = url
}
}
// policyCmd handles policy lifecycle commands
func policyCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "policy",
Short: "Manage policies (compile, build, prove, deploy)",
Long: `Complete policy lifecycle management for the SentinelOps Platform.`,
}
cmd.AddCommand(policyCompileCmd())
cmd.AddCommand(policyBuildCmd())
cmd.AddCommand(policyProveCmd())
cmd.AddCommand(policyDeployCmd())
cmd.AddCommand(policyListCmd())
return cmd
}
func policyCompileCmd() *cobra.Command {
var inputFile, outputDir string
var jsonOut bool
var diffOut bool
cmd := &cobra.Command{
Use: "compile --in <english.md> --out <build/>",
Short: "Compile English policy to ActionDSL",
Long: `Convert English policy description to ActionDSL format.`,
RunE: func(cmd *cobra.Command, args []string) error {
if dryRun {
fmt.Printf("DRY RUN: Would compile %s to %s\n", inputFile, outputDir)
return nil
}
// Read English policy
englishContent, err := os.ReadFile(inputFile)
if err != nil {
return fmt.Errorf("failed to read input file: %w", err)
}
// Prepare request
request := map[string]interface{}{
"english": string(englishContent),
"policy_id": filepath.Base(inputFile),
"version": "1.0.0",
}
// Call API
resp, err := callAPI("POST", "/api/v1/policy/compile", request)
if err != nil {
return err
}
// Create output directory
if err := os.MkdirAll(outputDir, 0755); err != nil {
return fmt.Errorf("failed to create output directory: %w", err)
}
// Write ActionDSL
actionDSLPath := filepath.Join(outputDir, "action_dsl.json")
actionDSLData, _ := json.MarshalIndent(resp["actionDsl"], "", " ")
if err := os.WriteFile(actionDSLPath, actionDSLData, 0644); err != nil {
return fmt.Errorf("failed to write ActionDSL: %w", err)
}
// Write IR with source map if present
if ir, ok := resp["ir"]; ok {
irPath := filepath.Join(outputDir, "ir.json")
irData, _ := json.MarshalIndent(ir, "", " ")
if err := os.WriteFile(irPath, irData, 0644); err != nil {
return fmt.Errorf("failed to write IR: %w", err)
}
}
// Write metadata
metadataPath := filepath.Join(outputDir, "metadata.json")
metadata := map[string]interface{}{
"policy_hash": resp["policy_hash"],
"timestamp": resp["timestamp"],
"diagnostics": resp["diagnostics"],
}
metadataData, _ := json.MarshalIndent(metadata, "", " ")
if err := os.WriteFile(metadataPath, metadataData, 0644); err != nil {
return fmt.Errorf("failed to write metadata: %w", err)
}
// Optional diff vs previous output
var diff string
if diffOut {
prevPath := filepath.Join(outputDir, "action_dsl.prev.json")
if b, err := os.ReadFile(prevPath); err == nil {
diff = computeJSONDiff(string(b), string(actionDSLData))
}
_ = os.WriteFile(prevPath, actionDSLData, 0644)
}
if jsonOut {
payload := map[string]any{
"ok": true,
"action_dsl_path": actionDSLPath,
"metadata_path": metadataPath,
"ir_path": filepath.Join(outputDir, "ir.json"),
"policy_hash": resp["policy_hash"],
"diagnostics": resp["diagnostics"],
}
if diffOut {
payload["diff"] = diff
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(payload)
} else {
fmt.Printf("✅ Policy compiled successfully\n")
fmt.Printf("📁 Output: %s\n", outputDir)
fmt.Printf("🔐 Policy hash: %s\n", resp["policy_hash"])
if diffOut && diff != "" {
fmt.Println("\nDiff vs previous ActionDSL:\n" + diff)
}
}
return nil
},
}
cmd.Flags().StringVar(&inputFile, "in", "", "Input English policy file")
cmd.Flags().StringVar(&outputDir, "out", "build/", "Output directory")
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output machine-readable JSON")
cmd.Flags().BoolVar(&diffOut, "diff", false, "Show JSON diff vs previous build output")
cmd.MarkFlagRequired("in")
return cmd
}
func policyProveCmd() *cobra.Command {
var buildDir string
var useMorph bool
var morphShards int
var jsonOut bool
cmd := &cobra.Command{
Use: "prove --build <build/>",
Short: "Run proofs for compiled policy",
Long: `Execute Lean proofs for the compiled policy.`,
RunE: func(cmd *cobra.Command, args []string) error {
if dryRun {
fmt.Printf("DRY RUN: Would run proofs for build in %s\n", buildDir)
return nil
}
// Load build metadata
metadataPath := filepath.Join(buildDir, "metadata.json")
metadataData, err := os.ReadFile(metadataPath)
if err != nil {
return fmt.Errorf("failed to read build metadata: %w", err)
}
var metadata map[string]interface{}
if err := json.Unmarshal(metadataData, &metadata); err != nil {
return fmt.Errorf("failed to parse metadata: %w", err)
}
// Load ActionDSL
actionDSLPath := filepath.Join(buildDir, "action_dsl.json")
actionDSLData, err := os.ReadFile(actionDSLPath)
if err != nil {
return fmt.Errorf("failed to read ActionDSL: %w", err)
}
var actionDSL interface{}
if err := json.Unmarshal(actionDSLData, &actionDSL); err != nil {
return fmt.Errorf("failed to parse ActionDSL: %w", err)
}
// Prepare proof request
request := map[string]interface{}{
"policy_hash": metadata["policy_hash"],
"action_dsl": actionDSL,
"use_morph": useMorph,
}
if useMorph && morphShards > 0 {
request["morph_shards"] = morphShards
}
// Call proof service
resp, err := callAPI("POST", "/api/v1/proofs/run", request)
if err != nil {
return err
}
// Update metadata with proof hash
metadata["proof_hash"] = resp["proof_hash"]
metadata["proof_status"] = resp["status"]
metadata["proof_artifacts"] = resp["artifacts"]
updatedMetadata, _ := json.MarshalIndent(metadata, "", " ")
if err := os.WriteFile(metadataPath, updatedMetadata, 0644); err != nil {
return fmt.Errorf("failed to update metadata: %w", err)
}
if jsonOut {
payload := map[string]any{
"ok": true,
"status": resp["status"],
"proof_hash": resp["proof_hash"],
"artifacts": resp["artifacts"],
"artifact_index": resp["artifact_index"],
"metadata": metadata,
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(payload)
} else {
fmt.Printf("✅ Proofs completed: %s\n", resp["status"])
fmt.Printf("🔐 Proof hash: %s\n", resp["proof_hash"])
if artifacts, ok := resp["artifacts"].([]interface{}); ok && len(artifacts) > 0 {
fmt.Printf("📁 Artifacts: %d files\n", len(artifacts))
}
}
// Persist local proofs manifest
proofsManifest := map[string]any{
"proof_hash": resp["proof_hash"],
"artifact_index": resp["artifact_index"],
"status": resp["status"],
}
pmBytes, _ := json.MarshalIndent(proofsManifest, "", " ")
_ = os.WriteFile(filepath.Join(buildDir, "proofs_manifest.json"), pmBytes, 0644)
return nil
},
}
cmd.Flags().StringVar(&buildDir, "build", "build/", "Build directory")
cmd.Flags().BoolVar(&useMorph, "morph", false, "Use Morph distributed proving")
cmd.Flags().IntVar(&morphShards, "shards", 4, "Number of Morph shards")
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output machine-readable JSON")
return cmd
}
func deployCmd() *cobra.Command {
var buildDir string
var epochRotate bool
var jsonOut bool
cmd := &cobra.Command{
Use: "deploy --build <build/> [--epoch rotate]",
Short: "Deploy policy build to runtime",
Long: `Deploy a built policy to the runtime environment.`,
RunE: func(cmd *cobra.Command, args []string) error {
if dryRun {
fmt.Printf("DRY RUN: Would deploy build from %s\n", buildDir)
return nil
}
// Load build metadata
metadataPath := filepath.Join(buildDir, "metadata.json")
metadataData, err := os.ReadFile(metadataPath)
if err != nil {
return fmt.Errorf("failed to read build metadata: %w", err)
}
var metadata map[string]interface{}
if err := json.Unmarshal(metadataData, &metadata); err != nil {
return fmt.Errorf("failed to parse metadata: %w", err)
}
// Check required hashes
policyHash, ok := metadata["policy_hash"].(string)
if !ok || policyHash == "" {
return fmt.Errorf("missing policy_hash in metadata")
}
automataHash, ok := metadata["automata_hash"].(string)
if !ok || automataHash == "" {
return fmt.Errorf("missing automata_hash - run build first")
}
// Determine epoch
currentEpoch := 1
if epochRotate {
currentEpoch++
}
// Deploy request
request := map[string]interface{}{
"policy_hash": policyHash,
"automata_hash": automataHash,
"epoch": currentEpoch,
}
resp, err := callAPI("POST", "/api/v1/runtime/deploy", request)
if err != nil {
return err
}
if jsonOut {
payload := map[string]any{
"ok": true,
"policy_hash": policyHash,
"automata_hash": automataHash,
"epoch": resp["epoch"],
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(payload)
} else {
fmt.Printf("✅ Policy deployed successfully\n")
fmt.Printf("🔐 Policy hash: %s\n", policyHash)
fmt.Printf("🔧 Automata hash: %s\n", automataHash)
fmt.Printf("⏰ Epoch: %v\n", resp["epoch"])
}
return nil
},
}
cmd.Flags().StringVar(&buildDir, "build", "build/", "Build directory")
cmd.Flags().BoolVar(&epochRotate, "epoch", false, "Rotate epoch during deployment")
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output machine-readable JSON")
return cmd
}
// certCmd handles certificate operations
func certCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "cert",
Short: "Certificate operations (verify, search)",
Long: `Validate and search CERT-V1 certificates.`,
}
cmd.AddCommand(certVerifyCmd())
cmd.AddCommand(certSearchCmd())
return cmd
}
func certVerifyCmd() *cobra.Command {
var jsonOut bool
var schemaValidate bool
var schemaPath string
var jwksURL string
var keyPath string
cmd := &cobra.Command{
Use: "verify <cert-files...>",
Short: "Verify CERT-V1 certificates",
Long: `Validate certificate files against CERT-V1 schema.`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if dryRun {
fmt.Printf("DRY RUN: Would verify %d certificate files\n", len(args))
return nil
}
var checkedFiles []string
totalCerts := 0
validCerts := 0
invalidCerts := 0
var invalidList []map[string]string
sigChecked := 0
sigVerified := 0
sigFailed := 0
signatureVerificationEnabled := (jwksURL != "" || keyPath != "")
for _, certFile := range args {
// Check if it's a directory or file
if info, err := os.Stat(certFile); err == nil && info.IsDir() {
// Process directory
err := filepath.Walk(certFile, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if strings.HasSuffix(path, ".cert.json") || strings.HasSuffix(path, ".json") {
checkedFiles = append(checkedFiles, path)
if verifyFileWithSchema(path, schemaPath) {
validCerts++
} else {
invalidCerts++
invalidList = append(invalidList, map[string]string{"file": path})
}
totalCerts++
if signatureVerificationEnabled {
sigChecked++
ok, reason := verifyCertSignatureForFile(path, jwksURL, keyPath)
if !ok {
sigFailed++
invalidList = append(invalidList, map[string]string{"file": path, "signature": reason})
} else {
sigVerified++
}
}
}
return nil
})
if err != nil {
fmt.Printf("Warning: Error walking directory %s: %v\n", certFile, err)
}
} else {
// Process single file
if strings.HasSuffix(certFile, ".json") || strings.HasSuffix(certFile, ".cert.json") {
checkedFiles = append(checkedFiles, certFile)
}
if verifyFileWithSchema(certFile, schemaPath) {
validCerts++
} else {
invalidCerts++
invalidList = append(invalidList, map[string]string{"file": certFile})
}
totalCerts++
if signatureVerificationEnabled {
sigChecked++
ok, reason := verifyCertSignatureForFile(certFile, jwksURL, keyPath)
if !ok {
sigFailed++
invalidList = append(invalidList, map[string]string{"file": certFile, "signature": reason})
} else {
sigVerified++
}
}
}
}
// Optional schema validation via Python helper
schemaOK := true
schemaOutput := ""
if schemaValidate && len(checkedFiles) > 0 {
ok, out, err := validateCertSchemaWithPython(schemaPath, checkedFiles)
schemaOK, schemaOutput = ok, out
if err != nil {
// Treat execution error as failure
schemaOK = false
}
}
if jsonOut {
payload := map[string]any{
"total": totalCerts,
"valid": validCerts,
"invalid": invalidCerts,
}
if schemaValidate {
payload["schema_valid"] = schemaOK
payload["schema_output"] = schemaOutput
}
if signatureVerificationEnabled {
payload["signature_checked"] = sigChecked
payload["signature_verified"] = sigVerified
payload["signature_failed"] = sigFailed
}
if invalidCerts > 0 {
payload["invalid_files"] = invalidList
}
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(payload)
} else {
fmt.Printf("📊 Certificate Verification Summary:\n")
fmt.Printf(" Total: %d\n", totalCerts)
fmt.Printf(" Valid: %d\n", validCerts)
fmt.Printf(" Invalid: %d\n", invalidCerts)
if schemaValidate {
fmt.Printf(" Schema valid: %v\n", schemaOK)
}
if signatureVerificationEnabled {
fmt.Printf(" Signature checked: %d, verified: %d, failed: %d\n", sigChecked, sigVerified, sigFailed)
}
}
if invalidCerts > 0 || (schemaValidate && !schemaOK) || (signatureVerificationEnabled && sigFailed > 0) {
return fmt.Errorf("validation failed")
}
if !jsonOut {
fmt.Println("✅ All certificates are valid")
}
return nil
},
}
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output machine-readable JSON")
cmd.Flags().BoolVar(&schemaValidate, "schema-validate", false, "Validate against CERT-V1 schema using Python helper")
cmd.Flags().StringVar(&schemaPath, "schema", "external/CERT-V1/schema/cert-v1.schema.json", "Path to CERT-V1 JSON schema")
cmd.Flags().StringVar(&jwksURL, "jwks", "", "JWKS URL for Ed25519 signature verification")
cmd.Flags().StringVar(&keyPath, "key", "", "Path to PEM-encoded Ed25519 public key for signature verification")
return cmd
}
func validateCertSchemaWithPython(schemaPath string, files []string) (bool, string, error) {
// Try python3 then python
interp := "python3"
if _, err := exec.LookPath(interp); err != nil {
interp = "python"
}
args := []string{"tools/cert-validate/validate.py", "--schema", schemaPath}
args = append(args, files...)
cmd := exec.Command(interp, args...)
out, err := cmd.CombinedOutput()
return err == nil, string(out), err
}
// verifyFileWithSchema validates a single JSON file against the CERT-V1 schema using gojsonschema
func verifyFileWithSchema(filePath string, schemaPath string) bool {
// Prefer Python-based JSON Schema validator if available and schema provided
if schemaPath == "" {
schemaPath = "external/CERT-V1/schema/cert-v1.schema.json"
}
if _, err := os.Stat(schemaPath); err == nil {
if ok, _, err := validateCertSchemaWithPython(schemaPath, []string{filePath}); err == nil {
return ok
}
}
// Fallback: quick structural validation
data, err := os.ReadFile(filePath)
if err != nil {
return false
}
var cert map[string]interface{}
if err := json.Unmarshal(data, &cert); err != nil {
return false
}
// Required fields (subset consistent with docs/evidence/overview.md)
required := []string{
"bundle_id", "policy_hash", "proof_hash", "automata_hash", "labeler_hash",
"ni_monitor", "permit_decision", "path_witness_ok", "label_derivation_ok", "epoch", "egress_profile",
}
for _, k := range required {
if _, ok := cert[k]; !ok {
return false
}
}
// Basic enum check for ni_monitor
if v, ok := cert["ni_monitor"].(string); ok {
switch v {
case "inapplicable", "accept", "reject", "error":
// ok
default:
return false
}
} else {
return false
}
return true
}
// verifyCertSignatureForFile verifies the signature of a CERT-V1 JSON file using either a local key or JWKS.
// Returns (true, "") on success. On failure, returns (false, reason).
func verifyCertSignatureForFile(filePath, jwksURL, keyPath string) (bool, string) {
data, err := os.ReadFile(filePath)
if err != nil {
return false, "read_error"
}
var cert map[string]interface{}
if err := json.Unmarshal(data, &cert); err != nil {
return false, "invalid_json"
}
// Extract signature
sigVal, ok := cert["sig"]
if !ok {
return false, "missing_sig"
}
sigStr, ok := sigVal.(string)
if !ok || sigStr == "" {
return false, "invalid_sig"
}
// Remove signature field for canonicalization
delete(cert, "sig")
canon, err := marshalCanonicalJSON(cert)
if err != nil {
return false, "canonicalize_error"
}
// Signature can be base64 (std or URL) - try both
var sig []byte
if b, err := base64.StdEncoding.DecodeString(sigStr); err == nil {
sig = b
} else if b2, err2 := base64.RawURLEncoding.DecodeString(sigStr); err2 == nil {
sig = b2
} else {
return false, "sig_decode_error"
}
// Try local key first if provided
if keyPath != "" {
if pub, err := loadEd25519PublicKeyFromPEM(keyPath); err == nil {
if ed25519.Verify(pub, canon, sig) {
return true, ""
}
}
}
// Then try JWKS if provided
if jwksURL != "" {
pubs, err := fetchEd25519KeysFromJWKS(jwksURL)
if err == nil {
for _, pub := range pubs {
if ed25519.Verify(pub, canon, sig) {
return true, ""
}
}
}
}
return false, "signature_mismatch"
}
// loadEd25519PublicKeyFromPEM loads an Ed25519 public key from a PEM-encoded file (PKIX or raw)
func loadEd25519PublicKeyFromPEM(path string) (ed25519.PublicKey, error) {
pemBytes, err := os.ReadFile(path)
if err != nil {
return nil, err
}
block, _ := pem.Decode(pemBytes)
if block == nil {
return nil, errors.New("no PEM block found")
}
// Try PKIX first
pub, err := x509.ParsePKIXPublicKey(block.Bytes)
if err == nil {
if ed, ok := pub.(ed25519.PublicKey); ok {
return ed, nil
}
return nil, errors.New("not an Ed25519 public key")
}
// Try raw
if len(block.Bytes) == ed25519.PublicKeySize {
return ed25519.PublicKey(block.Bytes), nil
}
return nil, errors.New("unsupported public key format")
}
// fetchEd25519KeysFromJWKS fetches JWKS and returns all Ed25519 public keys
func fetchEd25519KeysFromJWKS(url string) ([]ed25519.PublicKey, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, fmt.Errorf("jwks http error: %s", resp.Status)
}
var jwks struct {
Keys []struct {
Kty string `json:"kty"`
Crv string `json:"crv"`
X string `json:"x"`
Use string `json:"use"`
Alg string `json:"alg"`
Kid string `json:"kid"`
} `json:"keys"`
}
if err := json.NewDecoder(resp.Body).Decode(&jwks); err != nil {
return nil, err
}
var pubs []ed25519.PublicKey
for _, k := range jwks.Keys {
if strings.EqualFold(k.Kty, "OKP") && strings.EqualFold(k.Crv, "Ed25519") {
// x is base64url without padding
raw, err := base64.RawURLEncoding.DecodeString(k.X)
if err != nil {
continue
}
if len(raw) == ed25519.PublicKeySize {
pubs = append(pubs, ed25519.PublicKey(raw))
}
}
}
if len(pubs) == 0 {
return nil, errors.New("no ed25519 keys in JWKS")
}
return pubs, nil
}
// marshalCanonicalJSON produces a canonical JSON encoding with lexicographically sorted object keys.
func marshalCanonicalJSON(v interface{}) ([]byte, error) {
var buf bytes.Buffer
if err := writeCanonicalJSON(&buf, v); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func writeCanonicalJSON(buf *bytes.Buffer, v interface{}) error {
switch t := v.(type) {
case map[string]interface{}:
buf.WriteByte('{')
// sort keys
keys := make([]string, 0, len(t))
for k := range t {
keys = append(keys, k)
}
sort.Strings(keys)
for i, k := range keys {
// key
kb, _ := json.Marshal(k)
buf.Write(kb)
buf.WriteByte(':')
if err := writeCanonicalJSON(buf, t[k]); err != nil {
return err
}
if i < len(keys)-1 {
buf.WriteByte(',')
}
}
buf.WriteByte('}')
return nil
case []interface{}:
buf.WriteByte('[')
for i, elem := range t {
if err := writeCanonicalJSON(buf, elem); err != nil {
return err
}
if i < len(t)-1 {
buf.WriteByte(',')
}
}
buf.WriteByte(']')
return nil
case json.Number:
buf.WriteString(string(t))
return nil
case string, float64, float32, bool, int, int64, nil:
b, err := json.Marshal(t)
if err != nil {
return err
}
buf.Write(b)
return nil
default:
// For any other type, re-marshal through encoding/json to a generic representation
b, err := json.Marshal(t)
if err != nil {
return err
}
var vv interface{}
if err := json.Unmarshal(b, &vv); err != nil {
return err
}
return writeCanonicalJSON(buf, vv)
}
}
// replayCmd handles replay operations
func replayCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "replay",
Short: "Replay operations (run, status)",
Long: `Execute and monitor deterministic replays.`,
}
cmd.AddCommand(replayRunCmd())
cmd.AddCommand(replayStatusCmd())
return cmd
}
func replayRunCmd() *cobra.Command {
var replayFile, outputDir string
var jsonOut bool
cmd := &cobra.Command{
Use: "run --file <replay.json> --out <output/>",
Short: "Run deterministic replay",
Long: `Execute a deterministic replay from a trace file.`,
RunE: func(cmd *cobra.Command, args []string) error {
if dryRun {
fmt.Printf("DRY RUN: Would run replay from %s to %s\n", replayFile, outputDir)
return nil
}
// Read replay file
replayData, err := os.ReadFile(replayFile)
if err != nil {
return fmt.Errorf("failed to read replay file: %w", err)
}
// Prepare request
request := map[string]interface{}{
"replay_data": string(replayData),
"output_dir": outputDir,
}
// Call API
resp, err := callAPI("POST", "/api/v1/replay/run", request)
if err != nil {
return err
}
if jsonOut {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(resp)
} else {
fmt.Printf("✅ Replay executed successfully\n")
fmt.Printf("📁 Output: %s\n", outputDir)
fmt.Printf("📊 Stats: %+v\n", resp["stats"])
}
return nil
},
}
cmd.Flags().StringVar(&replayFile, "file", "", "Replay trace file")
cmd.Flags().StringVar(&outputDir, "out", "replay-output/", "Output directory")
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output machine-readable JSON")
cmd.MarkFlagRequired("file")
return cmd
}
func replayStatusCmdNew() *cobra.Command {
var replayID string
var jsonOut bool
cmd := &cobra.Command{
Use: "status --id <replay-id>",
Short: "Get replay status",
Long: `Get the status of a running or completed replay.`,
RunE: func(cmd *cobra.Command, args []string) error {
if dryRun {
fmt.Printf("DRY RUN: Would get status for replay %s\n", replayID)
return nil
}
// Call API
resp, err := callAPI("GET", fmt.Sprintf("/api/v1/replay/status/%s", replayID), nil)
if err != nil {
return err
}
if jsonOut {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(resp)
} else {
fmt.Printf("📊 Replay Status: %s\n", replayID)
fmt.Printf("Status: %s\n", resp["status"])
fmt.Printf("Progress: %s\n", resp["progress"])
if stats, ok := resp["stats"]; ok {
fmt.Printf("Stats: %+v\n", stats)
}
}
return nil
},
}
cmd.Flags().StringVar(&replayID, "id", "", "Replay ID")
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output machine-readable JSON")
cmd.MarkFlagRequired("id")
return cmd
}
// explainStateCmd provides the Explain State REPL functionality
func explainStateCmd() *cobra.Command {
var dfaFile, event string
var jsonOut bool
cmd := &cobra.Command{
Use: "explain-state",
Short: "Explain DFA state analysis",
Long: `Interactive tool for analyzing DFA states and transitions.`,
RunE: func(cmd *cobra.Command, args []string) error {
if dfaFile == "" && event == "" {
// Launch interactive REPL
return launchExplainStateREPL()
}
if dfaFile == "" {
return fmt.Errorf("DFA file required for analysis")
}
// Load DFA
dfa, err := loadDFAFromFile(dfaFile)
if err != nil {
return fmt.Errorf("failed to load DFA: %w", err)
}
if event == "" {
return fmt.Errorf("event required for analysis")
}
// Analyze event
analysis := analyzeEvent(dfa, event)
if jsonOut {
enc := json.NewEncoder(os.Stdout)
enc.SetIndent("", " ")
_ = enc.Encode(analysis)
} else {
displayAnalysis(analysis)
}
return nil
},
}
cmd.Flags().StringVar(&dfaFile, "dfa", "", "DFA JSON file")
cmd.Flags().StringVar(&event, "event", "", "Event to analyze")
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output machine-readable JSON")
return cmd
}
// unifiedCommands provides the main unified command interface
func unifiedCommands() *cobra.Command {
cmd := &cobra.Command{
Use: "unified",
Short: "Unified command interface",
Long: `Unified commands that hide complexity behind simple interfaces.`,
}
cmd.AddCommand(unifiedPolicyCmd())
cmd.AddCommand(unifiedDeployCmd())
cmd.AddCommand(unifiedReplayCmd())
cmd.AddCommand(unifiedPacketCmd())
cmd.AddCommand(unifiedCertCmd())
return cmd
}
func unifiedPolicyCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "policy",
Short: "Unified policy operations",
Long: `Simplified policy operations that hide complexity.`,
}
cmd.AddCommand(unifiedPolicyCompileCmd())
cmd.AddCommand(unifiedPolicyProveCmd())
return cmd
}
func unifiedPolicyCompileCmd() *cobra.Command {
var inputFile string
var jsonOut bool
cmd := &cobra.Command{
Use: "compile [input-file]",
Short: "Compile policy with automatic output management",
Long: `Compile policy with smart defaults and automatic output directory management.`,
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
inputFile = args[0]
}
if inputFile == "" {
inputFile = "policy.md" // Default
}
// Smart output directory
outputDir := fmt.Sprintf("build/%s", strings.TrimSuffix(filepath.Base(inputFile), filepath.Ext(inputFile)))
// Use existing policy compile logic
policyCompileCmd := policyCompileCmd()
policyCompileCmd.SetArgs([]string{
"--in", inputFile,