-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathsecurity_cmd.go
More file actions
2098 lines (1827 loc) · 61.3 KB
/
Copy pathsecurity_cmd.go
File metadata and controls
2098 lines (1827 loc) · 61.3 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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/spf13/cobra"
"go.uber.org/zap"
"golang.org/x/term"
clioutput "github.com/smart-mcp-proxy/mcpproxy-go/internal/cli/output"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/cliclient"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/config"
"github.com/smart-mcp-proxy/mcpproxy-go/internal/socket"
)
var (
// security scan flags
secScanAsync bool
secScanDryRun bool
secScanners string
secScanAll bool
// security approve flags
secApproveForce bool
// security configure flags
secConfigEnv []string
)
// GetSecurityCommand returns the security parent command.
func GetSecurityCommand() *cobra.Command {
securityCmd := &cobra.Command{
Use: "security",
Short: "Security scanner management and server scanning",
Long: `Commands for managing security scanners, scanning MCP servers,
and reviewing scan results.
Security scanners run as Docker containers and analyze upstream MCP servers
for vulnerabilities, tool poisoning attacks, and other security issues.
Examples:
mcpproxy security scanners
mcpproxy security enable mcp-scan
mcpproxy security disable mcp-scan
mcpproxy security scan github-server
mcpproxy security report github-server
mcpproxy security overview`,
}
securityCmd.AddCommand(newSecurityScannersCmd())
securityCmd.AddCommand(newSecurityEnableCmd())
securityCmd.AddCommand(newSecurityDisableCmd())
// Keep old names as hidden aliases for backwards compatibility
securityCmd.AddCommand(newSecurityInstallCmd())
securityCmd.AddCommand(newSecurityRemoveCmd())
securityCmd.AddCommand(newSecurityConfigureCmd())
securityCmd.AddCommand(newSecurityScanCmd())
securityCmd.AddCommand(newSecurityStatusCmd())
securityCmd.AddCommand(newSecurityReportCmd())
securityCmd.AddCommand(newSecurityApproveCmd())
securityCmd.AddCommand(newSecurityRejectCmd())
securityCmd.AddCommand(newSecurityRescanCmd())
securityCmd.AddCommand(newSecurityOverviewCmd())
securityCmd.AddCommand(newSecurityIntegrityCmd())
securityCmd.AddCommand(newSecurityCancelAllCmd())
return securityCmd
}
// newSecurityCLIClient creates a cliclient.Client connected to the running MCPProxy.
//
// Honors the package-level --config and --data-dir flags from main.go so that
// `mcpproxy security ...` commands behave consistently with `mcpproxy serve`,
// `mcpproxy status`, and `mcpproxy upstream ...`.
func newSecurityCLIClient() (*cliclient.Client, *config.Config, error) {
var (
cfg *config.Config
err error
)
if configFile != "" {
cfg, err = config.LoadFromFile(configFile)
} else {
cfg, err = config.Load()
}
if err != nil {
return nil, nil, fmt.Errorf("failed to load config: %w", err)
}
if dataDir != "" {
cfg.DataDir = dataDir
}
cfg.EnsureAPIKey()
socketPath := socket.DetectSocketPath(cfg.DataDir)
logger, _ := zap.NewProduction()
defer func() { _ = logger.Sync() }()
var client *cliclient.Client
if socket.IsSocketAvailable(socketPath) {
client = cliclient.NewClient(socketPath, logger.Sugar())
} else {
endpoint := fmt.Sprintf("http://%s", cfg.Listen)
client = cliclient.NewClientWithAPIKey(endpoint, cfg.APIKey, logger.Sugar())
}
return client, cfg, nil
}
// --- Subcommand constructors ---
func newSecurityScannersCmd() *cobra.Command {
return &cobra.Command{
Use: "scanners",
Short: "List available and installed scanners",
Long: `List all security scanners from the registry and their current status.
Examples:
mcpproxy security scanners
mcpproxy security scanners -o json`,
RunE: runSecurityScanners,
}
}
func newSecurityEnableCmd() *cobra.Command {
return &cobra.Command{
Use: "enable <scanner-id>",
Short: "Enable a security scanner",
Long: `Enable a security scanner by pulling its Docker image.
Examples:
mcpproxy security enable mcp-scan
mcpproxy security enable cisco-mcp-scanner`,
Args: cobra.ExactArgs(1),
RunE: runSecurityInstall,
}
}
func newSecurityDisableCmd() *cobra.Command {
return &cobra.Command{
Use: "disable <scanner-id>",
Short: "Disable a security scanner",
Long: `Disable a security scanner and clean up its Docker image.
Examples:
mcpproxy security disable mcp-scan`,
Args: cobra.ExactArgs(1),
RunE: runSecurityRemove,
}
}
func newSecurityInstallCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "install <scanner-id>",
Short: "Install a security scanner (alias for enable)",
Hidden: true,
Args: cobra.ExactArgs(1),
RunE: runSecurityInstall,
}
return cmd
}
func newSecurityRemoveCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "remove <scanner-id>",
Short: "Remove an installed scanner (alias for disable)",
Hidden: true,
Args: cobra.ExactArgs(1),
RunE: runSecurityRemove,
}
return cmd
}
func newSecurityConfigureCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "configure <scanner-id>",
Short: "Configure scanner environment variables",
Long: `Set API keys and other environment variables for a scanner.
Use --env KEY=VALUE (repeatable) to set one or more environment variables.
Examples:
mcpproxy security configure mcp-scan --env OPENAI_API_KEY=sk-xxx
mcpproxy security configure cisco-mcp-scanner --env API_KEY=xxx --env API_SECRET=yyy`,
Args: cobra.ExactArgs(1),
RunE: runSecurityConfigure,
}
cmd.Flags().StringArrayVar(&secConfigEnv, "env", nil, "Environment variable in KEY=VALUE format (repeatable)")
_ = cmd.MarkFlagRequired("env")
return cmd
}
func newSecurityScanCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "scan [server]",
Short: "Scan a server with security scanners",
Long: `Start a security scan on an upstream MCP server.
By default, blocks until the scan completes and shows a summary.
Use --async to start the scan and return immediately.
Use --all to scan all servers at once with a progress table.
Examples:
mcpproxy security scan github-server
mcpproxy security scan github-server --async
mcpproxy security scan github-server --dry-run
mcpproxy security scan github-server --scanners mcp-scan,cisco-mcp-scanner
mcpproxy security scan --all
mcpproxy security scan --all --scanners mcp-scan`,
Args: cobra.MaximumNArgs(1),
RunE: runSecurityScan,
}
cmd.Flags().BoolVar(&secScanAll, "all", false, "Scan all servers (shows progress table)")
cmd.Flags().BoolVar(&secScanAsync, "async", false, "Start scan and return immediately without waiting")
cmd.Flags().BoolVar(&secScanDryRun, "dry-run", false, "Simulate scan without executing")
cmd.Flags().StringVar(&secScanners, "scanners", "", "Comma-separated scanner IDs to use (default: all installed)")
return cmd
}
func newSecurityStatusCmd() *cobra.Command {
return &cobra.Command{
Use: "status <server>",
Short: "Show current scan status for a server",
Long: `Display the current or most recent scan status for a server.
Examples:
mcpproxy security status github-server
mcpproxy security status github-server -o json`,
Args: cobra.ExactArgs(1),
RunE: runSecurityStatus,
}
}
func newSecurityReportCmd() *cobra.Command {
return &cobra.Command{
Use: "report <server>",
Short: "View the latest scan report for a server",
Long: `Display the latest security scan report for a server.
Supports multiple output formats:
-o table Human-readable summary (default)
-o json Full JSON report
-o yaml Full YAML report
-o sarif Raw SARIF output from scanners
Examples:
mcpproxy security report github-server
mcpproxy security report github-server -o json
mcpproxy security report github-server -o sarif`,
Args: cobra.ExactArgs(1),
RunE: runSecurityReport,
}
}
func newSecurityApproveCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "approve <server>",
Short: "Approve a server after security scan",
Long: `Approve a server's security posture based on scan results.
Use --force to approve even if findings exist.
Examples:
mcpproxy security approve github-server
mcpproxy security approve github-server --force`,
Args: cobra.ExactArgs(1),
RunE: runSecurityApprove,
}
cmd.Flags().BoolVar(&secApproveForce, "force", false, "Force approval even with findings")
return cmd
}
func newSecurityRejectCmd() *cobra.Command {
return &cobra.Command{
Use: "reject <server>",
Short: "Reject a server and quarantine it",
Long: `Reject a server's security posture and quarantine it.
Examples:
mcpproxy security reject github-server`,
Args: cobra.ExactArgs(1),
RunE: runSecurityReject,
}
}
func newSecurityRescanCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "rescan <server>",
Short: "Re-run security scanners on a server",
Long: `Re-run all installed security scanners on a server.
This is equivalent to running 'security scan' again.
Examples:
mcpproxy security rescan github-server
mcpproxy security rescan github-server --async`,
Args: cobra.ExactArgs(1),
RunE: runSecurityScan, // Reuses scan logic
}
cmd.Flags().BoolVar(&secScanAsync, "async", false, "Start scan and return immediately without waiting")
cmd.Flags().BoolVar(&secScanDryRun, "dry-run", false, "Simulate scan without executing")
cmd.Flags().StringVar(&secScanners, "scanners", "", "Comma-separated scanner IDs to use (default: all installed)")
return cmd
}
func newSecurityOverviewCmd() *cobra.Command {
return &cobra.Command{
Use: "overview",
Short: "Show security dashboard summary",
Long: `Display an aggregate security overview including scanner counts,
scan statistics, and finding summaries.
Examples:
mcpproxy security overview
mcpproxy security overview -o json`,
RunE: runSecurityOverview,
}
}
func newSecurityIntegrityCmd() *cobra.Command {
return &cobra.Command{
Use: "integrity <server>",
Short: "Check runtime integrity of a server",
Long: `Verify the runtime integrity of a server against its approved baseline.
Checks for changes to tool descriptions, Docker images, and source hashes.
Examples:
mcpproxy security integrity github-server
mcpproxy security integrity github-server -o json`,
Args: cobra.ExactArgs(1),
RunE: runSecurityIntegrity,
}
}
// --- Command implementations ---
func runSecurityScanners(_ *cobra.Command, _ []string) error {
client, _, err := newSecurityCLIClient()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
resp, err := client.DoRaw(ctx, http.MethodGet, "/api/v1/security/scanners", nil)
if err != nil {
return fmt.Errorf("failed to list scanners: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return parseAPIError(respBody, resp.StatusCode, "list scanners")
}
var scanners []map[string]interface{}
respBody, err = unwrapAPIResponse(respBody)
if err != nil {
return fmt.Errorf("API error: %w", err)
}
if err := json.Unmarshal(respBody, &scanners); err != nil {
return fmt.Errorf("failed to parse response: %w", err)
}
format := ResolveOutputFormat()
if format == "json" || format == "yaml" {
return formatAndPrint(format, scanners)
}
if len(scanners) == 0 {
fmt.Println("No security scanners available.")
return nil
}
// Table format
fmt.Printf("%-20s %-22s %-22s %-12s %-s\n",
"ID", "NAME", "VENDOR", "STATUS", "INPUTS")
fmt.Println(strings.Repeat("-", 95))
for _, sc := range scanners {
id := getMapString(sc, "id")
name := getMapString(sc, "name")
vendor := getMapString(sc, "vendor")
rawStatus := getMapString(sc, "status")
status := scannerDisplayStatus(rawStatus)
colorOpen, colorReset := scannerStatusColor(rawStatus)
inputs := secJoinSlice(sc, "inputs")
// Pad status BEFORE applying color so column alignment isn't broken
// by invisible escape sequences.
paddedStatus := fmt.Sprintf("%-12s", status)
if colorOpen != "" {
paddedStatus = colorOpen + paddedStatus + colorReset
}
fmt.Printf("%-20s %-22s %-22s %s %-s\n",
secTruncate(id, 20),
secTruncate(name, 22),
secTruncate(vendor, 22),
paddedStatus,
inputs)
}
return nil
}
func runSecurityInstall(_ *cobra.Command, args []string) error {
client, _, err := newSecurityCLIClient()
if err != nil {
return err
}
scannerID := args[0]
fmt.Printf("Enabling scanner %q...\n", scannerID)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
resp, err := client.DoRaw(ctx, http.MethodPost, "/api/v1/security/scanners/"+scannerID+"/enable", nil)
if err != nil {
return fmt.Errorf("failed to enable scanner: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode != http.StatusOK {
return parseAPIError(respBody, resp.StatusCode, "install scanner")
}
format := ResolveOutputFormat()
if format == "json" || format == "yaml" {
return formatAndPrintRaw(format, respBody)
}
fmt.Printf("Scanner %q enabled successfully.\n", scannerID)
return nil
}
func runSecurityRemove(_ *cobra.Command, args []string) error {
client, _, err := newSecurityCLIClient()
if err != nil {
return err
}
scannerID := args[0]
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
resp, err := client.DoRaw(ctx, http.MethodPost, "/api/v1/security/scanners/"+scannerID+"/disable", nil)
if err != nil {
return fmt.Errorf("failed to disable scanner: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("scanner %q not found", scannerID)
}
if resp.StatusCode != http.StatusOK {
return parseAPIError(respBody, resp.StatusCode, "remove scanner")
}
format := ResolveOutputFormat()
if format == "json" || format == "yaml" {
return formatAndPrintRaw(format, respBody)
}
fmt.Printf("Scanner %q disabled successfully.\n", scannerID)
return nil
}
func runSecurityConfigure(_ *cobra.Command, args []string) error {
client, _, err := newSecurityCLIClient()
if err != nil {
return err
}
scannerID := args[0]
// Parse --env KEY=VALUE flags
envMap := make(map[string]string)
for _, e := range secConfigEnv {
parts := strings.SplitN(e, "=", 2)
if len(parts) != 2 || parts[0] == "" {
return fmt.Errorf("invalid env format %q, expected KEY=VALUE", e)
}
envMap[parts[0]] = parts[1]
}
body, err := json.Marshal(map[string]interface{}{"env": envMap})
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}
// F-15: bumped from 10s -> 60s. Configure can be slow when the scanner
// engine validates credentials against an upstream provider.
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
// F-15: client-side prefetch — confirm the scanner exists before issuing
// the (potentially slow) PUT, so a typo'd id fails fast with a 404 instead
// of hanging the user for 60s.
if err := securityVerifyScannerExists(ctx, client, scannerID); err != nil {
return err
}
resp, err := client.DoRaw(ctx, http.MethodPut, "/api/v1/security/scanners/"+scannerID+"/config", body)
if err != nil {
return fmt.Errorf("failed to configure scanner: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("scanner %q not found", scannerID)
}
if resp.StatusCode != http.StatusOK {
return parseAPIError(respBody, resp.StatusCode, "configure scanner")
}
format := ResolveOutputFormat()
if format == "json" || format == "yaml" {
return formatAndPrintRaw(format, respBody)
}
fmt.Printf("Scanner %q configured with %d environment variable(s).\n", scannerID, len(envMap))
return nil
}
// securityVerifyScannerExists pings the scanner status endpoint and returns
// a friendly "not found" error before the caller commits to a slower request.
func securityVerifyScannerExists(ctx context.Context, client *cliclient.Client, scannerID string) error {
statusCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
resp, err := client.DoRaw(statusCtx, http.MethodGet, "/api/v1/security/scanners/"+scannerID, nil)
if err != nil {
// Network error: don't block — let the real call surface the issue.
return nil
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return fmt.Errorf("scanner %q not found", scannerID)
}
return nil
}
func runSecurityScan(_ *cobra.Command, args []string) error {
// Handle --all flag
if secScanAll {
return runSecurityScanAll()
}
// Single server mode requires exactly one argument
if len(args) < 1 {
return fmt.Errorf("server name is required (or use --all to scan all servers)")
}
client, cfg, err := newSecurityCLIClient()
if err != nil {
return err
}
serverName := args[0]
// F-06: --dry-run never starts a real scan. Instead, fetch the scanner
// inventory + (best-effort) the server's last scan context, and print a
// human-readable plan describing what *would* run. We still exit 0 so
// the dry-run is scriptable.
if secScanDryRun {
return printScanDryRunPlan(client, serverName, secScanners)
}
// Build request body
reqBody := map[string]interface{}{
"dry_run": secScanDryRun,
}
if secScanners != "" {
reqBody["scanner_ids"] = splitAndTrim(secScanners)
}
body, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}
// Compute a sane hard timeout for the whole scan operation:
// per-scanner-timeout * scanner_count + 30s margin, capped at 30 min
// (or default to 15 min if we can't infer it).
hardTimeout := computeScanHardTimeout(cfg, secScanners)
ctx, cancel := context.WithTimeout(context.Background(), hardTimeout)
defer cancel()
resp, err := client.DoRaw(ctx, http.MethodPost, "/api/v1/servers/"+serverName+"/scan", body)
if err != nil {
return fmt.Errorf("failed to start scan: %w", err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("failed to read response: %w", err)
}
// Check for disabled server (500 with specific message)
if resp.StatusCode == http.StatusInternalServerError {
errMsg := extractAPIErrorMsg(respBody)
if strings.Contains(strings.ToLower(errMsg), "disabled") || strings.Contains(strings.ToLower(errMsg), "not enabled") {
fmt.Fprintf(os.Stderr, "Error: Server %q is disabled. Enable it first or quarantine and scan:\n", serverName)
fmt.Fprintf(os.Stderr, " mcpproxy upstream enable %s\n", serverName)
fmt.Fprintf(os.Stderr, " mcpproxy security scan %s\n", serverName)
return fmt.Errorf("server %q is disabled", serverName)
}
}
if resp.StatusCode != http.StatusAccepted && resp.StatusCode != http.StatusOK {
return parseAPIError(respBody, resp.StatusCode, "start scan")
}
var job map[string]interface{}
respBody, err = unwrapAPIResponse(respBody)
if err != nil {
return fmt.Errorf("API error: %w", err)
}
if err := json.Unmarshal(respBody, &job); err != nil {
return fmt.Errorf("failed to parse response: %w", err)
}
jobID := getMapString(job, "id")
// If --async, return immediately with the job ID
if secScanAsync {
format := ResolveOutputFormat()
if format == "json" || format == "yaml" {
return formatAndPrint(format, job)
}
fmt.Printf("Scan started for %q (job: %s)\n", serverName, jobID)
fmt.Println("Use 'mcpproxy security status " + serverName + "' to check progress.")
return nil
}
// Synchronous mode: poll until done.
//
// F-05 fixes:
// 1. Unwrap the API envelope (`{success,data}`) before reading status —
// the previous loop read `status` from the envelope and never saw
// "completed", causing infinite spin.
// 2. Use a 750ms ticker (no tight loop, no 2s lag).
// 3. Honor a hard timeout based on the configured per-scanner timeout.
// 4. Print one progress line per tick with run/running/failed counts.
fmt.Printf("Scanning %q (timeout %s, job %s)...\n", serverName, hardTimeout, jobID)
scanStart := time.Now()
ticker := time.NewTicker(750 * time.Millisecond)
defer ticker.Stop()
var lastProgressLen int
for {
select {
case <-ctx.Done():
fmt.Println()
return fmt.Errorf("scan timed out after %s for %q (job %s); use 'mcpproxy security status %s' to inspect", hardTimeout, serverName, jobID, serverName)
case <-ticker.C:
}
statusResp, err := client.DoRaw(ctx, http.MethodGet, "/api/v1/servers/"+serverName+"/scan/status", nil)
if err != nil {
return fmt.Errorf("failed to check scan status: %w", err)
}
statusBody, err := io.ReadAll(statusResp.Body)
statusResp.Body.Close()
if err != nil {
return fmt.Errorf("failed to read status response: %w", err)
}
if statusResp.StatusCode != http.StatusOK {
return parseAPIError(statusBody, statusResp.StatusCode, "check scan status")
}
// CRITICAL: unwrap the API envelope. The previous implementation
// read job fields directly from the envelope and never observed
// the "completed" terminal state.
statusBody, err = unwrapAPIResponse(statusBody)
if err != nil {
return fmt.Errorf("API error: %w", err)
}
var status map[string]interface{}
if err := json.Unmarshal(statusBody, &status); err != nil {
return fmt.Errorf("failed to parse status response: %w", err)
}
jobStatus := getMapString(status, "status")
elapsed := time.Since(scanStart).Truncate(time.Second)
// Aggregate per-scanner counts so the user sees forward progress.
var run, running, failed, total int
var runningNames []string
if scannerStatuses, ok := status["scanner_statuses"].([]interface{}); ok {
total = len(scannerStatuses)
for _, s := range scannerStatuses {
ss, ok := s.(map[string]interface{})
if !ok {
continue
}
switch getMapString(ss, "status") {
case "completed":
run++
case "failed":
failed++
case "running":
running++
if name := getMapString(ss, "scanner_id"); name != "" {
runningNames = append(runningNames, name)
}
}
}
}
progress := fmt.Sprintf(" [%s] %d run, %d running, %d failed of %d", elapsed, run, running, failed, total)
if len(runningNames) > 0 {
progress += fmt.Sprintf(" (running: %s)", strings.Join(runningNames, ", "))
}
// Erase previous line on TTY for a clean rolling display; on a pipe
// just print one progress line per tick.
if stdoutIsTTY() {
pad := ""
if lastProgressLen > len(progress) {
pad = strings.Repeat(" ", lastProgressLen-len(progress))
}
fmt.Print("\r" + progress + pad)
lastProgressLen = len(progress)
} else {
fmt.Println(progress)
}
switch jobStatus {
case "completed":
if stdoutIsTTY() {
fmt.Println()
}
fmt.Printf(" Scan completed in %s\n", elapsed)
return printScanSummary(client, ctx, serverName)
case "failed":
if stdoutIsTTY() {
fmt.Println()
}
fmt.Printf(" Scan failed after %s\n", elapsed)
errMsg := getMapString(status, "error")
if errMsg != "" {
return fmt.Errorf("scan failed: %s", errMsg)
}
return fmt.Errorf("scan failed for %q", serverName)
case "cancelled":
if stdoutIsTTY() {
fmt.Println()
}
fmt.Printf(" Scan cancelled after %s\n", elapsed)
return fmt.Errorf("scan was cancelled for %q", serverName)
}
// pending or running: continue polling
}
}
// computeScanHardTimeout returns a sensible upper bound for a scan operation:
//
// per_scanner_timeout * num_scanners + 30s margin, capped at 30 minutes.
//
// If the config does not specify a per-scanner timeout, falls back to 15 min.
func computeScanHardTimeout(cfg *config.Config, scannerFlag string) time.Duration {
const fallback = 15 * time.Minute
const cap = 30 * time.Minute
if cfg == nil || cfg.Security == nil || time.Duration(cfg.Security.ScanTimeoutDefault) <= 0 {
return fallback
}
per := time.Duration(cfg.Security.ScanTimeoutDefault)
count := 0
if scannerFlag != "" {
count = len(splitAndTrim(scannerFlag))
}
if count <= 0 {
// We don't know how many scanners are installed; assume up to 8.
count = 8
}
total := per*time.Duration(count) + 30*time.Second
if total > cap {
return cap
}
if total < fallback {
return fallback
}
return total
}
// printScanDryRunPlan implements the F-06 frontend dry-run: instead of asking
// the engine to "simulate" a scan (which today still launches containers),
// fetch the scanner inventory and the server's last scan context, then print
// a plan describing what *would* execute.
func printScanDryRunPlan(client *cliclient.Client, serverName, scannerFlag string) error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
// 1. Fetch all scanners so we can show docker images / commands.
scanResp, err := client.DoRaw(ctx, http.MethodGet, "/api/v1/security/scanners", nil)
if err != nil {
return fmt.Errorf("failed to list scanners: %w", err)
}
scanRaw, err := io.ReadAll(scanResp.Body)
scanResp.Body.Close()
if err != nil {
return fmt.Errorf("failed to read scanners response: %w", err)
}
if scanResp.StatusCode != http.StatusOK {
return parseAPIError(scanRaw, scanResp.StatusCode, "list scanners")
}
scanRaw, err = unwrapAPIResponse(scanRaw)
if err != nil {
return fmt.Errorf("API error: %w", err)
}
var allScanners []map[string]interface{}
if err := json.Unmarshal(scanRaw, &allScanners); err != nil {
return fmt.Errorf("failed to parse scanners response: %w", err)
}
// 2. Filter scanners: explicit --scanners flag wins, otherwise pick the
// ones that are configured/installed (i.e. the engine would run them).
var selected []map[string]interface{}
if scannerFlag != "" {
wanted := make(map[string]bool)
for _, id := range splitAndTrim(scannerFlag) {
wanted[id] = true
}
for _, sc := range allScanners {
if wanted[getMapString(sc, "id")] {
selected = append(selected, sc)
}
}
} else {
for _, sc := range allScanners {
st := getMapString(sc, "status")
if st == "installed" || st == "configured" {
selected = append(selected, sc)
}
}
}
// 3. Best-effort: fetch the server's last scan context for source info.
// This may 404 if the server has never been scanned — that's fine.
var scanContext map[string]interface{}
filesResp, err := client.DoRaw(ctx, http.MethodGet, "/api/v1/servers/"+serverName+"/scan/files", nil)
if err == nil {
filesRaw, _ := io.ReadAll(filesResp.Body)
filesResp.Body.Close()
if filesResp.StatusCode == http.StatusOK {
if unwrapped, uerr := unwrapAPIResponse(filesRaw); uerr == nil {
_ = json.Unmarshal(unwrapped, &scanContext)
}
}
}
format := ResolveOutputFormat()
plan := map[string]interface{}{
"server": serverName,
"dry_run": true,
"scanners": selected,
}
if scanContext != nil {
plan["source"] = map[string]interface{}{
"method": getMapString(scanContext, "source_method"),
"path": getMapString(scanContext, "source_path"),
"docker_isolation": scanContext["docker_isolation"],
"total_files": scanContext["total_files"],
}
}
if format == "json" || format == "yaml" {
return formatAndPrint(format, plan)
}
// Human-readable plan
fmt.Printf("Dry-run plan for %q\n", serverName)
fmt.Println(strings.Repeat("-", 60))
if scanContext != nil {
fmt.Println("Source (from last scan):")
fmt.Printf(" Method: %s\n", getMapString(scanContext, "source_method"))
fmt.Printf(" Path: %s\n", getMapString(scanContext, "source_path"))
if di, ok := scanContext["docker_isolation"].(bool); ok {
fmt.Printf(" Docker isolation: %t\n", di)
}
if tf, ok := scanContext["total_files"].(float64); ok {
fmt.Printf(" Files (last): %d\n", int(tf))
}
} else {
fmt.Println("Source: (no prior scan context — source will be resolved at scan time)")
}
fmt.Println()
if len(selected) == 0 {
fmt.Println("No scanners would run.")
if scannerFlag != "" {
fmt.Println("(no scanners matched --scanners filter)")
} else {
fmt.Println("(no scanners are installed/configured — run `mcpproxy security enable <id>`)")
}
return nil
}
fmt.Printf("Scanners that would run (%d):\n", len(selected))
for _, sc := range selected {
id := getMapString(sc, "id")
name := getMapString(sc, "name")
status := getMapString(sc, "status")
image := getMapString(sc, "docker_image")
if override := getMapString(sc, "image_override"); override != "" {
image = override
}
timeout := getMapString(sc, "timeout")
fmt.Printf(" - %s (%s) [%s]\n", id, name, status)
if image != "" {
fmt.Printf(" image: %s\n", image)
}
if timeout != "" {
fmt.Printf(" timeout: %s\n", timeout)
}
if cmd, ok := sc["command"].([]interface{}); ok && len(cmd) > 0 {
parts := make([]string, len(cmd))
for i, p := range cmd {
parts[i] = fmt.Sprintf("%v", p)
}
fmt.Printf(" command: %s\n", strings.Join(parts, " "))
}
if inputs, ok := sc["inputs"].([]interface{}); ok && len(inputs) > 0 {
parts := make([]string, len(inputs))
for i, p := range inputs {
parts[i] = fmt.Sprintf("%v", p)
}
fmt.Printf(" inputs: %s\n", strings.Join(parts, ", "))
}
}
fmt.Println()
fmt.Println("Dry-run only — no scanners executed. Re-run without --dry-run to scan.")
return nil
}
// runSecurityScanAll handles the --all flag: starts a batch scan and polls for progress.
func runSecurityScanAll() error {
client, _, err := newSecurityCLIClient()
if err != nil {
return err
}
// Build request body
reqBody := map[string]interface{}{}
if secScanners != "" {
reqBody["scanner_ids"] = splitAndTrim(secScanners)
}
body, err := json.Marshal(reqBody)
if err != nil {
return fmt.Errorf("failed to marshal request: %w", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Minute)
defer cancel()
resp, err := client.DoRaw(ctx, http.MethodPost, "/api/v1/security/scan-all", body)
if err != nil {
return fmt.Errorf("failed to start batch scan: %w", err)