ds-server-lib 6.3.2__tar.gz → 7.0.0a2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ds-server-lib
3
- Version: 6.3.2
3
+ Version: 7.0.0a2
4
4
  Summary: Server library for owasp depscan
5
5
  Author-email: Team AppThreat <cloud@appthreat.com>
6
6
  License-Expression: MIT
@@ -11,20 +11,19 @@ Classifier: Development Status :: 5 - Production/Stable
11
11
  Classifier: Intended Audience :: Developers
12
12
  Classifier: Intended Audience :: System Administrators
13
13
  Classifier: Operating System :: OS Independent
14
- Classifier: Programming Language :: Python :: 3.10
15
14
  Classifier: Programming Language :: Python :: 3.11
16
15
  Classifier: Programming Language :: Python :: 3.12
17
16
  Classifier: Programming Language :: Python :: 3.13
18
17
  Classifier: Programming Language :: Python :: 3.14
19
18
  Classifier: Topic :: Security
20
19
  Classifier: Topic :: Utilities
21
- Requires-Python: >=3.10
20
+ Requires-Python: >=3.11
22
21
  Description-Content-Type: text/markdown
23
- Requires-Dist: appthreat-vulnerability-db~=6.7.7
22
+ Requires-Dist: appthreat-vulnerability-db<8,>=7.0.6
24
23
  Requires-Dist: custom-json-diff~=2.1.6
25
24
  Requires-Dist: quart~=0.20
26
25
  Requires-Dist: rich~=15.0.0
27
- Requires-Dist: ds-analysis-lib~=6.3.2
26
+ Requires-Dist: ds-analysis-lib~=7.0.0a2
28
27
  Provides-Extra: dev
29
28
  Requires-Dist: pytest~=9.2.0; extra == "dev"
30
29
  Requires-Dist: pytest-asyncio~=1.4.1; extra == "dev"
@@ -1,19 +1,19 @@
1
1
  [project]
2
2
  name = "ds-server-lib"
3
- version = "6.3.2"
3
+ version = "7.0.0a2"
4
4
  description = "Server library for owasp depscan"
5
5
  authors = [
6
6
  {name = "Team AppThreat", email = "cloud@appthreat.com"},
7
7
  ]
8
8
  dependencies = [
9
- "appthreat-vulnerability-db~=6.7.7",
9
+ "appthreat-vulnerability-db>=7.0.6,<8",
10
10
  "custom-json-diff~=2.1.6",
11
11
  "quart~=0.20",
12
12
  "rich~=15.0.0",
13
- "ds-analysis-lib~=6.3.2"
13
+ "ds-analysis-lib~=7.0.0a2"
14
14
  ]
15
15
 
16
- requires-python = ">=3.10"
16
+ requires-python = ">=3.11"
17
17
  readme = "README.md"
18
18
  license = "MIT"
19
19
  classifiers = [
@@ -21,7 +21,6 @@ classifiers = [
21
21
  "Intended Audience :: Developers",
22
22
  "Intended Audience :: System Administrators",
23
23
  "Operating System :: OS Independent",
24
- "Programming Language :: Python :: 3.10",
25
24
  "Programming Language :: Python :: 3.11",
26
25
  "Programming Language :: Python :: 3.12",
27
26
  "Programming Language :: Python :: 3.13",
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ds-server-lib
3
- Version: 6.3.2
3
+ Version: 7.0.0a2
4
4
  Summary: Server library for owasp depscan
5
5
  Author-email: Team AppThreat <cloud@appthreat.com>
6
6
  License-Expression: MIT
@@ -11,20 +11,19 @@ Classifier: Development Status :: 5 - Production/Stable
11
11
  Classifier: Intended Audience :: Developers
12
12
  Classifier: Intended Audience :: System Administrators
13
13
  Classifier: Operating System :: OS Independent
14
- Classifier: Programming Language :: Python :: 3.10
15
14
  Classifier: Programming Language :: Python :: 3.11
16
15
  Classifier: Programming Language :: Python :: 3.12
17
16
  Classifier: Programming Language :: Python :: 3.13
18
17
  Classifier: Programming Language :: Python :: 3.14
19
18
  Classifier: Topic :: Security
20
19
  Classifier: Topic :: Utilities
21
- Requires-Python: >=3.10
20
+ Requires-Python: >=3.11
22
21
  Description-Content-Type: text/markdown
23
- Requires-Dist: appthreat-vulnerability-db~=6.7.7
22
+ Requires-Dist: appthreat-vulnerability-db<8,>=7.0.6
24
23
  Requires-Dist: custom-json-diff~=2.1.6
25
24
  Requires-Dist: quart~=0.20
26
25
  Requires-Dist: rich~=15.0.0
27
- Requires-Dist: ds-analysis-lib~=6.3.2
26
+ Requires-Dist: ds-analysis-lib~=7.0.0a2
28
27
  Provides-Extra: dev
29
28
  Requires-Dist: pytest~=9.2.0; extra == "dev"
30
29
  Requires-Dist: pytest-asyncio~=1.4.1; extra == "dev"
@@ -1,8 +1,8 @@
1
- appthreat-vulnerability-db~=6.7.7
1
+ appthreat-vulnerability-db<8,>=7.0.6
2
2
  custom-json-diff~=2.1.6
3
3
  quart~=0.20
4
4
  rich~=15.0.0
5
- ds-analysis-lib~=6.3.2
5
+ ds-analysis-lib~=7.0.0a2
6
6
 
7
7
  [dev]
8
8
  pytest~=9.2.0
@@ -24,4 +24,10 @@ class ServerOptions:
24
24
  max_content_length: Optional[int] = 100 * 1024 * 1024 # 100MB
25
25
  # Hack
26
26
  create_bom: Optional[Callable] = None
27
+ # Scans one BOM file for a request: takes the BOM path, a reports
28
+ # directory under the server's temporary directory, the requested project
29
+ # type and the suggest/fuzzy flags, and returns the list of VDR
30
+ # vulnerability objects for the response. Injected by depscan because
31
+ # this package cannot import it.
32
+ scan_bom: Optional[Callable] = None
27
33
  custom_data_directory: Optional[str] = None
@@ -3,6 +3,7 @@ import ipaddress
3
3
  import json
4
4
  import os
5
5
  import re
6
+ import shutil
6
7
  import socket
7
8
  import sys
8
9
  import tempfile
@@ -10,11 +11,7 @@ from hmac import compare_digest
10
11
  from typing import cast
11
12
  from urllib.parse import urlparse, urlsplit
12
13
 
13
- from analysis_lib import VdrAnalysisKV
14
14
  from analysis_lib.config import SUPPORTED_BOM_PROFILES
15
- from analysis_lib.search import get_pkgs_by_scope
16
- from analysis_lib.utils import get_pkg_list
17
- from analysis_lib.vdr import VDRAnalyzer
18
15
  from custom_json_diff.lib.utils import file_write
19
16
  from quart import Quart, request
20
17
  from rich.console import Console
@@ -533,6 +530,7 @@ async def run_scan():
533
530
  params = {}
534
531
  uploaded_bom_file = await request.files
535
532
  create_bom = app.config.get("create_bom")
533
+ scan_bom = app.config.get("scan_bom")
536
534
  allow_private_urls = _is_truthy(app.config.get("ALLOW_PRIVATE_URLS"))
537
535
  max_bom_file_size = _get_config_int(
538
536
  app.config,
@@ -545,7 +543,6 @@ async def run_scan():
545
543
  path = None
546
544
  multi_project = None
547
545
  project_type = None
548
- results = []
549
546
  profile = "generic"
550
547
  deep = False
551
548
  suggest_mode = _is_truthy(q.get("suggest"))
@@ -771,16 +768,6 @@ async def run_scan():
771
768
  if logger_instance:
772
769
  logger_instance.warning("Blocked request for path: %s", bom_file_path)
773
770
  return {"error": "true", "message": PATH_NOT_ALLOWED_MESSAGE}, 403
774
- pkg_list, _ = get_pkg_list(bom_file_path)
775
- if not pkg_list:
776
- if logger_instance:
777
- logger_instance.debug("Empty package search attempted!")
778
- else:
779
- if logger_instance:
780
- logger_instance.debug("Scanning %d oss dependencies for issues", len(pkg_list))
781
- # Categorize packages by CycloneDX scope (required/optional/excluded)
782
- # so scope-based prioritization works in server mode just like the CLI.
783
- scoped_pkgs = get_pkgs_by_scope(pkg_list)
784
771
  bom_data, bom_error = _load_bom_data(bom_file_path, max_bom_file_size)
785
772
  if not bom_data:
786
773
  return (
@@ -788,30 +775,52 @@ async def run_scan():
788
775
  400,
789
776
  {"Content-Type": "application/json"},
790
777
  )
791
- options = VdrAnalysisKV(
792
- project_type,
793
- results,
794
- pkg_aliases={},
795
- purl_aliases={},
796
- suggest_mode=suggest_mode,
797
- scoped_pkgs=scoped_pkgs,
798
- no_vuln_table=True,
799
- bom_file=bom_file_path,
800
- pkg_list=pkg_list,
801
- direct_purls={},
802
- reached_purls={},
803
- console=console,
804
- logger=logger_instance,
805
- fuzzy_search=fuzzy_search,
778
+ if scan_bom is None:
779
+ # Without a scanner the server cannot look anything up, and a
780
+ # BOM returned without vulnerabilities would look clean.
781
+ if logger_instance:
782
+ logger_instance.error("The server was started without a BOM scanner.")
783
+ return (
784
+ {
785
+ "error": "true",
786
+ "message": "The server cannot scan BOM files. Check the server logs.",
787
+ },
788
+ 500,
789
+ {"Content-Type": "application/json"},
790
+ )
791
+ # The scan runs through the injected callable. Its reports go
792
+ # under the server's temporary directory and are cleaned up
793
+ # with the request's other temporary files. A scan that stops
794
+ # early raises, and a failed request must not come back
795
+ # looking like a BOM with no vulnerabilities.
796
+ scan_reports_dir = tempfile.mkdtemp(
797
+ prefix="depscan-scan-", dir=_get_server_temp_dir()
806
798
  )
807
- vdr_result = VDRAnalyzer(vdr_options=options).process()
808
- if vdr_result.success:
809
- pkg_vulnerabilities = vdr_result.pkg_vulnerabilities
810
- if pkg_vulnerabilities:
811
- bom_data["vulnerabilities"] = pkg_vulnerabilities
812
- return json.dumps(bom_data), 200, {"Content-Type": "application/json"}
813
- if bom_data:
814
- return json.dumps(bom_data), 200, {"Content-Type": "application/json"}
799
+ temp_paths.append(scan_reports_dir)
800
+ if logger_instance:
801
+ logger_instance.debug("Scanning %s", bom_file_path)
802
+ try:
803
+ vulnerabilities = scan_bom(
804
+ bom_file_path,
805
+ scan_reports_dir,
806
+ project_type,
807
+ suggest_mode=suggest_mode,
808
+ fuzzy_search=fuzzy_search,
809
+ )
810
+ except Exception as exc: # noqa: BLE001 - the request fails, not the server
811
+ if logger_instance:
812
+ logger_instance.warning("Scan failed for %s: %s", bom_file_path, exc)
813
+ return (
814
+ {
815
+ "error": "true",
816
+ "message": "Unable to scan the BOM file. Check the server logs.",
817
+ },
818
+ 500,
819
+ {"Content-Type": "application/json"},
820
+ )
821
+ if vulnerabilities:
822
+ bom_data["vulnerabilities"] = vulnerabilities
823
+ return json.dumps(bom_data), 200, {"Content-Type": "application/json"}
815
824
  return (
816
825
  {
817
826
  "error": "true",
@@ -832,7 +841,11 @@ def cleanup_temp(*temp_files):
832
841
  if not candidate:
833
842
  continue
834
843
  with contextlib.suppress(FileNotFoundError, OSError, TypeError):
835
- os.remove(candidate)
844
+ if os.path.isdir(candidate):
845
+ # A scan's reports directory holds everything the scan wrote.
846
+ shutil.rmtree(candidate, ignore_errors=True)
847
+ else:
848
+ os.remove(candidate)
836
849
 
837
850
 
838
851
  def run_server(options: ServerOptions):
@@ -854,6 +867,8 @@ def run_server(options: ServerOptions):
854
867
  # Dirty hack to get access to the create_bom function
855
868
  if options.create_bom:
856
869
  app.config["create_bom"] = options.create_bom
870
+ if options.scan_bom:
871
+ app.config["scan_bom"] = options.scan_bom
857
872
  if options.custom_data_directory:
858
873
  if options.logger:
859
874
  options.logger.info(
@@ -34,6 +34,7 @@ def client():
34
34
  "MAX_BOM_FILE_SIZE",
35
35
  "TRUSTED_HOST_NAMES",
36
36
  "create_bom",
37
+ "scan_bom",
37
38
  ):
38
39
  app.config.pop(config_key, None)
39
40
  app.config["MAX_CONTENT_LENGTH"] = None
@@ -48,6 +49,32 @@ def allowed_dirs():
48
49
  yield str(safe_dir), str(sub_dir)
49
50
 
50
51
 
52
+ def inject_scanner(monkeypatch=None, vulnerabilities=None, error=None):
53
+ """Inject a BOM scanner into the app config and record its calls.
54
+
55
+ The real scanner is injected by depscan (it cannot be imported here);
56
+ the recording doubles as the positive control that a request reached it.
57
+ """
58
+ calls = []
59
+
60
+ def scan_bom(bom_file, reports_dir, project_type, *, suggest_mode=False, fuzzy_search=False):
61
+ calls.append(
62
+ {
63
+ "bom_file": bom_file,
64
+ "reports_dir": reports_dir,
65
+ "project_type": project_type,
66
+ "suggest_mode": suggest_mode,
67
+ "fuzzy_search": fuzzy_search,
68
+ }
69
+ )
70
+ if error is not None:
71
+ raise error
72
+ return list(vulnerabilities or [])
73
+
74
+ app.config["scan_bom"] = scan_bom
75
+ return calls
76
+
77
+
51
78
  @pytest.mark.asyncio
52
79
  async def test_host_allowlist_blocks_disallowed(client: QuartClient):
53
80
  app.config["ALLOWED_HOSTS"] = ["127.0.0.1"]
@@ -349,20 +376,7 @@ async def test_scan_existing_bom_path(client: QuartClient, tmp_path, monkeypatch
349
376
  ),
350
377
  encoding="utf-8",
351
378
  )
352
-
353
- class DummyAnalyzer:
354
- def __init__(self, vdr_options):
355
- self.vdr_options = vdr_options
356
-
357
- def process(self):
358
- return type(
359
- "DummyResult",
360
- (),
361
- {"success": True, "pkg_vulnerabilities": []},
362
- )()
363
-
364
- monkeypatch.setattr("server_lib.simple.get_pkg_list", lambda _: ([], None))
365
- monkeypatch.setattr("server_lib.simple.VDRAnalyzer", DummyAnalyzer)
379
+ calls = inject_scanner(monkeypatch, vulnerabilities=[])
366
380
 
367
381
  response = await client.get(
368
382
  f"/scan?type=python&path={bom_path}",
@@ -371,6 +385,7 @@ async def test_scan_existing_bom_path(client: QuartClient, tmp_path, monkeypatch
371
385
  assert response.status_code == 200
372
386
  data = await response.get_json()
373
387
  assert data["bomFormat"] == "CycloneDX"
388
+ assert calls, "the injected scanner was never called"
374
389
 
375
390
 
376
391
  @pytest.mark.asyncio
@@ -389,22 +404,9 @@ async def test_scan_existing_bom_path_with_invalid_max_content_length(
389
404
  ),
390
405
  encoding="utf-8",
391
406
  )
392
-
393
- class DummyAnalyzer:
394
- def __init__(self, vdr_options):
395
- self.vdr_options = vdr_options
396
-
397
- def process(self):
398
- return type(
399
- "DummyResult",
400
- (),
401
- {"success": True, "pkg_vulnerabilities": []},
402
- )()
407
+ calls = inject_scanner(monkeypatch, vulnerabilities=[])
403
408
 
404
409
  app.config["MAX_CONTENT_LENGTH"] = "not-an-integer"
405
- monkeypatch.setattr("server_lib.simple.get_pkg_list", lambda _: ([], None))
406
- monkeypatch.setattr("server_lib.simple.VDRAnalyzer", DummyAnalyzer)
407
-
408
410
  response = await client.get(
409
411
  f"/scan?type=python&path={bom_path}",
410
412
  headers={"X-Test-Remote-Addr": "127.0.0.1"},
@@ -412,6 +414,7 @@ async def test_scan_existing_bom_path_with_invalid_max_content_length(
412
414
  assert response.status_code == 200
413
415
  data = await response.get_json()
414
416
  assert data["bomFormat"] == "CycloneDX"
417
+ assert calls, "the injected scanner was never called"
415
418
 
416
419
 
417
420
  def _write_bom_with_components(bom_path: Path):
@@ -443,71 +446,144 @@ def _write_bom_with_components(bom_path: Path):
443
446
 
444
447
 
445
448
  @pytest.mark.asyncio
446
- async def test_scan_passes_parsed_pkg_list_to_analyzer(client: QuartClient, tmp_path, monkeypatch):
447
- """Regression test for issue #515: the parsed pkg_list must reach the VDR
448
- analyzer instead of being discarded in favor of a hardcoded empty list."""
449
+ async def test_scan_passes_the_bom_path_to_the_injected_scanner(
450
+ client: QuartClient, tmp_path, monkeypatch
451
+ ):
452
+ """The request hands the BOM it resolved to the injected scanner, which
453
+ runs depscan's own pipeline on it. (The parsing of the package list from
454
+ the BOM, which issue #515 was about, moved into that pipeline; the server
455
+ no longer parses packages itself.)"""
449
456
  bom_path = tmp_path / "sample.bom.json"
450
457
  _write_bom_with_components(bom_path)
451
458
 
452
- captured = {}
459
+ calls = inject_scanner(monkeypatch, vulnerabilities=[])
460
+
461
+ response = await client.get(
462
+ f"/scan?type=js&path={bom_path}",
463
+ headers={"X-Test-Remote-Addr": "127.0.0.1"},
464
+ )
465
+ assert response.status_code == 200
453
466
 
454
- class CapturingAnalyzer:
455
- def __init__(self, vdr_options):
456
- captured["options"] = vdr_options
467
+ assert calls, "the injected scanner was never called"
468
+ assert calls[0]["bom_file"] == str(bom_path)
469
+ assert calls[0]["project_type"] == "js"
470
+ assert calls[0]["suggest_mode"] is False
471
+ assert calls[0]["fuzzy_search"] is False
457
472
 
458
- def process(self):
459
- return type(
460
- "DummyResult",
461
- (),
462
- {"success": True, "pkg_vulnerabilities": []},
463
- )()
464
473
 
465
- monkeypatch.setattr("server_lib.simple.VDRAnalyzer", CapturingAnalyzer)
474
+ @pytest.mark.asyncio
475
+ async def test_scan_forwards_suggest_and_fuzzy_flags_to_the_scanner(
476
+ client: QuartClient, tmp_path, monkeypatch
477
+ ):
478
+ bom_path = tmp_path / "sample.bom.json"
479
+ _write_bom_with_components(bom_path)
480
+
481
+ calls = inject_scanner(monkeypatch, vulnerabilities=[])
466
482
 
467
483
  response = await client.get(
468
- f"/scan?type=js&path={bom_path}",
484
+ f"/scan?type=js&suggest=true&fuzzy_search=true&path={bom_path}",
469
485
  headers={"X-Test-Remote-Addr": "127.0.0.1"},
470
486
  )
471
487
  assert response.status_code == 200
472
-
473
- options = captured["options"]
474
- purls = [pkg.get("purl") for pkg in options.pkg_list]
475
- assert "pkg:npm/lodash@4.17.20" in purls
476
- assert "pkg:npm/axios@0.21.0" in purls
477
- assert options.scoped_pkgs == {"required": ["pkg:npm/lodash@4.17.20"]}
488
+ assert calls, "the injected scanner was never called"
489
+ assert calls[0]["suggest_mode"] is True
490
+ assert calls[0]["fuzzy_search"] is True
478
491
 
479
492
 
480
493
  @pytest.mark.asyncio
481
494
  async def test_scan_attaches_vulnerabilities_to_response(
482
495
  client: QuartClient, tmp_path, monkeypatch
483
496
  ):
484
- """When the VDR analyzer reports vulnerabilities, the /scan response BOM
485
- must carry a vulnerabilities array instead of echoing the input unchanged."""
497
+ """When the injected scanner reports vulnerabilities, the /scan response
498
+ BOM must carry a vulnerabilities array instead of echoing the input
499
+ unchanged."""
486
500
  bom_path = tmp_path / "sample.bom.json"
487
501
  _write_bom_with_components(bom_path)
488
502
 
489
503
  sample_vulns = [{"id": "CVE-2021-23337", "ratings": [{"severity": "high"}]}]
504
+ calls = inject_scanner(monkeypatch, vulnerabilities=sample_vulns)
505
+
506
+ response = await client.get(
507
+ f"/scan?type=js&path={bom_path}",
508
+ headers={"X-Test-Remote-Addr": "127.0.0.1"},
509
+ )
510
+ assert response.status_code == 200
511
+ data = await response.get_json()
512
+ assert data["vulnerabilities"] == sample_vulns
513
+ assert calls, "the injected scanner was never called"
490
514
 
491
- class ReportingAnalyzer:
492
- def __init__(self, vdr_options):
493
- self.vdr_options = vdr_options
494
515
 
495
- def process(self):
496
- return type(
497
- "DummyResult",
498
- (),
499
- {"success": True, "pkg_vulnerabilities": sample_vulns},
500
- )()
516
+ @pytest.mark.asyncio
517
+ async def test_scan_failure_returns_an_error_response(client: QuartClient, tmp_path, monkeypatch):
518
+ """A scan that stops early raises inside the injected scanner; the
519
+ request must fail instead of returning a BOM with no vulnerabilities."""
520
+ bom_path = tmp_path / "sample.bom.json"
521
+ _write_bom_with_components(bom_path)
501
522
 
502
- monkeypatch.setattr("server_lib.simple.VDRAnalyzer", ReportingAnalyzer)
523
+ calls = inject_scanner(monkeypatch, error=RuntimeError("database is unusable"))
503
524
 
504
525
  response = await client.get(
505
526
  f"/scan?type=js&path={bom_path}",
506
527
  headers={"X-Test-Remote-Addr": "127.0.0.1"},
507
528
  )
508
- assert response.status_code == 200
529
+ assert response.status_code == 500
509
530
  data = await response.get_json()
510
- assert data["vulnerabilities"] == sample_vulns
531
+ assert "Unable to scan the BOM file" in data["message"]
532
+ assert calls, "the injected scanner was never called"
533
+
534
+
535
+ @pytest.mark.asyncio
536
+ async def test_scan_reports_dir_lives_under_the_server_temp_dir_and_is_cleaned(
537
+ client: QuartClient, tmp_path
538
+ ):
539
+ bom_path = tmp_path / "sample.bom.json"
540
+ _write_bom_with_components(bom_path)
541
+
542
+ recorded = {}
543
+ original = app.config.get("scan_bom")
544
+
545
+ def scan_bom(bom_file, reports_dir, project_type, *, suggest_mode=False, fuzzy_search=False):
546
+ recorded["reports_dir"] = reports_dir
547
+ return []
548
+
549
+ app.config["scan_bom"] = scan_bom
550
+ try:
551
+ response = await client.get(
552
+ f"/scan?type=js&path={bom_path}",
553
+ headers={"X-Test-Remote-Addr": "127.0.0.1"},
554
+ )
555
+ assert response.status_code == 200
556
+ assert recorded, "the injected scanner was never called"
557
+ server_temp_dir = simple_module._get_server_temp_dir()
558
+ assert os.path.dirname(recorded["reports_dir"]) == server_temp_dir
559
+ # The request cleans the scan's reports directory up with its other
560
+ # temporary files.
561
+ assert not os.path.exists(recorded["reports_dir"])
562
+ finally:
563
+ app.config.pop("scan_bom", None)
564
+ if original is not None:
565
+ app.config["scan_bom"] = original
566
+
567
+
568
+ @pytest.mark.asyncio
569
+ async def test_scan_without_a_scanner_fails_instead_of_returning_a_clean_bom(
570
+ client: QuartClient, tmp_path
571
+ ):
572
+ bom_path = tmp_path / "sample.bom.json"
573
+ _write_bom_with_components(bom_path)
574
+ original = app.config.pop("scan_bom", None)
575
+ try:
576
+ response = await client.get(
577
+ f"/scan?type=js&path={bom_path}",
578
+ headers={"X-Test-Remote-Addr": "127.0.0.1"},
579
+ )
580
+ assert response.status_code == 500
581
+ body = await response.get_json()
582
+ assert "vulnerabilities" not in body
583
+ assert body["error"] == "true"
584
+ finally:
585
+ if original is not None:
586
+ app.config["scan_bom"] = original
511
587
 
512
588
 
513
589
  @pytest.mark.asyncio
@@ -536,23 +612,14 @@ async def test_scan_rejects_unsupported_profile(client: QuartClient, tmp_path, p
536
612
  async def test_scan_accepts_supported_profile(client: QuartClient, tmp_path, monkeypatch):
537
613
  bom_path = tmp_path / "sample.bom.json"
538
614
  _write_bom_with_components(bom_path)
539
- captured = {}
540
-
541
- class CapturingAnalyzer:
542
- def __init__(self, vdr_options):
543
- captured["options"] = vdr_options
544
-
545
- def process(self):
546
- return type("DummyResult", (), {"success": True, "pkg_vulnerabilities": []})()
547
-
548
- monkeypatch.setattr("server_lib.simple.VDRAnalyzer", CapturingAnalyzer)
615
+ calls = inject_scanner(monkeypatch, vulnerabilities=[])
549
616
 
550
617
  response = await client.get(
551
618
  f"/scan?type=js&path={bom_path}&profile=appsec",
552
619
  headers={"X-Test-Remote-Addr": "127.0.0.1"},
553
620
  )
554
621
  assert response.status_code == 200
555
- assert captured["options"] is not None
622
+ assert calls, "the injected scanner was never called"
556
623
 
557
624
 
558
625
  @pytest.mark.asyncio
@@ -640,14 +707,7 @@ async def test_uploaded_bom_is_not_blocked_by_path_allowlist(
640
707
  safe_dir.mkdir()
641
708
  app.config["ALLOWED_PATHS"] = [str(safe_dir)]
642
709
 
643
- class DummyAnalyzer:
644
- def __init__(self, vdr_options):
645
- self.vdr_options = vdr_options
646
-
647
- def process(self):
648
- return type("DummyResult", (), {"success": True, "pkg_vulnerabilities": []})()
649
-
650
- monkeypatch.setattr("server_lib.simple.VDRAnalyzer", DummyAnalyzer)
710
+ calls = inject_scanner(monkeypatch, vulnerabilities=[])
651
711
 
652
712
  payload = json.dumps(
653
713
  {"bomFormat": "CycloneDX", "specVersion": "1.5", "version": 1, "components": []}
@@ -666,6 +726,7 @@ async def test_uploaded_bom_is_not_blocked_by_path_allowlist(
666
726
  assert response.status_code == 200
667
727
  data = await response.get_json()
668
728
  assert data["bomFormat"] == "CycloneDX"
729
+ assert calls, "the injected scanner was never called"
669
730
 
670
731
 
671
732
  def test_server_temp_dir_is_private_and_reused():
@@ -695,14 +756,7 @@ async def test_uploaded_bom_is_staged_in_private_temp_dir(client: QuartClient, m
695
756
 
696
757
  monkeypatch.setattr(simple_module, "file_write", tracking_file_write)
697
758
 
698
- class DummyAnalyzer:
699
- def __init__(self, vdr_options):
700
- self.vdr_options = vdr_options
701
-
702
- def process(self):
703
- return type("DummyResult", (), {"success": True, "pkg_vulnerabilities": []})()
704
-
705
- monkeypatch.setattr("server_lib.simple.VDRAnalyzer", DummyAnalyzer)
759
+ calls = inject_scanner(monkeypatch, vulnerabilities=[])
706
760
 
707
761
  payload = json.dumps(
708
762
  {"bomFormat": "CycloneDX", "specVersion": "1.5", "version": 1, "components": []}
@@ -721,6 +775,9 @@ async def test_uploaded_bom_is_staged_in_private_temp_dir(client: QuartClient, m
721
775
  assert response.status_code == 200
722
776
  assert staged_paths
723
777
  assert os.path.dirname(staged_paths[0]) == simple_module._get_server_temp_dir()
778
+ # The staged upload is what the scanner receives.
779
+ assert calls, "the injected scanner was never called"
780
+ assert calls[0]["bom_file"] == staged_paths[0]
724
781
 
725
782
 
726
783
  @pytest.mark.asyncio
@@ -760,15 +817,8 @@ async def test_generated_bom_inside_temp_dir_is_accepted(
760
817
  json.dump({"bomFormat": "CycloneDX", "specVersion": "1.5", "components": []}, fp)
761
818
  return type("BOMStatus", (), {"success": True, "primary": bom_file})()
762
819
 
763
- class DummyAnalyzer:
764
- def __init__(self, vdr_options):
765
- self.vdr_options = vdr_options
766
-
767
- def process(self):
768
- return type("DummyResult", (), {"success": True, "pkg_vulnerabilities": []})()
769
-
770
820
  app.config["create_bom"] = create_bom
771
- monkeypatch.setattr("server_lib.simple.VDRAnalyzer", DummyAnalyzer)
821
+ calls = inject_scanner(monkeypatch, vulnerabilities=[])
772
822
 
773
823
  response = await client.get(
774
824
  f"/scan?type=js&path={project_dir}",
@@ -1155,15 +1205,8 @@ async def test_generated_bom_is_not_blocked_by_the_path_allowlist(
1155
1205
  json.dump({"bomFormat": "CycloneDX", "specVersion": "1.5", "components": []}, fp)
1156
1206
  return type("BOMStatus", (), {"success": True, "primary": bom_file})()
1157
1207
 
1158
- class DummyAnalyzer:
1159
- def __init__(self, vdr_options):
1160
- self.vdr_options = vdr_options
1161
-
1162
- def process(self):
1163
- return type("DummyResult", (), {"success": True, "pkg_vulnerabilities": []})()
1164
-
1165
1208
  app.config["create_bom"] = create_bom
1166
- monkeypatch.setattr("server_lib.simple.VDRAnalyzer", DummyAnalyzer)
1209
+ calls = inject_scanner(monkeypatch, vulnerabilities=[])
1167
1210
  response = await client.get(
1168
1211
  "/scan", query_string={"type": "js", "path": str(project_dir)}, headers=LOCAL
1169
1212
  )
@@ -1280,3 +1323,130 @@ async def test_windows_network_paths_are_refused_before_any_file_access(
1280
1323
  )
1281
1324
  assert response.status_code == 403
1282
1325
  assert checked == []
1326
+
1327
+
1328
+ # ---------------------------------------------------------------------------
1329
+ # Server requests reach golem for Go projects, with cgo off
1330
+ # ---------------------------------------------------------------------------
1331
+
1332
+
1333
+ def _wire_real_create_bom(monkeypatch, project_dir):
1334
+ """Wire the app to the real ``depscan.lib.bom.create_bom`` and stub the
1335
+ cdxgen generator so the request reaches the reachability stage without
1336
+ spawning cdxgen.
1337
+
1338
+ The real server wiring injects exactly this function (see
1339
+ ``depscan.lib.pipeline.build_context``); the stub generator writes the
1340
+ minimal BOM create_bom needs to consider the generation successful.
1341
+ """
1342
+ from depscan.lib import bom as bom_mod
1343
+
1344
+ class FakeCdxgenGenerator:
1345
+ def __init__(self, source_dir, bom_file, logger=None, options=None):
1346
+ self.bom_file = bom_file
1347
+
1348
+ def generate(self):
1349
+ with open(self.bom_file, "w", encoding="utf-8") as fp:
1350
+ json.dump(
1351
+ {
1352
+ "bomFormat": "CycloneDX",
1353
+ "specVersion": "1.6",
1354
+ "version": 1,
1355
+ "metadata": {
1356
+ "component": {
1357
+ "type": "application",
1358
+ "name": "github.com/example/app",
1359
+ "version": "v0.1.0",
1360
+ }
1361
+ },
1362
+ "components": [],
1363
+ },
1364
+ fp,
1365
+ )
1366
+ return bom_mod.BomResult(
1367
+ success=True, bom_files=[self.bom_file], primary=self.bom_file
1368
+ )
1369
+
1370
+ monkeypatch.setattr(bom_mod, "CdxgenGenerator", FakeCdxgenGenerator)
1371
+ # Without this, create_bom probes the real cdxgen CLI for its version.
1372
+ monkeypatch.setattr(bom_mod, "_refuse_old_cdxgen", lambda logger=None: True)
1373
+ app.config["create_bom"] = bom_mod.create_bom
1374
+
1375
+
1376
+ @pytest.mark.asyncio
1377
+ async def test_go_scan_request_reaches_golem_without_a_cgo_opt_in(
1378
+ client, monkeypatch, tmp_path
1379
+ ):
1380
+ """A request for a Go directory reaches run_golem through the real
1381
+ create_bom, with no cgo opt-in in the options the server builds.
1382
+
1383
+ The server assembles its options from the request alone, so nothing in
1384
+ them can carry go_analyzer_cgo; run_golem must be called with the hardened
1385
+ default. The stubbed runner fails the run (it writes no report), which the
1386
+ fallback degrades from without failing the request."""
1387
+ from xbom_lib import golem as golem_mod
1388
+
1389
+ project_dir = tmp_path / "go-project"
1390
+ project_dir.mkdir()
1391
+ _wire_real_create_bom(monkeypatch, project_dir)
1392
+ inject_scanner(monkeypatch, vulnerabilities=[])
1393
+
1394
+ calls = []
1395
+
1396
+ def fake_run_golem(src_dir, out_path, **kwargs):
1397
+ calls.append({"src_dir": src_dir, "kwargs": kwargs})
1398
+ return golem_mod.GolemResult(success=False, command_output="stubbed")
1399
+
1400
+ monkeypatch.setattr(golem_mod, "run_golem", fake_run_golem)
1401
+
1402
+ response = await client.get(
1403
+ f"/scan?type=go&path={project_dir}",
1404
+ headers={"X-Test-Remote-Addr": "127.0.0.1"},
1405
+ )
1406
+ assert response.status_code == 200
1407
+ assert len(calls) == 1, "the golem fallback was not reached for a Go request"
1408
+ assert calls[0]["src_dir"] == str(project_dir)
1409
+ # The opt-in is a CLI-level decision; the server never sets it.
1410
+ assert calls[0]["kwargs"].get("allow_cgo") is False
1411
+
1412
+
1413
+ @pytest.mark.asyncio
1414
+ async def test_go_scan_request_runs_golem_with_cgo_disabled(
1415
+ client, monkeypatch, tmp_path
1416
+ ):
1417
+ """The golem subprocess the server path ends up starting runs with
1418
+ CGO_ENABLED=0 and without the host's CGO_*_ALLOW values, even when the
1419
+ server process itself carries them."""
1420
+ from xbom_lib import golem as golem_mod
1421
+
1422
+ project_dir = tmp_path / "go-project"
1423
+ project_dir.mkdir()
1424
+ _wire_real_create_bom(monkeypatch, project_dir)
1425
+ inject_scanner(monkeypatch, vulnerabilities=[])
1426
+ monkeypatch.setenv("CGO_ENABLED", "1")
1427
+ monkeypatch.setenv("CGO_CFLAGS_ALLOW", ".*")
1428
+
1429
+ captured = {}
1430
+
1431
+ def fake_run(full_cmd, **kwargs):
1432
+ captured["env"] = kwargs.get("env", {})
1433
+ from subprocess import CompletedProcess
1434
+
1435
+ if "version" in [str(part) for part in full_cmd]:
1436
+ return CompletedProcess(
1437
+ args=full_cmd, returncode=0, stdout="go version go1.26.10 linux/amd64", stderr=""
1438
+ )
1439
+ return CompletedProcess(args=full_cmd, returncode=1, stdout="stubbed", stderr="")
1440
+
1441
+ monkeypatch.setattr(golem_mod, "find_golem_binary", lambda logger=None: "/tmp/golem")
1442
+ monkeypatch.setattr(golem_mod, "go_toolchain_available", lambda logger=None: True)
1443
+ monkeypatch.setattr(golem_mod, "get_golem_version", lambda binary, logger=None: "2.5.2")
1444
+ monkeypatch.setattr("subprocess.run", fake_run)
1445
+
1446
+ response = await client.get(
1447
+ f"/scan?type=go&path={project_dir}",
1448
+ headers={"X-Test-Remote-Addr": "127.0.0.1"},
1449
+ )
1450
+ assert response.status_code == 200
1451
+ assert captured["env"]["CGO_ENABLED"] == "0"
1452
+ assert "CGO_CFLAGS_ALLOW" not in captured["env"]
File without changes
File without changes