diff --git a/CONTAINER_DOCS.md b/CONTAINER_DOCS.md index a103cb2..780fa39 100644 --- a/CONTAINER_DOCS.md +++ b/CONTAINER_DOCS.md @@ -21,6 +21,8 @@ Inputs documented in the GitHub Actions [README](README.md#inputs) are all suppo |`failThreshold`|`FAIL_THRESHOLD`|`CONTRAST_FAIL_THRESHOLD`| |`jobStartTime`|`JOB_START_TIME`|`CONTRAST_JOB_START_TIME`| |`severities`|`SEVERITIES`|`CONTRAST_SEVERITIES`| +|`sessionMetadata`|`SESSION_METADATA`|`CONTRAST_SESSION_METADATA`| +|`routeCoverageThreshold`|`ROUTE_COVERAGE_THRESHOLD`|`CONTRAST_ROUTE_COVERAGE_THRESHOLD`| The `CONTRAST_` prefix is optional. diff --git a/README.md b/README.md index f210efc..a2d4e65 100644 --- a/README.md +++ b/README.md @@ -16,6 +16,8 @@ This action verifies an application that's onboarded to Contrast by determining |`failThreshold`|Number of vulnerabilities that are needed to fail the build (not used if there is a defined job outcome policy)|No, defaults to `0`| |`jobStartTime`|Filter vulnerabilities first found after this timestamp (formatted **in milliseconds** since the epoch)|No, defaults to `0`| |`severities`|Comma separated list of vulnerability severities to consider (not used if there is a defined job outcome policy). Values allowed are `CRITICAL`, `HIGH`, `MEDIUM`, `LOW` and `NOTE`|No, defaults to `CRITICAL,HIGH`| +|`sessionMetadata`|Session metadata to filter vulnerabilities and route coverage by, in the same `key=value` format as the agent's `session_metadata` configuration, e.g. `branchName=main,commitHash=abc123`. See [Session Metadata](#session-metadata)|No| +|`routeCoverageThreshold`|Minimum route coverage percentage (`0`-`100`) required to pass. Filtered by `sessionMetadata` if provided|No, route coverage is not checked if unset| ## Example usage @@ -65,6 +67,32 @@ You may also pass a `buildNumber` input which will filter for vulnerabilities fo If both `jobStartTime` and `buildNumber` are provided, the step will consider only vulnerabilities found since the specified start time, **and** with the provided `buildNumber`. +### Session Metadata + +Contrast agents can tag the vulnerabilities and routes they observe with [session metadata](https://docs.contrastsecurity.com/en/session-metadata.html), configured via `CONTRAST__APPLICATION__SESSION_METADATA` (or `application.session_metadata` in YAML), for example `branchName=main,commitHash=abc123`. + +Pass the same key/value pairs to the `sessionMetadata` input to verify only results from that session. Entries may be separated by commas or newlines, and keys may be the agent key (`branchName`) or the TeamServer display label (`Branch Name`). When `sessionMetadata` is provided: + +- Job outcome policies are **not** used. Instead, open vulnerabilities matching **all** of the provided metadata (plus `severities`, and `buildNumber`/`jobStartTime` if set) are counted, and the step fails if the count is above `failThreshold`. +- If `routeCoverageThreshold` is set, route coverage (exercised routes / discovered routes) is calculated for the matching session, and the step fails if it is below the threshold. + +`routeCoverageThreshold` may also be used without `sessionMetadata`, in which case route coverage for the whole application is checked. If multiple checks fail, all failures are reported. + +If any `sessionMetadata` key or value has not been reported to TeamServer for the application, a warning is logged and both checks fall back to the whole application: all open vulnerabilities (still filtered by `severities`, `buildNumber` and `jobStartTime`) are compared against `failThreshold`, and route coverage is calculated for the whole application. + +```yaml + - name: Contrast Verify + uses: Contrast-Security-OSS/integration-verify-github-action@main + with: + apiKey: ${{ secrets.CONTRAST_API_KEY }} + orgId: + authHeader: ${{ secrets.CONTRAST_AUTH_HEADER }} + appName: App_Name_Here + sessionMetadata: "branchName=${{ github.ref_name }},commitHash=${{ github.sha }}" + failThreshold: 0 + routeCoverageThreshold: 80 +``` + ## Use outside of GitHub Actions This integration is available as a Docker image which allows it to be used in other environments outside of GitHub Actions, for example, in GitLab pipelines. For more details, see [Container Documentation](CONTAINER_DOCS.md). diff --git a/action.yaml b/action.yaml index 6f8d4f2..9386493 100644 --- a/action.yaml +++ b/action.yaml @@ -36,6 +36,10 @@ inputs: severities: description: 'Comma separated list of vulnerability severities to consider (not used if there is a defined job outcome policy)' default: 'CRITICAL,HIGH' + sessionMetadata: + description: 'Session metadata to filter vulnerabilities and route coverage by, in the same format as the agent session_metadata configuration, e.g. "branchName=main,commitHash=abc123". When set, job outcome policies are not used and matching open vulnerabilities are compared against failThreshold.' + routeCoverageThreshold: + description: 'Minimum route coverage percentage (0-100) required to pass. Route coverage is filtered by sessionMetadata if provided. Not checked if unset.' runs: using: 'docker' diff --git a/contrastverify/helpers/input_output_helpers.py b/contrastverify/helpers/input_output_helpers.py index db54598..2e8e8d1 100644 --- a/contrastverify/helpers/input_output_helpers.py +++ b/contrastverify/helpers/input_output_helpers.py @@ -93,6 +93,33 @@ def get_included_severities(severities_csv: str) -> list[str]: if severity in input_severities ] + @staticmethod + def parse_session_metadata(session_metadata: str | None) -> dict[str, str]: + """ + Parse session metadata in the same format used by the Contrast agent's `application.session_metadata` + configuration, e.g. `branchName=main,commitHash=abc123,buildNumber=42`. + Entries may be separated by commas or newlines; keys and values are trimmed. + :raises ValueError: if an entry is not a key=value pair, or a key is repeated + """ + metadata = {} + if not session_metadata: + return metadata + + for entry in session_metadata.replace("\n", ",").split(","): + entry = entry.strip() + if entry == "": + continue + key, separator, value = entry.partition("=") + key = key.strip() + value = value.strip() + if not separator or key == "" or value == "": + raise ValueError(f'"{entry}" is not in the format key=value') + if key in metadata: + raise ValueError(f'key "{key}" is specified more than once') + metadata[key] = value + + return metadata + @staticmethod def load_certs(output_helper: OutputHelper) -> Path | None: certs_to_add = InputHelper.get_input("CA_FILE") diff --git a/contrastverify/verify.py b/contrastverify/verify.py index fdf2e0d..60cb974 100644 --- a/contrastverify/verify.py +++ b/contrastverify/verify.py @@ -24,6 +24,8 @@ def __init__( severities: list[str], output_helper: OutputHelper | None = None, cert_file: Path | None = None, + session_metadata: dict[str, str] | None = None, + route_coverage_threshold: float | None = None, ) -> None: self._app_id = app_id self._app_name = app_name @@ -36,11 +38,16 @@ def __init__( self._severities = severities self._output_helper = output_helper or OutputHelper() self._cert_file = str(cert_file) if cert_file else True + self._session_metadata = session_metadata or {} + self._route_coverage_threshold = route_coverage_threshold self._headers = None self._user_agent = None self._app_id_verified = False self._job_start_time_provided = job_start_time is not None + self._session_metadata_fields = None + self._session_metadata_filters_resolved = False + self._session_metadata_filters = None @property def user_agent(self): @@ -90,11 +97,12 @@ def get_request(self, path, parameters={}): response.raise_for_status() return response - def post_request(self, path, body): + def post_request(self, path, body, parameters={}): """Send a POST request to TeamServer.""" - self._output_helper.debug(f"POST {path}") + self._output_helper.debug(f"POST {path} {parameters}") response = requests.post( self._base_url + path, + params=parameters, json=body, headers=self.teamserver_headers, verify=self._cert_file, @@ -148,6 +156,7 @@ def determine_application_id(self): ) else: self._app_id = matching_named_apps[0]["app_id"] + self._app_id_verified = True self._output_helper.info( f'Application ID for "{self._app_name}" is {self._app_id}' ) @@ -187,7 +196,208 @@ def fetch_vulnerability_count(self): ) return response.json() - def verify_application(self): + @staticmethod + def _normalize_metadata_key(key: str | None) -> str: + """Normalize a metadata key/label so `branchName`, `Branch Name` and `branch_name` all match.""" + return "".join(filter(str.isalnum, key or "")).lower() + + def fetch_session_metadata_fields(self): + """Fetch (and cache) the session metadata fields TeamServer knows about for this application.""" + if self._session_metadata_fields is None: + response = self.get_request(f"metadata/session/{self.app_id}/filters") + self._session_metadata_fields = response.json().get("filters") or [] + self._output_helper.debug( + f"Session metadata fields: {self._session_metadata_fields}" + ) + return self._session_metadata_fields + + def resolve_session_metadata(self): + """ + Match each configured session metadata key to a TeamServer metadata field, by agent label or display label, + where the field also has the configured value. + :return: tuple of (list of (key, value, field) for matched pairs, list of unmatched keys) + """ + fields = self.fetch_session_metadata_fields() + resolved = [] + unresolved = [] + for key, value in self._session_metadata.items(): + normalized_key = self._normalize_metadata_key(key) + field = next( + ( + field + for field in fields + if self._normalize_metadata_key(field.get("agentLabel")) + == normalized_key + ), + None, + ) or next( + ( + field + for field in fields + if self._normalize_metadata_key(field.get("label")) + == normalized_key + ), + None, + ) + field_values = { + str(field_value.get("value")) + for field_value in (field or {}).get("values") or [] + } + if field and value in field_values: + resolved.append((key, value, field)) + else: + unresolved.append(key) + return resolved, unresolved + + def session_metadata_filters(self): + """ + Resolve (and cache) the configured session metadata for use as filters. + If any key or value is not found in TeamServer, the session cannot be matched, so checks fall back to the whole application. + :return: list of (key, value, field), or None if checks should consider the whole application + """ + if not self._session_metadata_filters_resolved: + self._session_metadata_filters_resolved = True + if self._session_metadata: + resolved, unresolved = self.resolve_session_metadata() + if unresolved: + missing = ", ".join( + f"{key}={self._session_metadata[key]}" for key in unresolved + ) + self._output_helper.warning( + f"Session metadata {missing} was not found for this application, checks will consider the whole application instead. Check the keys and values match the agent session_metadata configuration." + ) + else: + self._session_metadata_filters = resolved + return self._session_metadata_filters + + @property + def session_metadata_description(self): + return ", ".join( + f"{key}={value}" for key, value in self._session_metadata.items() + ) + + def fetch_session_metadata_vulnerability_count(self): + """ + Count open vulnerabilities matching all configured session metadata (and other filters), + or across the whole application if the session metadata could not be resolved. + :return: number of matching open vulnerabilities + """ + body = { + "quickFilter": "OPEN", + "severities": self._severities, + } + filters = self.session_metadata_filters() + if filters is not None: + body["metadataFilters"] = [ + { + "fieldID": ( + int(field["id"]) if str(field["id"]).isdigit() else field["id"] + ), + "values": [value], + } + for _, value, field in filters + ] + if self._build_number: + body["appVersionTags"] = [self._build_number] + if self._job_start_time_provided: + body["startDate"] = self._job_start_time + body["timestampFilter"] = "FIRST" + + response = self.post_request( + f"traces/{self.app_id}/filter", + body, + {"expand": "skip_links", "limit": 1}, + ) + result = response.json() + self._output_helper.debug(result) + return result["count"] + + def fetch_route_coverage(self): + """ + Fetch route coverage for the application, filtered by session metadata if configured and resolved. + :return: tuple of (exercised route count, total route count) + """ + filters = self.session_metadata_filters() + if filters is not None: + body = { + "metadata": [ + {"label": field["label"], "values": [value]} + for _, value, field in filters + ] + } + response = self.post_request( + f"applications/{self.app_id}/route/filter", + body, + {"expand": "skip_links"}, + ) + else: + response = self.get_request( + f"applications/{self.app_id}/route", {"expand": "skip_links"} + ) + + result = response.json() + self._output_helper.debug(result) + routes = result.get("routes") or [] + total = result.get("count") + if total is None: + total = len(routes) + exercised = result.get("exercisedCount", result.get("exercised_count")) + if exercised is None: + exercised = len( + [ + route + for route in routes + if route.get("status") == "EXERCISED" or route.get("exercised") + ] + ) + return exercised, total + + def verify_route_coverage(self): + """ + Compare route coverage percentage against the configured minimum. + :return: failure message, or None if the check passes + """ + threshold = self._route_coverage_threshold + if threshold is None: + return None + exercised, total = self.fetch_route_coverage() + coverage = (exercised / total * 100) if total else 0.0 + scope = ( + f" for session metadata [{self.session_metadata_description}]" + if self.session_metadata_filters() is not None + else "" + ) + summary = f"Route coverage{scope} is {coverage:.2f}% ({exercised} of {total} routes exercised)" + if total == 0: + self._output_helper.warning( + "No routes were found, check that the application has been exercised with a Contrast agent." + ) + if coverage < threshold: + return f"{summary} - Contrast verify gate fails as this is below threshold (threshold requires {threshold:g}%)" + self._output_helper.info(f"{summary} (meets threshold of {threshold:g}%)") + return None + + def verify_session_metadata_vulnerabilities(self): + """ + Compare the number of open vulnerabilities matching session metadata against the fail threshold. + :return: failure message, or None if the check passes + """ + self._output_helper.info( + f"Session metadata provided [{self.session_metadata_description}], checking matching vulnerabilities against threshold (job outcome policies are not used)..." + ) + open_vulnerabilities = self.fetch_session_metadata_vulnerability_count() + if open_vulnerabilities > self._fail_threshold: + return f"The vulnerability count is {open_vulnerabilities} - Contrast verify gate fails as this is above threshold (threshold allows {self._fail_threshold})" + self._output_helper.info( + f"The vulnerability count is {open_vulnerabilities} (below threshold)" + ) + return None + + def verify_vulnerabilities(self): + """ + Check the application against a matching job outcome policy, or the open vulnerability count if none match. + :return: failure message, or None if the check passes + """ # First check for a configured job outcome policy defined in TeamServer job_outcome_policy_result = self.perform_security_check() self._output_helper.debug(job_outcome_policy_result) @@ -207,9 +417,7 @@ def verify_application(self): f'Matching policy "{jop_name}" has job start time configured, but no job start time was provided, so 0 was passed to consider all open vulnerabilities.' ) - self._output_helper.set_failed( - f'Contrast verify gate fails with status {jop_outcome} - policy "{jop_name}"' - ) + return f'Contrast verify gate fails with status {jop_outcome} - policy "{jop_name}"' elif security_check_result is True: self._output_helper.info("Step passes matching policy") else: @@ -226,10 +434,28 @@ def verify_application(self): ) open_vulnerabilities = open_vulnerabilities_data["count"] if open_vulnerabilities > self._fail_threshold: - self._output_helper.set_failed( - f"The vulnerability count is {open_vulnerabilities} - Contrast verify gate fails as this is above threshold (threshold allows {self._fail_threshold})" - ) - else: - self._output_helper.info( - f"The vulnerability count is {open_vulnerabilities} (below threshold)" - ) + return f"The vulnerability count is {open_vulnerabilities} - Contrast verify gate fails as this is above threshold (threshold allows {self._fail_threshold})" + self._output_helper.info( + f"The vulnerability count is {open_vulnerabilities} (below threshold)" + ) + return None + + def verify_application(self): + """Run all configured checks, marking the step failed if any of them fail.""" + if self._session_metadata: + failures = [self.verify_session_metadata_vulnerabilities()] + else: + failures = [self.verify_vulnerabilities()] + + if self._route_coverage_threshold is not None: + failures.append(self.verify_route_coverage()) + + failures = [failure for failure in failures if failure] + if len(failures) == 1: + self._output_helper.set_failed(failures[0]) + elif failures: + for failure in failures: + self._output_helper.error(failure) + self._output_helper.set_failed( + f"Contrast verify gate fails - {len(failures)} checks failed" + ) diff --git a/tests/test_input_helper.py b/tests/test_input_helper.py index 8f146a4..a3fb056 100644 --- a/tests/test_input_helper.py +++ b/tests/test_input_helper.py @@ -38,6 +38,28 @@ def test_severities_validation(self): ["CRITICAL", "HIGH", "MEDIUM", "LOW", "NOTE"], ) + def test_parse_session_metadata(self): + self.assertEqual(InputHelper.parse_session_metadata(None), {}) + self.assertEqual(InputHelper.parse_session_metadata(""), {}) + self.assertEqual( + InputHelper.parse_session_metadata( + "branchName=main, commitHash = abc123,buildNumber=42" + ), + {"branchName": "main", "commitHash": "abc123", "buildNumber": "42"}, + ) + self.assertEqual( + InputHelper.parse_session_metadata( + "branchName=feature/a=b\n committer=Jane Doe\n\n" + ), + {"branchName": "feature/a=b", "committer": "Jane Doe"}, + ) + + def test_parse_session_metadata_invalid(self): + for invalid in ["branchName", "=main", "branchName=", "a=1,a=2"]: + with self.subTest(invalid=invalid): + with self.assertRaises(ValueError): + InputHelper.parse_session_metadata(invalid) + def test_debug_environment_variable_enabled(self): """Test OutputHelper initialization when DEBUG environment variable is set.""" # Ensure DEBUG is set and GITHUB_ACTIONS is not diff --git a/tests/test_session_metadata.py b/tests/test_session_metadata.py new file mode 100644 index 0000000..df6a5a6 --- /dev/null +++ b/tests/test_session_metadata.py @@ -0,0 +1,362 @@ +import contextlib +import io +import os +import unittest + +import responses +from responses import matchers + +from contrastverify import ContrastVerifyAction + +BASE_URL = "https://apptwo.contrastsecurity.com/api/ng/anOrgId/" +METADATA_FILTERS_URL = f"{BASE_URL}metadata/session/verifier_app_uuid/filters" +TRACES_FILTER_URL = f"{BASE_URL}traces/verifier_app_uuid/filter" +ROUTE_FILTER_URL = f"{BASE_URL}applications/verifier_app_uuid/route/filter" +ROUTE_URL = f"{BASE_URL}applications/verifier_app_uuid/route" +SECURITY_CHECKS_URL = f"{BASE_URL}securityChecks" + + +class SessionMetadataTestCase(unittest.TestCase): + def setUp(self): + os.environ["GITHUB_ACTIONS"] = "false" + self._matchers = [ + matchers.header_matcher( + { + "Accept": "application/json", + "Content-Type": "application/json", + "Api-Key": "An_Api_Key", + "Authorization": "Base64Header", + } + ), + ] + + def create_action(self, **kwargs): + args = { + "app_id": None, + "app_name": "VerifierTest", + "base_url": BASE_URL, + "build_number": "", + "contrast_api_key": "An_Api_Key", + "contrast_authorization": "Base64Header", + "fail_threshold": 0, + "job_start_time": None, + "severities": ["CRITICAL", "HIGH"], + "session_metadata": {"branchName": "main", "commitHash": "abc123"}, + } + args.update(kwargs) + return ContrastVerifyAction(**args) + + def add_common_responses(self): + responses.add( + responses.GET, + f"{BASE_URL}applications/name?filterText=VerifierTest", + json={ + "applications": [ + {"name": "VerifierTest", "app_id": "verifier_app_uuid"} + ] + }, + ) + responses.add( + responses.GET, + METADATA_FILTERS_URL, + json={ + "success": True, + "filters": [ + { + "id": "11", + "label": "Branch Name", + "agentLabel": "branchName", + "values": [{"value": "main", "count": 3}], + }, + # older TeamServer versions may not return agentLabel, so display label is matched + { + "id": "12", + "label": "Commit Hash", + "values": [{"value": "abc123", "count": 3}], + }, + ], + }, + match=self._matchers, + ) + + def add_traces_filter_response(self, count, body): + responses.add( + responses.POST, + TRACES_FILTER_URL, + json={"success": True, "count": count, "traces": []}, + match=[ + *self._matchers, + matchers.query_param_matcher({"expand": "skip_links", "limit": "1"}), + matchers.json_params_matcher(body), + ], + ) + + def run_verify(self, action): + out = io.StringIO() + exit_code = None + with contextlib.redirect_stdout(out): + try: + action.verify_application() + except SystemExit as e: + exit_code = e.code + return exit_code, out.getvalue() + + @responses.activate + def test_session_metadata_vulnerabilities_below_threshold(self): + self.add_common_responses() + self.add_traces_filter_response( + 0, + { + "quickFilter": "OPEN", + "severities": ["CRITICAL", "HIGH"], + "metadataFilters": [ + {"fieldID": 11, "values": ["main"]}, + {"fieldID": 12, "values": ["abc123"]}, + ], + }, + ) + + exit_code, output = self.run_verify(self.create_action()) + + self.assertIsNone(exit_code) + self.assertIn( + "Session metadata provided [branchName=main, commitHash=abc123]", output + ) + self.assertIn("The vulnerability count is 0 (below threshold)", output) + # job outcome policies must not be checked when session metadata is provided + self.assertFalse( + any(call.request.url == SECURITY_CHECKS_URL for call in responses.calls) + ) + + @responses.activate + def test_session_metadata_vulnerabilities_above_threshold_with_filters(self): + self.add_common_responses() + self.add_traces_filter_response( + 5, + { + "quickFilter": "OPEN", + "severities": ["CRITICAL"], + "metadataFilters": [ + {"fieldID": 11, "values": ["main"]}, + {"fieldID": 12, "values": ["abc123"]}, + ], + "appVersionTags": ["123"], + "startDate": 1000, + "timestampFilter": "FIRST", + }, + ) + + exit_code, output = self.run_verify( + self.create_action( + build_number="123", + job_start_time=1000, + severities=["CRITICAL"], + fail_threshold=2, + ) + ) + + self.assertEqual(exit_code, 1) + self.assertIn( + "The vulnerability count is 5 - Contrast verify gate fails as this is above threshold (threshold allows 2)", + output, + ) + + @responses.activate + def test_session_metadata_unknown_field_checks_whole_application(self): + self.add_common_responses() + # no metadataFilters, so all open vulnerabilities in the application are counted + self.add_traces_filter_response( + 3, {"quickFilter": "OPEN", "severities": ["CRITICAL", "HIGH"]} + ) + + exit_code, output = self.run_verify( + self.create_action(session_metadata={"repository": "my-repo"}) + ) + + self.assertEqual(exit_code, 1) + self.assertIn( + "Session metadata repository=my-repo was not found for this application, checks will consider the whole application instead", + output, + ) + self.assertIn( + "The vulnerability count is 3 - Contrast verify gate fails as this is above threshold (threshold allows 0)", + output, + ) + + @responses.activate + def test_session_metadata_unknown_value_checks_whole_application(self): + self.add_common_responses() + self.add_traces_filter_response( + 0, {"quickFilter": "OPEN", "severities": ["CRITICAL", "HIGH"]} + ) + + exit_code, output = self.run_verify( + self.create_action( + session_metadata={"branchName": "feature-x", "commitHash": "abc123"} + ) + ) + + self.assertIsNone(exit_code) + self.assertIn( + "Session metadata branchName=feature-x was not found for this application, checks will consider the whole application instead", + output, + ) + self.assertIn("The vulnerability count is 0 (below threshold)", output) + # job outcome policies are still not used when session metadata is provided + self.assertFalse( + any(call.request.url == SECURITY_CHECKS_URL for call in responses.calls) + ) + + @responses.activate + def test_route_coverage_with_session_metadata_meets_threshold(self): + self.add_common_responses() + self.add_traces_filter_response( + 0, + { + "quickFilter": "OPEN", + "severities": ["CRITICAL", "HIGH"], + "metadataFilters": [ + {"fieldID": 11, "values": ["main"]}, + {"fieldID": 12, "values": ["abc123"]}, + ], + }, + ) + responses.add( + responses.POST, + ROUTE_FILTER_URL, + json={"success": True, "count": 4, "exercisedCount": 3, "routes": []}, + match=[ + *self._matchers, + matchers.query_param_matcher({"expand": "skip_links"}), + matchers.json_params_matcher( + { + "metadata": [ + {"label": "Branch Name", "values": ["main"]}, + {"label": "Commit Hash", "values": ["abc123"]}, + ] + } + ), + ], + ) + + exit_code, output = self.run_verify( + self.create_action(route_coverage_threshold=75) + ) + + self.assertIsNone(exit_code) + self.assertIn( + "Route coverage for session metadata [branchName=main, commitHash=abc123] is 75.00% (3 of 4 routes exercised) (meets threshold of 75%)", + output, + ) + + @responses.activate + def test_route_coverage_and_vulnerabilities_both_fail(self): + self.add_common_responses() + self.add_traces_filter_response( + 1, + { + "quickFilter": "OPEN", + "severities": ["CRITICAL", "HIGH"], + "metadataFilters": [{"fieldID": 11, "values": ["main"]}], + }, + ) + responses.add( + responses.POST, + ROUTE_FILTER_URL, + json={ + "success": True, + "routes": [ + {"status": "EXERCISED", "exercised": 1700000000000}, + {"status": "DISCOVERED", "exercised": None}, + {"status": "DISCOVERED", "exercised": None}, + ], + }, + match=self._matchers, + ) + + exit_code, output = self.run_verify( + self.create_action( + session_metadata={"branchName": "main"}, + route_coverage_threshold=50, + ) + ) + + self.assertEqual(exit_code, 1) + self.assertIn( + "The vulnerability count is 1 - Contrast verify gate fails", output + ) + self.assertIn( + "Route coverage for session metadata [branchName=main] is 33.33% (1 of 3 routes exercised) - Contrast verify gate fails as this is below threshold (threshold requires 50%)", + output, + ) + self.assertIn("Contrast verify gate fails - 2 checks failed", output) + + @responses.activate + def test_route_coverage_without_session_metadata(self): + self.add_common_responses() + responses.add( + responses.POST, + SECURITY_CHECKS_URL, + json={"security_check": {"result": True}}, + match=self._matchers, + ) + responses.add( + responses.GET, + ROUTE_URL, + json={"success": True, "count": 0, "exercised_count": 0, "routes": []}, + match=[ + *self._matchers, + matchers.query_param_matcher({"expand": "skip_links"}), + ], + ) + + exit_code, output = self.run_verify( + self.create_action(session_metadata=None, route_coverage_threshold=10) + ) + + self.assertEqual(exit_code, 1) + self.assertIn("Step passes matching policy", output) + self.assertIn("No routes were found", output) + self.assertIn( + "Route coverage is 0.00% (0 of 0 routes exercised) - Contrast verify gate fails as this is below threshold (threshold requires 10%)", + output, + ) + + @responses.activate + def test_route_coverage_unknown_metadata_value_checks_whole_application(self): + self.add_common_responses() + self.add_traces_filter_response( + 0, {"quickFilter": "OPEN", "severities": ["CRITICAL", "HIGH"]} + ) + responses.add( + responses.GET, + ROUTE_URL, + json={"success": True, "count": 4, "exercisedCount": 1}, + match=[ + *self._matchers, + matchers.query_param_matcher({"expand": "skip_links"}), + ], + ) + + exit_code, output = self.run_verify( + self.create_action( + session_metadata={"branchName": "feature-x"}, + route_coverage_threshold=20, + ) + ) + + self.assertIsNone(exit_code) + # the warning is only logged once, even though both checks use session metadata + self.assertEqual( + output.count("Session metadata branchName=feature-x was not found"), 1 + ) + self.assertIn( + "Route coverage is 25.00% (1 of 4 routes exercised) (meets threshold of 20%)", + output, + ) + self.assertFalse( + any( + (call.request.url or "").startswith(ROUTE_FILTER_URL) + for call in responses.calls + ) + ) diff --git a/tests/test_verify.py b/tests/test_verify.py index 4140453..63e63c1 100644 --- a/tests/test_verify.py +++ b/tests/test_verify.py @@ -53,6 +53,12 @@ def setUp(self): "CONTRAST_FAIL_THRESHOLD", "CONTRAST_BUILD_NUMBER", "CONTRAST_CA_FILE", + "SESSION_METADATA", + "INPUT_SESSIONMETADATA", + "CONTRAST_SESSION_METADATA", + "ROUTE_COVERAGE_THRESHOLD", + "INPUT_ROUTECOVERAGETHRESHOLD", + "CONTRAST_ROUTE_COVERAGE_THRESHOLD", ] for var in env_vars_to_clear: if var in os.environ: @@ -275,6 +281,56 @@ def test_validate_inputs_invalid_job_start_time(self): self.assertEqual(cm.exception.code, 1) + def _set_required_inputs(self): + os.environ["API_KEY"] = "test_api_key" + os.environ["ORG_ID"] = "test_org_id" + os.environ["AUTH_HEADER"] = "test_auth_header" + os.environ["APP_ID"] = "test_app_id" + + def test_validate_inputs_session_metadata_defaults(self): + """Test validate_inputs defaults when session metadata and route coverage are not set.""" + self._set_required_inputs() + + config = verify.validate_inputs(OutputHelper()) + + self.assertEqual(config["SESSION_METADATA"], {}) + self.assertNotIn("ROUTE_COVERAGE_THRESHOLD", config) + + def test_validate_inputs_with_session_metadata_and_route_coverage(self): + """Test validate_inputs with session metadata and route coverage threshold.""" + self._set_required_inputs() + os.environ["INPUT_SESSIONMETADATA"] = "branchName=main,commitHash=abc123" + os.environ["INPUT_ROUTECOVERAGETHRESHOLD"] = "75.5%" + + config = verify.validate_inputs(OutputHelper()) + + self.assertEqual( + config["SESSION_METADATA"], {"branchName": "main", "commitHash": "abc123"} + ) + self.assertEqual(config["ROUTE_COVERAGE_THRESHOLD"], 75.5) + + def test_validate_inputs_invalid_session_metadata(self): + """Test validate_inputs fails when session metadata is malformed.""" + self._set_required_inputs() + os.environ["SESSION_METADATA"] = "branchName" + + with self.assertRaises(SystemExit) as cm: + verify.validate_inputs(OutputHelper()) + + self.assertEqual(cm.exception.code, 1) + + def test_validate_inputs_invalid_route_coverage_threshold(self): + """Test validate_inputs fails when route coverage threshold is not a valid percentage.""" + for invalid in ["abc", "-1", "101"]: + with self.subTest(invalid=invalid): + self._set_required_inputs() + os.environ["ROUTE_COVERAGE_THRESHOLD"] = invalid + + with self.assertRaises(SystemExit) as cm: + verify.validate_inputs(OutputHelper()) + + self.assertEqual(cm.exception.code, 1) + def test_validate_inputs_empty_string_values(self): """Test validate_inputs handles empty string values correctly.""" os.environ["API_KEY"] = "" diff --git a/verify.py b/verify.py index 50d4f40..8d344f9 100644 --- a/verify.py +++ b/verify.py @@ -59,6 +59,23 @@ def validate_inputs(output_helper: OutputHelper): except ValueError: errors.append("jobStartTime (must be a number)") + try: + config["SESSION_METADATA"] = InputHelper.parse_session_metadata( + InputHelper.get_input("SESSION_METADATA") + ) + except ValueError as e: + errors.append(f"sessionMetadata ({e})") + + route_coverage_threshold = InputHelper.get_input("ROUTE_COVERAGE_THRESHOLD") + if route_coverage_threshold is not None and route_coverage_threshold != "": + try: + threshold = float(route_coverage_threshold.strip().rstrip("%")) + if not 0 <= threshold <= 100: + raise ValueError() + config["ROUTE_COVERAGE_THRESHOLD"] = threshold + except ValueError: + errors.append("routeCoverageThreshold (must be a number from 0 to 100)") + if len(errors) != 0: output_helper.error( f'Missing required inputs: {", ".join(errors)}, please see documentation for correct usage.' @@ -99,6 +116,8 @@ def validate_inputs(output_helper: OutputHelper): config["SEVERITIES"], output_helper, cert_file, + session_metadata=config.get("SESSION_METADATA"), + route_coverage_threshold=config.get("ROUTE_COVERAGE_THRESHOLD"), ) action.validate_connection() action.validate_organization()