Skip to content

Conversation

@mscasso-scanoss
Copy link
Contributor

@mscasso-scanoss mscasso-scanoss commented Dec 23, 2025

Summary by CodeRabbit

  • New Features

    • Header-based scan settings (base64 JSON), SBOM-aware scanning, and a unified config-driven scanning flow
    • Server tuning options for ranking, snippet thresholds, and file-extension handling with sensible defaults
    • More graceful handling for invalid KB names in scanning endpoints
  • Tests

    • Unit tests for scanning configuration and E2E tests covering scan-settings header scenarios
  • Chores

    • Changelog updated, test coverage make targets added, and stricter input validation in test helpers

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link

coderabbitai bot commented Dec 23, 2025

📝 Walkthrough

Walkthrough

Adds server-side scanning tuning fields and defaults; implements a new ScanningServiceConfig with per-request overrides via a base64 JSON scanoss-scan-settings header; refactors scanning call sites to accept the config and SBOM parameters; and adds unit, integration/e2e tests and test helpers.

Changes

Cohort / File(s) Summary
Configuration schema
pkg/config/server_config.go
Added ServerConfig.Scanning fields: RankingAllowed, RankingEnabled, RankingThreshold, MinSnippetHits, MinSnippetLines, SnippetRangeTol, HonourFileExts with env tags and defaults in setServerConfigDefaults.
Scanning config type & tests
pkg/service/scanning_service_config.go, pkg/service/scanning_service_config_test.go
New ScanningServiceConfig struct plus DefaultScanningServiceConfig and UpdateScanningServiceConfigDTO to derive runtime config from server defaults, base64/JSON scanoss-scan-settings, and legacy params. Adds comprehensive unit tests for defaults, JSON updates, ranking restrictions, legacy params, invalid input, combined updates, and nil-config handling.
Scanning service refactor
pkg/service/scanning_service.go
Replaced legacy per-request parsing with getConfigFromRequest() (decodes scanoss-scan-settings); added SBOM constants; updated signatures for singleScan, scanThreaded, workerScan, scanWfp to accept ScanningServiceConfig and sbomFile; engine invocations now derive flags, dbName, SBOM, ranking and snippet options from the config.
KB details usage
pkg/service/kb_details.go
loadKBDetails now passes DefaultScanningServiceConfig(s.config) to s.scanWfp instead of an empty string.
End-to-end tests
tests/scanning_test.go
Added TestScanSettingsHeader() (valid/invalid base64 JSON and legacy flags scenarios); adjusted existing tests (invalid KB name now expects 200; assets switched to JSON PURLs).
Makefile targets
Makefile
Added unit_test_cover, int_test_cover, and e2e_test_cover targets to run tests with coverage.
CHANGELOG
CHANGELOG.md
Added [1.6.0] Unreleased entry noting scanoss.json scanning config support and new server-side scanning parameters.
Test helper script
test-support/scanoss.sh
Added MD5 validation for -k, tightened KB name handling for -n<name>, and improved -w detection.
Minor tests/header update
pkg/service/scanning_service_test.go
Updated copyright year in test header.

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant HTTP as "HTTP Server"
  participant Service as "ScanningService"
  participant Storage as "SBOM/Storage"
  participant Engine as "Scan Engine"

  Client->>HTTP: POST /scan/direct (multipart + optional header `scanoss-scan-settings`)
  HTTP->>Service: forward request + headers
  Service->>Service: DefaultScanningServiceConfig(server defaults)
  Service->>Service: getConfigFromRequest (decode base64 JSON -> UpdateScanningServiceConfigDTO)
  alt SBOM provided
    Service->>Storage: store/validate SBOM (config.sbomFile / sbomType)
    Storage-->>Service: sbomFile path
  end
  Service->>Engine: start scan(s) with ScanningServiceConfig + sbomFile
  Engine->>Engine: workerScan threads use config (flags, ranking, snippet options)
  Engine-->>Service: aggregated scan results
  Service->>HTTP: respond with results/status
  HTTP->>Client: HTTP response
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

"I nibble at JSON, base64 delight,
defaults hop in, configs take flight.
Threads hum softly, SBOMs stored neat,
rankings and snippets make scans complete.
🐇🔍"

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately reflects the main changes: adding support for new scanning parameters (ranking, snippet, and file extension options) to the Go API, which is the core objective across all modified files.
Docstring Coverage ✅ Passed Docstring coverage is 92.31% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (4)
tests/scanning_test.go (1)

136-222: Good test coverage for the new scan settings header feature.

The test covers key scenarios: valid base64-encoded settings, invalid base64 handling, and integration with legacy flags. Consider adding a test case for malformed JSON (valid base64 but invalid JSON content) to verify that the server handles this gracefully and uses defaults.

🔎 Optional: Additional test case for malformed JSON
{
    name:            "Test Invalid ScanSettings - Malformed JSON",
    filename:        "../pkg/service/tests/fingers.wfp",
    shortName:       "fingers.wfp",
    // Base64 of "{invalid json}"
    scanSettingsB64: "e2ludmFsaWQganNvbn0=",
    extraFields:     map[string]string{},
    want:            http.StatusOK,
    description:     "Should handle malformed JSON gracefully and continue with defaults",
},
pkg/service/scanning_service_config.go (2)

74-74: Address the TODO or create an issue to track it.

The TODO indicates a warning should be added when ranking settings are rejected due to RankingAllowed being false. This would improve observability for API consumers.

Would you like me to open an issue to track adding a warning log when ranking settings are rejected?


100-123: Simplify redundant empty string checks.

The conditions len(x) > 0 && x != "" are redundant since an empty string always has length 0. Either check is sufficient.

🔎 Proposed fix
-	if len(dbName) > 0 && dbName != "" {
+	if dbName != "" {
 		currentConfig.dbName = dbName
 		s.Debugf("Updated DbName to %s", currentConfig.dbName)
 	}

-	if len(flags) > 0 && flags != "" {
+	if flags != "" {
 		flagsInt, err := strconv.Atoi(flags)
 		if err != nil {
 			s.Errorf("Error converting flags to integer: %v", err)
 		} else {
 			currentConfig.flags = flagsInt
 			s.Debugf("Updated Flags to %d", currentConfig.flags)
 		}
 	}

-	if len(scanType) > 0 && scanType != "" {
+	if scanType != "" {
 		currentConfig.sbomType = scanType
 		s.Debugf("Updated SbomType to %s", currentConfig.sbomType)
 	}

-	if len(sbom) > 0 && sbom != "" {
+	if sbom != "" {
 		currentConfig.sbomFile = sbom
 		s.Debugf("Updated SbomFile to %s", currentConfig.sbomFile)
 	}
pkg/service/scanning_service.go (1)

93-95: Extract "identify" and "blacklist" as constants.

Static analysis flagged that the string "identify" appears 3 times. Extract these SBOM type strings as constants for maintainability.

🔎 Proposed fix - Add constants at package level
+const (
+	sbomTypeIdentify  = "identify"
+	sbomTypeBlacklist = "blacklist"
+)
+
 // scanDirect handles WFP scanning requests from a client.

Then update usages:

-		if scanConfig.sbomType != "identify" && scanConfig.sbomType != "blacklist" {
+		if scanConfig.sbomType != sbomTypeIdentify && scanConfig.sbomType != sbomTypeBlacklist {

...

-		case "identify":
+		case sbomTypeIdentify:
 			args = append(args, "-s")
-		case "blacklist":
+		case sbomTypeBlacklist:
 			args = append(args, "-b")
 		default:
 			args = append(args, "-s") // Default to identify

Also applies to: 414-421

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0dcc097 and 83ce843.

📒 Files selected for processing (6)
  • pkg/config/server_config.go
  • pkg/service/kb_details.go
  • pkg/service/scanning_service.go
  • pkg/service/scanning_service_config.go
  • pkg/service/scanning_service_config_test.go
  • tests/scanning_test.go
🧰 Additional context used
🧬 Code graph analysis (3)
pkg/service/kb_details.go (1)
pkg/service/scanning_service_config.go (1)
  • DefaultScanningServiceConfig (39-52)
pkg/service/scanning_service_config_test.go (2)
pkg/config/server_config.go (1)
  • ServerConfig (37-93)
pkg/service/scanning_service_config.go (3)
  • DefaultScanningServiceConfig (39-52)
  • ScanningServiceConfig (26-37)
  • UpdateScanningServiceConfigDTO (54-126)
pkg/service/scanning_service.go (2)
pkg/service/utils_service.go (1)
  • APIService (71-73)
pkg/service/scanning_service_config.go (3)
  • ScanningServiceConfig (26-37)
  • DefaultScanningServiceConfig (39-52)
  • UpdateScanningServiceConfigDTO (54-126)
🪛 GitHub Check: build
pkg/config/server_config.go

[warning] 77-77:
comment-spacings: no space between comment delimiter and comment text (revive)


[warning] 73-73:
comment-spacings: no space between comment delimiter and comment text (revive)


[warning] 131-131:
comment-spacings: no space between comment delimiter and comment text (revive)

pkg/service/scanning_service.go

[failure] 94-94:
string identify has 3 occurrences, make it a constant (goconst)


[failure] 197-197:
elseif: can replace 'else {if cond {}}' with 'else if cond {}' (gocritic)

🔇 Additional comments (13)
pkg/service/kb_details.go (1)

88-89: LGTM!

The refactor correctly uses DefaultScanningServiceConfig to create a configuration object from server defaults before passing it to scanWfp. This aligns with the new unified configuration flow introduced across the scanning service.

tests/scanning_test.go (2)

51-51: LGTM - Expected behavior change documented.

The change from http.StatusInternalServerError to http.StatusOK reflects that the engine now handles invalid KB names gracefully with a fallback, as noted in the comment.


93-101: LGTM - Assets format updated to proper JSON structure.

The assets field now uses proper JSON format with components array containing PURLs, which aligns with the expected SBOM structure.

pkg/service/scanning_service_config_test.go (5)

27-64: LGTM - Comprehensive test for default config creation.

The test properly validates that all fields from ServerConfig.Scanning are correctly mapped to ScanningServiceConfig.


66-123: LGTM - Good coverage for JSON-based settings updates.

The test validates that all JSON settings fields are correctly parsed and applied when rankingAllowed is true.


125-162: LGTM - Important test for the RankingAllowed guard.

This test verifies the critical security/business logic that ranking settings are ignored when RankingAllowed is false at the server level.


164-222: LGTM - Good coverage for legacy parameters and invalid input handling.

Tests properly validate backward compatibility with legacy string parameters and graceful error handling for invalid inputs.


224-286: LGTM - Combined update test validates precedence.

Good test ensuring both JSON settings and legacy parameters can be applied together in a single update.

pkg/service/scanning_service_config.go (2)

26-37: LGTM - Well-structured configuration type.

The ScanningServiceConfig struct cleanly encapsulates all scanning parameters with appropriate types. Using unexported fields enforces controlled access through the provided functions.


39-52: LGTM - Clean mapping from server config to service config.

DefaultScanningServiceConfig correctly initializes all fields from the server configuration, providing sensible empty defaults for sbomType and sbomFile.

pkg/service/scanning_service.go (3)

90-109: LGTM - Clean integration with new config flow.

The scan direct handler now correctly uses getConfigFromRequest to obtain configuration and accesses SBOM settings through the config object.


224-226: LGTM - Updated method signatures.

The singleScan method correctly accepts the new ScanningServiceConfig parameter and passes it through to scanWfp.


425-443: LGTM - New scan arguments are properly conditionally added.

The new ranking and snippet parameters are correctly added to the command arguments when their conditions are met. Good to log that honourFileExts is not yet implemented in the engine.

Copy link

@agustingroh agustingroh left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please, add changes to CHANGELOG.md file

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (2)
pkg/config/server_config.go (1)

131-138: Typo in comment on line 137.

The comment for MinSnippetLines says "minimum snippet hits" but should say "minimum snippet lines".

🔎 Proposed fix
-	cfg.Scanning.MinSnippetLines = 0 // Lets the engine decide on minimum snippet hits on the file total lines
+	cfg.Scanning.MinSnippetLines = 0 // Lets the engine decide on minimum snippet lines based on the file total lines
pkg/service/scanning_service.go (1)

411-414: Flag format inconsistency.

This was flagged in a previous review: the flag uses "-F %v" with a space, but other single-character flags in this file use no space (e.g., "-n%s" on line 408, "-r%d" on line 431).

🔎 Proposed fix
-		args = append(args, fmt.Sprintf("-F %v", config.flags))
+		args = append(args, fmt.Sprintf("-F%v", config.flags))
🧹 Nitpick comments (1)
pkg/service/scanning_service_config.go (1)

108-131: Simplify redundant empty string checks.

The checks len(x) > 0 && x != "" are redundant since a non-empty string always has length > 0.

🔎 Proposed fix
-	if len(dbName) > 0 && dbName != "" {
+	if dbName != "" {
 		currentConfig.dbName = dbName
 		s.Debugf("Updated DbName to %s", currentConfig.dbName)
 	}

-	if len(flags) > 0 && flags != "" {
+	if flags != "" {
 		flagsInt, err := strconv.Atoi(flags)
 		if err != nil {
 			s.Errorf("Error converting flags to integer: %v", err)
 		} else {
 			currentConfig.flags = flagsInt
 			s.Debugf("Updated Flags to %d", currentConfig.flags)
 		}
 	}

-	if len(scanType) > 0 && scanType != "" {
+	if scanType != "" {
 		currentConfig.sbomType = scanType
 		s.Debugf("Updated SbomType to %s", currentConfig.sbomType)
 	}

-	if len(sbom) > 0 && sbom != "" {
+	if sbom != "" {
 		currentConfig.sbomFile = sbom
 		s.Debugf("Updated SbomFile to %s", currentConfig.sbomFile)
 	}
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 83ce843 and b789b60.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • pkg/config/server_config.go
  • pkg/service/scanning_service.go
  • pkg/service/scanning_service_config.go
  • pkg/service/scanning_service_config_test.go
🧰 Additional context used
🧬 Code graph analysis (2)
pkg/service/scanning_service_config.go (1)
pkg/config/server_config.go (1)
  • ServerConfig (37-93)
pkg/service/scanning_service_config_test.go (2)
pkg/config/server_config.go (1)
  • ServerConfig (37-93)
pkg/service/scanning_service_config.go (3)
  • DefaultScanningServiceConfig (39-52)
  • ScanningServiceConfig (26-37)
  • UpdateScanningServiceConfigDTO (54-134)
🔇 Additional comments (11)
pkg/config/server_config.go (1)

73-80: LGTM!

The new scanning configuration fields are well-structured with appropriate environment variable tags and clear inline documentation.

pkg/service/scanning_service_config.go (3)

26-37: LGTM!

The struct encapsulates all scanning configuration fields appropriately. Using unexported fields enforces controlled access through the provided functions.


39-52: LGTM!

The default config factory correctly maps all server configuration fields to the service config.


54-73: Consider whether early return on JSON error is the desired behavior.

When JSON unmarshalling fails, the function logs an error and returns the original config unchanged. This silently ignores potentially malformed input. Consider whether returning an error or setting a flag to indicate partial configuration would be more appropriate for debugging/observability.

pkg/service/scanning_service_config_test.go (3)

27-64: LGTM!

Comprehensive test for default config creation, validating all fields are correctly mapped from server config.


125-162: LGTM!

Good test ensuring the RankingAllowed guard prevents ranking settings from being modified when not allowed.


197-222: LGTM!

Important error handling tests that verify the config remains unchanged when given invalid input.

pkg/service/scanning_service.go (4)

40-43: LGTM!

Good practice defining constants for SBOM types to avoid magic strings.


95-114: LGTM!

Clean integration of the new config-based approach for SBOM validation and file handling.


164-209: LGTM!

Well-structured function that consolidates config extraction from form values, headers, and base64-encoded settings. The else-if style issue from previous review has been addressed.


429-447: LGTM!

Good handling of the new scanning parameters. The honourFileExts logging with a note about engine support is a pragmatic approach for future-proofing.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
pkg/service/scanning_service.go (1)

411-414: Fix flag formatting inconsistency.

The flag formatting uses fmt.Sprintf("-F %v", config.flags) with a space, but other single-character flags in the same function consistently use no space: -n%s (line 408) and -r%d (line 431). Change to -F%v to maintain consistency.

🔎 Proposed fix
 	// Scanning flags
 	if config.flags > 0 {
-		args = append(args, fmt.Sprintf("-F %v", config.flags))
+		args = append(args, fmt.Sprintf("-F%v", config.flags))
 	}
🧹 Nitpick comments (1)
pkg/service/scanning_service_config.go (1)

54-134: Consider simplifying the parameter/return pattern.

The function takes a pointer parameter, modifies it in-place, and then returns the dereferenced value. Since callers use the return value (line 208 in scanning_service.go), the pointer modification is redundant. Consider either:

  • Taking the config by value and returning the modified value (no pointer needed), OR
  • Modifying the pointer and returning nothing (void)

The current pattern works but may confuse future maintainers about whether to use the modified pointer or the returned value.

🔎 Proposed refactor (pass by value)
-func UpdateScanningServiceConfigDTO(s *zap.SugaredLogger, currentConfig *ScanningServiceConfig,
+func UpdateScanningServiceConfigDTO(s *zap.SugaredLogger, currentConfig ScanningServiceConfig,
 	flags, scanType, sbom, dbName string, inputSettings []byte) ScanningServiceConfig {
 	// ScanSettings represents the scanning parameters that can be configured
 	type scanSettings struct {
 		RankingEnabled   *bool `json:"ranking_enabled,omitempty"`
 		RankingThreshold *int  `json:"ranking_threshold,omitempty"`
 		MinSnippetHits   *int  `json:"min_snippet_hits,omitempty"`
 		MinSnippetLines  *int  `json:"min_snippet_lines,omitempty"`
 		HonourFileExts   *bool `json:"honour_file_exts,omitempty"`
 	}
 
 	// Parse scan settings from JSON if provided
 	var newSettings scanSettings
 	if len(inputSettings) > 0 {
 		err := json.Unmarshal(inputSettings, &newSettings)
 		if err != nil {
 			s.Errorf("Error unmarshalling scanning service config input: %v", err)
-			return *currentConfig
+			return currentConfig
 		}
 	}
 
 	if newSettings.RankingEnabled != nil {
 		if currentConfig.rankingAllowed {
 			currentConfig.rankingEnabled = *newSettings.RankingEnabled
 			s.Debugf("Updated RankingEnabled to %v", currentConfig.rankingEnabled)
 		} else {
 			s.Warnf("RankingEnabled setting ignored as RankingAllowed is false")
 		}
 	}
 
 	// ... rest of the function remains the same ...
 
-	return *currentConfig
+	return currentConfig
 }

And update the caller at line 208 in scanning_service.go:

-	return UpdateScanningServiceConfigDTO(zs, &scanConfig, flags, scanType, sbom, dbName, decoded)
+	return UpdateScanningServiceConfigDTO(zs, scanConfig, flags, scanType, sbom, dbName, decoded)
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b789b60 and 272af55.

📒 Files selected for processing (3)
  • CHANGELOG.md
  • pkg/service/scanning_service.go
  • pkg/service/scanning_service_config.go
🧰 Additional context used
🧬 Code graph analysis (2)
pkg/service/scanning_service.go (2)
pkg/service/utils_service.go (1)
  • APIService (71-73)
pkg/service/scanning_service_config.go (3)
  • ScanningServiceConfig (26-37)
  • DefaultScanningServiceConfig (39-52)
  • UpdateScanningServiceConfigDTO (54-134)
pkg/service/scanning_service_config.go (1)
pkg/config/server_config.go (1)
  • ServerConfig (37-93)
🔇 Additional comments (8)
CHANGELOG.md (1)

11-15: LGTM!

The version entry is properly formatted with a recent release date and clear descriptions of the new scanning configuration features. The comparison link that was previously missing has been added at line 169.

pkg/service/scanning_service_config.go (1)

39-52: LGTM!

The function correctly initializes default scanning configuration from server-wide settings, with appropriate defaults for SBOM fields.

pkg/service/scanning_service.go (6)

40-43: LGTM!

The SBOM type constants are well-defined and improve maintainability by centralizing these string literals.


164-209: LGTM!

The function cleanly extracts configuration from both form values and headers, with proper base64 decoding of the scan settings header. The fallback logic ensures flexibility in how clients can provide parameters.


95-115: LGTM!

The config-driven approach is well-integrated here, with proper validation of SBOM types using the defined constants. The configuration flows correctly to the scanning functions.


228-228: LGTM!

The function signatures have been consistently updated to accept the scanning configuration. Passing the config by value is appropriate since these functions only read from it.

Also applies to: 248-248, 340-340, 379-379


416-427: LGTM!

The SBOM configuration logic correctly maps the SBOM type to the appropriate command-line flags using the defined constants, with a sensible default fallback.


444-447: Update the stale comment or remove the unsupported flag.

The --ignore-file-ext flag is added to scan arguments when honourFileExts is false (lines 445-446), but the comment states it's "not yet implemented in scanoss engine." The mock test engine does not recognize this flag, and no engine documentation confirms support. Either:

  1. Update the comment to reflect current engine support if now implemented, or
  2. Remove or gate this flag behind a feature flag until engine support is confirmed

Running scans with an unrecognized flag risks failures depending on the engine version in use.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

♻️ Duplicate comments (2)
pkg/service/scanning_service.go (1)

406-414: Fix flag formatting inconsistency.

Line 413 formats the -F flag with a space ("-F %v"), while other single-character flags in the same function use no space (e.g., line 408: "-n%s", line 431: "-r%d"). This creates an inconsistent argument format.

🔎 Proposed fix
 	// Scanning flags
 	if config.flags > 0 {
-		args = append(args, fmt.Sprintf("-F %v", config.flags))
+		args = append(args, fmt.Sprintf("-F%v", config.flags))
 	}
pkg/config/server_config.go (1)

132-140: Fix minor typo in comment.

Line 138 has a small typo: "on the file total lines" should be "based on the file total lines" to match the comment on line 137.

🔎 Proposed fix
-	cfg.Scanning.MinSnippetLines = 0 // Lets the engine decide on minimum snippet hits on the file total lines
+	cfg.Scanning.MinSnippetLines = 0 // Lets the engine decide on minimum snippet lines based on the file total lines

Also note: the comment says "minimum snippet hits" but should say "minimum snippet lines" to match the field name.

🧹 Nitpick comments (2)
pkg/config/server_config.go (1)

73-81: Good addition of scanning configuration fields.

The new ranking and snippet matching configuration fields are well-documented and properly grouped. The defaults set later in the file are reasonable.

💡 Optional: Consider using full field name for consistency

The field SnippetRangeTol abbreviates "Tolerance" to "Tol", while other fields use full words (e.g., MinSnippetHits, MinSnippetLines). For consistency, consider renaming to SnippetRangeTolerance:

-		SnippetRangeTol int  `env:"SCANOSS_SNIPPET_RANGE_TOL"` // Snippet range tolerance for matching
+		SnippetRangeTolerance int  `env:"SCANOSS_SNIPPET_RANGE_TOL"` // Snippet range tolerance for matching

Note: This would require updating all references in scanning_service_config.go where it's currently mapped as snippetRangeTolerance.

pkg/service/scanning_service_config.go (1)

26-38: Consider field visibility for better encapsulation.

All fields in ScanningServiceConfig are private (unexported). While this works since the accessing code is in the same package, it limits flexibility and testability. Consider either:

  1. Making fields public (exported) if external packages need access
  2. Adding getter methods for better encapsulation

The current approach is acceptable for internal package use, but adding getters would improve maintainability if the struct evolves.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 272af55 and 1636654.

📒 Files selected for processing (4)
  • pkg/config/server_config.go
  • pkg/service/scanning_service.go
  • pkg/service/scanning_service_config.go
  • pkg/service/scanning_service_config_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/service/scanning_service_config_test.go
🧰 Additional context used
🧬 Code graph analysis (2)
pkg/service/scanning_service_config.go (1)
pkg/config/server_config.go (1)
  • ServerConfig (37-94)
pkg/service/scanning_service.go (2)
pkg/service/utils_service.go (1)
  • APIService (71-73)
pkg/service/scanning_service_config.go (3)
  • ScanningServiceConfig (26-38)
  • DefaultScanningServiceConfig (40-54)
  • UpdateScanningServiceConfigDTO (56-142)
🪛 GitHub Actions: Go Unit Test
pkg/service/scanning_service_config.go

[error] TestUpdateScanningServiceConfigDTO_JSONSettings failed: Expected SnippetRangeTol to be 10, got 0.

🔇 Additional comments (5)
pkg/service/scanning_service.go (4)

40-43: Good addition of SBOM constants.

Defining constants for the SBOM types improves code maintainability and reduces the risk of typos.


95-115: Clean refactoring to config-driven SBOM handling.

The SBOM validation logic has been successfully refactored to use the new ScanningServiceConfig. The validation remains consistent with the previous implementation while improving code organization.


164-209: Well-structured config extraction logic.

The function cleanly handles form values, header fallbacks, and base64-decoded scan settings. The configuration flow is logical and the error handling is appropriate.


228-228: Consistent signature updates across all scanning functions.

All scanning functions have been successfully updated to accept the new ScanningServiceConfig parameter. The signatures are consistent and all call sites have been properly updated.

Also applies to: 248-248, 340-340, 379-379

pkg/service/scanning_service_config.go (1)

40-54: Clean initialization from server config.

The function correctly initializes a ScanningServiceConfig from the server's default configuration, mapping all relevant fields appropriately.

"go.uber.org/zap"
)

const (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

explain what these are

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I created this constants to avoid the repeated code checking for the strings "identify" and "blacklist". Actually, this was suggested by coderabbit

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant to document what they are used for.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI Agents
In @pkg/service/scanning_service_config.go:
- Around line 98-109: Add a nil check before dereferencing currentConfig: if
currentConfig == nil { s.Errorf("nil currentConfig passed to update scanning
service config") ; return ScanningServiceConfig{} } so you avoid the panic when
doing updatedConfig := *currentConfig; then proceed to create updatedConfig :=
*currentConfig and continue with unmarshalling inputSettings into newSettings.
Ensure you reference currentConfig and updatedConfig exactly as in the diff and
keep the existing error log style (s.Errorf).
🧹 Nitpick comments (1)
pkg/service/scanning_service_config.go (1)

41-55: Consider adding nil check for defensive programming.

If serverDefaultConfig is nil, this function will panic. While this may be controlled by callers, a nil check would provide better resilience and clearer error messaging.

🔎 Proposed defensive check
 func DefaultScanningServiceConfig(serverDefaultConfig *cfg.ServerConfig) ScanningServiceConfig {
+	if serverDefaultConfig == nil {
+		return ScanningServiceConfig{}
+	}
 	return ScanningServiceConfig{
 		flags:                 serverDefaultConfig.Scanning.ScanFlags,
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 5770f39 and 84f6836.

📒 Files selected for processing (2)
  • Makefile
  • pkg/service/scanning_service_config.go
🔇 Additional comments (6)
Makefile (2)

36-39: LGTM!

The new unit_test_cover target correctly mirrors the existing unit_test target with the addition of the -cover flag for coverage reporting. The implementation is consistent with the existing Makefile conventions.


74-79: LGTM!

The e2e_test_cover target correctly follows the same docker-compose workflow as e2e_test while adding coverage reporting. The structure is clean and consistent.

pkg/service/scanning_service_config.go (4)

27-39: LGTM!

The struct design with unexported fields provides good encapsulation. The field types are appropriate for their purposes.


154-162: Error handling is inconsistent but acceptable.

JSON unmarshal errors (line 107) cause an early return, while flags conversion errors (line 157) only log and continue processing other fields. This difference is reasonable—a malformed JSON blob invalidates all settings, whereas a bad flags value shouldn't prevent other valid updates from applying.

If you prefer consistent behavior, consider documenting this explicitly or applying the same "continue on error" approach to JSON parsing for partial updates.


111-147: LGTM!

The conditional updates with pointer nil checks correctly distinguish between "not provided" and "zero value". The ranking settings are properly guarded by rankingAllowed with appropriate warning logs when ignored.


164-172: LGTM!

The sbomType and sbomFile updates are straightforward with proper debug logging.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
test-support/scanoss.sh (1)

32-32: Consider writing error to stderr for consistency.

Line 65 writes its error message to stderr (>&2), but this error message goes to stdout. While not critical for a test script, directing all error messages to stderr would improve consistency.

♻️ Optional improvement
-    echo "Error: Invalid MD5 hash format: $md5"
+    echo "Error: Invalid MD5 hash format: $md5" >&2
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 84f6836 and d486014.

📒 Files selected for processing (1)
  • test-support/scanoss.sh
🔇 Additional comments (2)
test-support/scanoss.sh (2)

30-34: LGTM! MD5 validation logic is correct.

The regex pattern correctly validates that MD5 hashes are exactly 32 hexadecimal characters, and the error handling appropriately exits with a non-zero status for invalid inputs.


59-68: LGTM! KB name validation logic is sound.

The validation correctly enforces that the KB name must be attached to the -n flag (e.g., -nMyKB rather than -n MyKB). By checking for standalone -n, the code effectively ensures a non-empty KB name is provided, since any attached name would make the argument not equal to -n.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In @pkg/service/scanning_service_config.go:
- Line 101: Update the fmt.Errorf messages that start with a capitalized
"Default" to use a lowercase "default" to follow Go error string conventions
(ST1005); locate the fmt.Errorf call returning ScanningServiceConfig{} (the
message "Default server scanning service config is undefined") and the similar
fmt.Errorf at the other occurrence and change their messages to start with
"default" instead.

In @pkg/service/scanning_service.go:
- Line 202: The error string returned when decoding scan settings is
capitalized; change the fmt.Errorf call that currently uses "Error decoding scan
settings from base64: %v" to use a lowercase leading word (e.g., "error decoding
scan settings from base64: %v") so it follows Go ST1005 conventions; locate the
return that returns scanConfig and fmt.Errorf in scanning_service.go (the
decode/parse routine that handles base64 scan settings) and update the message
accordingly.
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d486014 and cdc98ee.

📒 Files selected for processing (6)
  • pkg/service/scanning_service.go
  • pkg/service/scanning_service_config.go
  • pkg/service/scanning_service_config_test.go
  • pkg/service/scanning_service_test.go
  • test-support/scanoss.sh
  • tests/scanning_test.go
✅ Files skipped from review due to trivial changes (1)
  • pkg/service/scanning_service_test.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/service/scanning_service_config_test.go
🧰 Additional context used
🧬 Code graph analysis (1)
pkg/service/scanning_service_config.go (1)
pkg/config/server_config.go (1)
  • ServerConfig (37-94)
🪛 GitHub Check: build
pkg/service/scanning_service_config.go

[failure] 110-110:
ST1005: error strings should not be capitalized (stylecheck)


[failure] 101-101:
ST1005: error strings should not be capitalized (stylecheck)

pkg/service/scanning_service.go

[failure] 202-202:
ST1005: error strings should not be capitalized (stylecheck)

🔇 Additional comments (15)
test-support/scanoss.sh (3)

30-34: LGTM: MD5 validation is correct.

The regex pattern properly validates MD5 hash format (32 hexadecimal characters), and the error handling with exit code 1 is appropriate for test simulation.


59-68: LGTM: KB name validation is correct.

The validation properly detects the bare -n flag without an attached KB name and provides a clear error message. This aligns with the expected engine behavior.


71-79: LGTM: -w flag detection works correctly.

The loop properly detects the -w flag anywhere in the arguments and produces appropriate simulated output for test purposes.

tests/scanning_test.go (3)

93-93: LGTM: Assets payload format improved.

The change from plain PURL strings to structured JSON with a components array is a good improvement that aligns with standard SBOM formats like CycloneDX and SPDX.

Also applies to: 100-100


136-222: LGTM: Comprehensive test coverage for scan settings header.

The new TestScanSettingsHeader test function provides excellent coverage:

  • Valid multi-parameter scan settings with proper base64 encoding
  • Invalid base64 handling with appropriate error response
  • Integration with legacy flags parameter

The inline comments documenting the decoded JSON payloads enhance readability and maintainability.


46-52: Test expectation is well-documented and appears correct.

The test change from http.StatusInternalServerError to http.StatusOK is clearly explained by the inline comment: the engine now handles invalid KB names gracefully with fallback behavior. The API correctly passes the db_name parameter through to the scanning engine without validation—this is the appropriate responsibility boundary since the engine itself determines whether the KB name is valid. Debug logging is already in place for tracking DB name configuration updates.

pkg/service/scanning_service_config.go (3)

28-40: LGTM: Well-structured configuration type.

The ScanningServiceConfig struct has a comprehensive set of fields for scanning configuration, and the use of unexported fields is appropriate for internal service configuration.


42-56: LGTM: Proper default configuration initialization.

The function correctly initializes the scanning configuration from server defaults while appropriately leaving per-request fields (sbomType, sbomFile) empty.


87-167: LGTM: Well-implemented configuration update logic.

The function properly:

  • Checks for nil config and returns an error
  • Creates a copy to avoid modifying the original
  • Gates ranking updates based on rankingAllowed with appropriate warnings
  • Handles JSON unmarshalling errors
  • Validates and converts flags with error handling

The immutable update pattern (copy, modify, return) is a good design choice.

pkg/service/scanning_service.go (6)

40-43: LGTM: SBOM type constants improve code clarity.

The constants eliminate magic strings and make the code more maintainable. As noted in past reviews, these represent the two SBOM scan types supported by the engine: "identify" (include matching components) and "blacklist" (exclude matching components).


95-120: LGTM: Proper config extraction and error handling.

The refactored code correctly:

  • Obtains scanning configuration from the request
  • Handles configuration errors with appropriate HTTP status
  • Validates SBOM types using the new constants
  • Uses config fields consistently

169-208: LGTM: Well-implemented config extraction with proper fallbacks.

The function correctly:

  • Extracts scanning parameters from both form values and headers
  • Implements a proper fallback mechanism
  • Decodes and validates base64-encoded scan settings
  • Returns errors to the caller for proper HTTP error responses
  • Guards trace logging appropriately

The past review concern about else-if style has been addressed.


227-227: LGTM: Consistent config-driven refactoring.

The updated function signatures consistently use ScanningServiceConfig instead of multiple individual parameters, resulting in cleaner, more maintainable code across all scanning functions.

Also applies to: 247-247, 339-339, 378-378


398-446: LGTM: Well-structured argument building logic.

The command argument construction is well-organized:

  • Consistent flag formatting for single-character flags (-n%s, -F%v, -r%d)
  • Proper use of long-form flags with equals signs for snippet parameters
  • Ranking threshold correctly gated by both rankingEnabled and positive threshold value
  • SBOM configuration properly uses constants with switch statement

The past review concern about flag format consistency has been addressed.


447-450: Verify --ignore-file-ext flag support before release.

As flagged in a previous review, the --ignore-file-ext flag may not be supported by the SCANOSS engine. The comment on line 447 states "(not yet implemented in scanoss engine)". This creates a risk:

  1. If the flag is not recognized, the scan command will fail with "Unknown command option"
  2. The simulator script (test-support/scanoss.sh) doesn't handle this flag, so E2E tests won't catch the issue

Run the following script to check if the flag is handled by the test simulator and verify its usage in the real engine:

#!/bin/bash
# Check if --ignore-file-ext is handled in the simulator
echo "=== Check test simulator for --ignore-file-ext handling ==="
grep -n "ignore-file-ext" test-support/scanoss.sh

echo ""
echo "=== Check for any documentation or comments about this flag ==="
rg -n "ignore-file-ext|honourFileExts" --type=go -B 2 -A 2

echo ""
echo "=== Check if there's version detection for this flag ==="
rg -n "version|engine.*version" pkg/service/scanning_service.go -B 2 -A 2 | grep -i "detect\|check"

If the flag is not yet supported, consider:

  1. Remove lines 447-450 until engine support is confirmed
  2. Add version detection to conditionally pass the flag
  3. Update the test simulator to handle/ignore this flag gracefully

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
pkg/service/scanning_service.go (1)

428-430: Consider adding rankingAllowed check for defensive coding.

While UpdateScanningServiceConfigDTO prevents clients from enabling ranking when rankingAllowed is false, the condition here doesn't verify rankingAllowed. If the server configuration itself is misconfigured (e.g., rankingAllowed=false but rankingEnabled=true), the ranking flag would still be passed to the engine.

For defensive coding, consider changing the condition to:

if config.rankingAllowed && config.rankingEnabled && config.rankingThreshold > 0 {

This ensures the flag is only passed when ranking is both allowed and enabled.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cdc98ee and 97ede06.

📒 Files selected for processing (2)
  • pkg/service/scanning_service.go
  • pkg/service/scanning_service_config.go
🧰 Additional context used
🧬 Code graph analysis (2)
pkg/service/scanning_service_config.go (1)
pkg/config/server_config.go (1)
  • ServerConfig (37-94)
pkg/service/scanning_service.go (2)
pkg/service/utils_service.go (1)
  • APIService (71-73)
pkg/service/scanning_service_config.go (3)
  • ScanningServiceConfig (28-40)
  • DefaultScanningServiceConfig (42-56)
  • UpdateScanningServiceConfigDTO (87-167)
🔇 Additional comments (5)
pkg/service/scanning_service_config.go (1)

1-167: LGTM! Well-structured config management implementation.

The file introduces a clean, immutable configuration update pattern. All past review concerns have been addressed:

  • Nil check prevents panics
  • Error strings follow Go conventions (lowercase)
  • JSON field names match correctly
  • Comprehensive documentation explains the immutable copy semantics

The conditional logic properly restricts ranking modifications when rankingAllowed is false, and the logging provides good observability.

pkg/service/scanning_service.go (4)

40-43: Good use of constants for SBOM type checking.

Using sbomIdentify and sbomBlackList constants eliminates string literal repetition and reduces the risk of typos when checking SBOM types throughout the code.


169-208: LGTM! Clean config extraction with proper error handling.

The function correctly extracts configuration from both form values and headers, with appropriate fallback logic. The base64 decoding error handling follows Go conventions, and all past review concerns have been addressed.


104-119: LGTM! Proper SBOM validation.

The validation correctly uses the new constants and ensures only valid SBOM types (identify or blacklist) are accepted before proceeding with scan operations.


404-445: LGTM! Consistent flag formatting and conditional logic.

The command argument construction properly:

  • Uses consistent formatting: -n%s, -F%v, -r%d (no spaces) and --long-form=%d (with equals)
  • Applies conditional checks to only add flags when values are positive
  • Handles SBOM flags correctly with the switch statement

if flags != "" {
flagsInt, err := strconv.Atoi(flags)
if err != nil {
s.Errorf("Error converting flags to integer: %v", err)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do you want this to fail or just ignore it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It´s not failing, this is just a log, right?

"go.uber.org/zap"
)

const (
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant to document what they are used for.

flags, scanType, sbom, dbName := s.getFlags(r, zs)
scanConfig, err := s.getConfigFromRequest(r, zs)
if err != nil {
http.Error(w, "ERROR invalid scanning configuration", http.StatusBadRequest)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we want to share what was invalid?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I understood that the idea is to inform the user if the client is sending a wrong configuration, do you prefer just a server side log?

## [1.6.0] - 2025-12-26
### Added
- Added scanoss.json scanning config support.
- Added new server-side configuration parameters for scanning tune-up.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add the new parameter names here in a sub-list please


## [1.6.0] - 2025-12-26
### Added
- Added scanoss.json scanning config support.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

List out the support header parameters

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
CHANGELOG.md (1)

11-21: Consider consistent spelling for honourFileExts.

The parameter name uses British English spelling (honour). Ensure this spelling is consistent across the entire codebase (code, configuration, and documentation) to avoid confusion. If the codebase uses American English elsewhere, consider standardizing to honorFileExts.

pkg/service/scanning_service_config.go (1)

87-179: Refactor to reduce cognitive complexity and verify validation logic.

The function has high cognitive complexity (32 > 25) due to multiple conditional branches. Consider extracting validation logic into separate helper functions.

Additionally, verify the validation inconsistency:

  • MinSnippetHits allows >= 0 (Line 130)
  • MinSnippetLines requires > 0 (Line 138)
  • SnippetRangeTolerance allows >= 0 (Line 146)

Are these different bounds intentional? If so, document why MinSnippetHits can be 0 but MinSnippetLines cannot. If not, standardize the validation logic.

♻️ Example refactoring to reduce complexity

Extract validation into helper functions:

func validateMinSnippetHits(value int) bool {
    return value >= 0
}

func validateMinSnippetLines(value int) bool {
    return value > 0
}

func validateSnippetRangeTolerance(value int) bool {
    return value >= 0
}

func (c *ScanningServiceConfig) applyRankingSetting(s *zap.SugaredLogger, enabled *bool, threshold *int) {
    if !c.rankingAllowed {
        s.Warnf("Ranking settings ignored as RankingAllowed is false")
        return
    }
    if enabled != nil {
        c.rankingEnabled = *enabled
        s.Debugf("Updated RankingEnabled to %v", c.rankingEnabled)
    }
    if threshold != nil {
        c.rankingThreshold = *threshold
        s.Debugf("Updated RankingThreshold to %d", c.rankingThreshold)
    }
}

Then simplify the main function by calling these helpers.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 97ede06 and 290ec7a.

📒 Files selected for processing (4)
  • CHANGELOG.md
  • Makefile
  • pkg/service/scanning_service.go
  • pkg/service/scanning_service_config.go
🧰 Additional context used
🪛 GitHub Check: build
pkg/service/scanning_service_config.go

[failure] 87-87:
cognitive complexity 32 of func UpdateScanningServiceConfigDTO is high (> 25) (gocognit)

🪛 LanguageTool
CHANGELOG.md

[grammar] ~20-~20: Ensure spelling is correct
Context: ...inSnippetLines - snippetRangeTolerance - honourFileExts ## [1.5.2] - 2025-11-07 ### Added - Added Cu...

(QB_NEW_EN_ORTHOGRAPHY_ERROR_IDS_1)

🔇 Additional comments (9)
Makefile (1)

36-38: LGTM! Coverage test targets properly implemented.

The new coverage targets correctly extend the existing test workflow by adding the -cover flag to unit, integration, and end-to-end tests. The implementation follows the existing patterns and provides explicit coverage reporting without modifying the base test targets.

Also applies to: 44-46, 78-83

CHANGELOG.md (1)

176-176: LGTM! Version link properly added.

The version comparison link is correctly formatted and follows the existing pattern.

pkg/service/scanning_service_config.go (2)

28-40: LGTM! Well-structured configuration type.

The ScanningServiceConfig struct is well-organized with unexported fields appropriate for internal service use. The logical grouping of related fields (SBOM, ranking, snippet settings) enhances readability.


42-56: LGTM! Default configuration properly initialized.

The function correctly initializes all configuration fields from the server defaults, with appropriate empty string defaults for SBOM-related fields that are request-specific.

pkg/service/scanning_service.go (5)

40-43: LGTM! SBOM constants improve code clarity.

The SBOM type constants enhance code readability and reduce the risk of typos in string comparisons throughout the codebase.


95-100: LGTM! Proper error handling for configuration.

The error handling for invalid scanning configuration is appropriate and provides clear feedback to the client with a 400 Bad Request status.


168-207: LGTM! Config extraction well-implemented with proper fallbacks.

The function correctly:

  • Extracts parameters from form values with header fallbacks
  • Decodes base64-encoded scan settings with appropriate error handling
  • Creates default config and applies updates via the DTO pattern
  • Provides comprehensive debug logging when trace is enabled

398-444: LGTM! Config-driven command building properly implemented.

The refactored command-building logic correctly derives all scanning options from the ScanningServiceConfig:

  • Database name, flags, and SBOM handling
  • Ranking controls with proper permission checks
  • Snippet threshold parameters
  • File extension handling

The implementation maintains backward compatibility while enabling flexible per-request configuration.


439-441: Clarify the status of the --ignore-file-ext flag support in the SCANOSS engine.

The code adds the --ignore-file-ext flag based on the honourFileExts configuration (lines 440-441), but the comment explicitly states this feature is "not yet implemented in scanoss engine." This creates ambiguity: either the comment is outdated and the engine now supports this flag, or the configuration option has no actual effect.

Please confirm:

  • Is --ignore-file-ext currently supported by the SCANOSS engine?
  • If not supported, remove this conditional logic or add a note explaining it's a placeholder for future functionality.
  • If now supported, remove or update the "not yet implemented" comment.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In @pkg/service/scanning_service_config.go:
- Around line 42-56: DefaultScanningServiceConfig currently dereferences
serverDefaultConfig and will panic if it's nil; add a nil guard at the start of
DefaultScanningServiceConfig (similar to UpdateScanningServiceConfigDTO) that
returns a safe ScanningServiceConfig (zero-values or explicit defaults) when
serverDefaultConfig is nil, otherwise proceed to read fields like
serverDefaultConfig.Scanning.ScanFlags, ScanKbName, RankingAllowed,
RankingEnabled, RankingThreshold, MinSnippetHits, MinSnippetLines,
SnippetRangeTol and HonourFileExts to populate the ScanningServiceConfig struct.
🧹 Nitpick comments (1)
pkg/service/scanning_service_config.go (1)

119-142: Consider returning validation errors for consistency.

Unlike applySnippetSettings which returns invalid settings, this function silently logs and ignores invalid flags values. The caller has no indication that the flags update was skipped. Consider returning validation errors for consistency.

♻️ Optional improvement
-func applyDirectParameters(s *zap.SugaredLogger, config *ScanningServiceConfig, flags, scanType, sbom, dbName string) {
+func applyDirectParameters(s *zap.SugaredLogger, config *ScanningServiceConfig, flags, scanType, sbom, dbName string) []string {
+	var invalidParams []string
 	if dbName != "" {
 		config.dbName = dbName
 		s.Debugf("Updated DbName to %s", config.dbName)
 	}
 	if flags != "" {
 		flagsInt, err := strconv.Atoi(flags)
 		if err == nil {
 			config.flags = flagsInt
 			s.Debugf("Updated Flags to %d", config.flags)
 		} else {
 			s.Errorf("Error converting flags to integer: %v", err)
+			invalidParams = append(invalidParams, fmt.Sprintf("flags: %s", flags))
 		}
 	}
 	// ... rest unchanged
+	return invalidParams
 }
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 290ec7a and ad1f7c4.

📒 Files selected for processing (1)
  • pkg/service/scanning_service_config.go
🧰 Additional context used
🧬 Code graph analysis (1)
pkg/service/scanning_service_config.go (1)
pkg/config/server_config.go (1)
  • ServerConfig (37-94)
🔇 Additional comments (6)
pkg/service/scanning_service_config.go (6)

1-26: LGTM!

License header and imports are appropriate. All imported packages are used in the implementation.


28-40: LGTM!

The struct with unexported fields provides good encapsulation. The fields correctly mirror the server-side scanning configuration from ServerConfig.Scanning.


58-66: LGTM!

Good use of pointer types for optional JSON fields, enabling proper distinction between unset values and zero values.


68-83: LGTM!

Proper guard logic ensures ranking settings are only applied when rankingAllowed is true. The warning log provides good visibility when settings are ignored.


85-117: LGTM!

Validation logic is sensible: MinSnippetHits and SnippetRangeTolerance allow zero (disabling the constraint), while MinSnippetLines requires at least 1 line. Returning invalid settings for logging is a clean pattern.


144-196: LGTM!

Well-documented function with clear immutability guarantees. The nil check, copy-before-modify pattern, and delegated helper functions provide a clean and safe implementation. Error handling for JSON unmarshalling correctly returns the unmodified copy.

Comment on lines +42 to +56
func DefaultScanningServiceConfig(serverDefaultConfig *cfg.ServerConfig) ScanningServiceConfig {
return ScanningServiceConfig{
flags: serverDefaultConfig.Scanning.ScanFlags,
sbomType: "",
sbomFile: "",
dbName: serverDefaultConfig.Scanning.ScanKbName,
rankingAllowed: serverDefaultConfig.Scanning.RankingAllowed,
rankingEnabled: serverDefaultConfig.Scanning.RankingEnabled,
rankingThreshold: serverDefaultConfig.Scanning.RankingThreshold,
minSnippetHits: serverDefaultConfig.Scanning.MinSnippetHits,
minSnippetLines: serverDefaultConfig.Scanning.MinSnippetLines,
snippetRangeTolerance: serverDefaultConfig.Scanning.SnippetRangeTol,
honourFileExts: serverDefaultConfig.Scanning.HonourFileExts,
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Add nil check for serverDefaultConfig parameter.

If serverDefaultConfig is nil, this function will panic with a nil pointer dereference. Consider adding a guard similar to what's done in UpdateScanningServiceConfigDTO.

🛡️ Proposed fix
 func DefaultScanningServiceConfig(serverDefaultConfig *cfg.ServerConfig) ScanningServiceConfig {
+	if serverDefaultConfig == nil {
+		return ScanningServiceConfig{}
+	}
 	return ScanningServiceConfig{
 		flags:                 serverDefaultConfig.Scanning.ScanFlags,
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func DefaultScanningServiceConfig(serverDefaultConfig *cfg.ServerConfig) ScanningServiceConfig {
return ScanningServiceConfig{
flags: serverDefaultConfig.Scanning.ScanFlags,
sbomType: "",
sbomFile: "",
dbName: serverDefaultConfig.Scanning.ScanKbName,
rankingAllowed: serverDefaultConfig.Scanning.RankingAllowed,
rankingEnabled: serverDefaultConfig.Scanning.RankingEnabled,
rankingThreshold: serverDefaultConfig.Scanning.RankingThreshold,
minSnippetHits: serverDefaultConfig.Scanning.MinSnippetHits,
minSnippetLines: serverDefaultConfig.Scanning.MinSnippetLines,
snippetRangeTolerance: serverDefaultConfig.Scanning.SnippetRangeTol,
honourFileExts: serverDefaultConfig.Scanning.HonourFileExts,
}
}
func DefaultScanningServiceConfig(serverDefaultConfig *cfg.ServerConfig) ScanningServiceConfig {
if serverDefaultConfig == nil {
return ScanningServiceConfig{}
}
return ScanningServiceConfig{
flags: serverDefaultConfig.Scanning.ScanFlags,
sbomType: "",
sbomFile: "",
dbName: serverDefaultConfig.Scanning.ScanKbName,
rankingAllowed: serverDefaultConfig.Scanning.RankingAllowed,
rankingEnabled: serverDefaultConfig.Scanning.RankingEnabled,
rankingThreshold: serverDefaultConfig.Scanning.RankingThreshold,
minSnippetHits: serverDefaultConfig.Scanning.MinSnippetHits,
minSnippetLines: serverDefaultConfig.Scanning.MinSnippetLines,
snippetRangeTolerance: serverDefaultConfig.Scanning.SnippetRangeTol,
honourFileExts: serverDefaultConfig.Scanning.HonourFileExts,
}
}
🤖 Prompt for AI Agents
In @pkg/service/scanning_service_config.go around lines 42 - 56,
DefaultScanningServiceConfig currently dereferences serverDefaultConfig and will
panic if it's nil; add a nil guard at the start of DefaultScanningServiceConfig
(similar to UpdateScanningServiceConfigDTO) that returns a safe
ScanningServiceConfig (zero-values or explicit defaults) when
serverDefaultConfig is nil, otherwise proceed to read fields like
serverDefaultConfig.Scanning.ScanFlags, ScanKbName, RankingAllowed,
RankingEnabled, RankingThreshold, MinSnippetHits, MinSnippetLines,
SnippetRangeTol and HonourFileExts to populate the ScanningServiceConfig struct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants