Repository navigation
AIML-239 Part 4: Fix review issues and bugs from AIML-239 implementation #38
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 7 commits
bf84d86
238a391
a3a9e72
51bb7ec
488c992
0f20a9d
9425c8b
7de2cbf
65af643
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||
|---|---|---|---|---|
|
|
@@ -31,13 +31,15 @@ | |||
| import com.contrast.labs.ai.mcp.contrast.sdkextension.data.sca.LibraryObservation; | ||||
| import com.contrast.labs.ai.mcp.contrast.utils.PaginationHandler; | ||||
| import com.contrastsecurity.http.TraceFilterForm; | ||||
| import com.contrastsecurity.models.EventResource; | ||||
| import com.contrastsecurity.models.MetadataFilterResponse; | ||||
| import com.contrastsecurity.models.MetadataItem; | ||||
| import com.contrastsecurity.models.Rules; | ||||
| import com.contrastsecurity.models.SessionMetadata; | ||||
| import com.contrastsecurity.models.Stacktrace; | ||||
| import com.contrastsecurity.models.TraceFilterBody; | ||||
| import com.contrastsecurity.models.Trace; | ||||
| import com.contrastsecurity.models.Traces; | ||||
| import com.contrastsecurity.sdk.ContrastSDK; | ||||
| import java.io.IOException; | ||||
| import java.util.ArrayList; | ||||
| import java.util.EnumSet; | ||||
|
|
@@ -101,21 +103,32 @@ public Vulnerability getVulnerabilityById( | |||
| log.debug("ContrastSDK initialized with host: {}", hostName); | ||||
|
|
||||
| try { | ||||
| var trace = | ||||
| contrastSDK.getTraces(orgID, appID, new TraceFilterBody()).getTraces().stream() | ||||
| .filter(t -> t.getUuid().equalsIgnoreCase(vulnID)) | ||||
| .findFirst() | ||||
| .orElseThrow(); | ||||
| // Use expand to include application, environments, and session metadata | ||||
| var expand = | ||||
| EnumSet.of( | ||||
| TraceFilterForm.TraceExpandValue.APPLICATION, | ||||
| TraceFilterForm.TraceExpandValue.SERVER_ENVIRONMENTS, | ||||
| TraceFilterForm.TraceExpandValue.SESSION_METADATA); | ||||
| var trace = contrastSDK.getTrace(orgID, appID, vulnID, expand); | ||||
| if (trace == null) { | ||||
| throw new IOException( | ||||
| String.format( | ||||
| "Vulnerability API returned null for vulnID %s in app %s. Please check API" | ||||
| + " connectivity, permissions, and that the vulnerability exists.", | ||||
| vulnID, appID)); | ||||
| } | ||||
| log.debug("Found trace with title: {} and rule: {}", trace.getTitle(), trace.getRule()); | ||||
|
|
||||
| var recommendationResponse = contrastSDK.getRecommendation(orgID, vulnID); | ||||
| var requestResponse = contrastSDK.getHttpRequest(orgID, vulnID); | ||||
| var eventSummaryResponse = contrastSDK.getEventSummary(orgID, vulnID); | ||||
|
|
||||
| var triggerEvent = | ||||
| eventSummaryResponse.getEvents().stream() | ||||
| .filter(e -> e.getType().equalsIgnoreCase("trigger")) | ||||
| .findFirst(); | ||||
| (eventSummaryResponse != null && eventSummaryResponse.getEvents() != null) | ||||
| ? eventSummaryResponse.getEvents().stream() | ||||
| .filter(e -> e.getType().equalsIgnoreCase("trigger")) | ||||
| .findFirst() | ||||
| : Optional.<EventResource>empty(); | ||||
|
|
||||
| var stackTraces = new ArrayList<String>(); | ||||
| if (triggerEvent.isPresent()) { | ||||
|
|
@@ -154,13 +167,18 @@ public Vulnerability getVulnerabilityById( | |||
| } | ||||
|
|
||||
| String httpRequestText = null; | ||||
| if (requestResponse.getHttpRequest() != null) { | ||||
| if (requestResponse != null && requestResponse.getHttpRequest() != null) { | ||||
| httpRequestText = requestResponse.getHttpRequest().getText(); | ||||
| } | ||||
|
|
||||
| String recommendationText = null; | ||||
| if (recommendationResponse != null && recommendationResponse.getRecommendation() != null) { | ||||
| recommendationText = recommendationResponse.getRecommendation().getText(); | ||||
| } | ||||
|
|
||||
| var context = | ||||
| VulnerabilityContext.builder() | ||||
| .recommendation(recommendationResponse.getRecommendation().getText()) | ||||
| .recommendation(recommendationText) | ||||
| .stackLibs(stackLibs) | ||||
| .libraries(new ArrayList<>(libsToReturn)) // Convert Set to List | ||||
| .httpRequest(httpRequestText) | ||||
|
|
@@ -458,7 +476,7 @@ public PaginatedResponse<VulnLight> searchVulnerabilities( | |||
| required = false) | ||||
| String vulnTags) | ||||
| throws IOException { | ||||
| log.info( | ||||
| log.debug( | ||||
| "Searching org vulnerabilities - page: {}, pageSize: {}, filters: severities={}," | ||||
| + " statuses={}, vulnTypes={}, environments={}, lastSeenAfter={}, lastSeenBefore={}," | ||||
| + " vulnTags={}", | ||||
|
|
@@ -653,15 +671,15 @@ public PaginatedResponse<VulnLight> searchAppVulnerabilities( | |||
| if (!StringUtils.hasText(appId)) { | ||||
| var errorMessage = "appId parameter is required"; | ||||
| log.error("Validation error: {}", errorMessage); | ||||
| return PaginatedResponse.error(1, 50, errorMessage); | ||||
| return PaginatedResponse.error(1, PaginationParams.DEFAULT_PAGE_SIZE, errorMessage); | ||||
| } | ||||
|
|
||||
| // Validate incomplete parameters: sessionMetadataValue without sessionMetadataName | ||||
| if (StringUtils.hasText(sessionMetadataValue) && !StringUtils.hasText(sessionMetadataName)) { | ||||
| var errorMessage = | ||||
| "sessionMetadataValue requires sessionMetadataName. Both must be provided together."; | ||||
| log.error("Validation error: {}", errorMessage); | ||||
| return PaginatedResponse.error(1, 50, errorMessage); | ||||
| return PaginatedResponse.error(1, PaginationParams.DEFAULT_PAGE_SIZE, errorMessage); | ||||
| } | ||||
|
|
||||
| // Parse and validate inputs | ||||
|
|
@@ -711,42 +729,48 @@ public PaginatedResponse<VulnLight> searchAppVulnerabilities( | |||
| } | ||||
|
|
||||
| // Make API call - always use app-specific endpoint | ||||
| // Note: When using session filtering, we get all results (no SDK pagination) | ||||
| // because we need to filter in-memory before paginating | ||||
| Traces traces; | ||||
| // Note: When using session filtering, we fetch ALL pages because we need | ||||
| // the complete dataset before filtering in-memory | ||||
| Traces traces = null; | ||||
| List<VulnLight> vulnerabilities; | ||||
|
|
||||
| // Always set expand values for session metadata | ||||
| filterForm.setExpand( | ||||
| EnumSet.of( | ||||
| TraceFilterForm.TraceExpandValue.SESSION_METADATA, | ||||
| TraceFilterForm.TraceExpandValue.SERVER_ENVIRONMENTS, | ||||
| TraceFilterForm.TraceExpandValue.APPLICATION)); | ||||
|
|
||||
| if (needsInMemorySessionFiltering) { | ||||
| // Get all results for in-memory filtering (no SDK pagination, no limit/offset) | ||||
| filterForm.setExpand( | ||||
| EnumSet.of( | ||||
| TraceFilterForm.TraceExpandValue.SESSION_METADATA, | ||||
| TraceFilterForm.TraceExpandValue.SERVER_ENVIRONMENTS, | ||||
| TraceFilterForm.TraceExpandValue.APPLICATION)); | ||||
| traces = contrastSDK.getTraces(orgID, appId, filterForm); | ||||
| // Fetch ALL pages for in-memory filtering (iterates through SDK pagination) | ||||
| var allTraces = fetchAllTracesForSessionFiltering(contrastSDK, orgID, appId, filterForm); | ||||
|
|
||||
| if (allTraces.isEmpty()) { | ||||
| log.debug("No traces found for app {} (all pages fetched)", appId); | ||||
| } | ||||
|
|
||||
| // Convert to VulnLight directly from the list | ||||
| vulnerabilities = allTraces.stream().map(vulnerabilityMapper::toVulnLight).toList(); | ||||
| } else { | ||||
| // Use SDK pagination when no in-memory filtering needed | ||||
| filterForm.setLimit(pagination.limit()); | ||||
| filterForm.setOffset(pagination.offset()); | ||||
| filterForm.setExpand( | ||||
| EnumSet.of( | ||||
| TraceFilterForm.TraceExpandValue.SESSION_METADATA, | ||||
| TraceFilterForm.TraceExpandValue.SERVER_ENVIRONMENTS, | ||||
| TraceFilterForm.TraceExpandValue.APPLICATION)); | ||||
| traces = contrastSDK.getTraces(orgID, appId, filterForm); | ||||
| } | ||||
|
|
||||
| if (traces == null || traces.getTraces() == null) { | ||||
| var errorMsg = | ||||
| String.format( | ||||
| "App-level vulnerability API returned null for app %s. Please check API" | ||||
| + " connectivity and permissions.", | ||||
| appId); | ||||
| log.error(errorMsg); | ||||
| return PaginatedResponse.error(pagination.page(), pagination.pageSize(), errorMsg); | ||||
| } | ||||
| if (traces == null || traces.getTraces() == null) { | ||||
| var errorMsg = | ||||
| String.format( | ||||
| "App-level vulnerability API returned null for app %s. Please check API" | ||||
| + " connectivity and permissions.", | ||||
| appId); | ||||
| log.error(errorMsg); | ||||
| return PaginatedResponse.error(pagination.page(), pagination.pageSize(), errorMsg); | ||||
| } | ||||
|
|
||||
| // Convert to VulnLight | ||||
| var vulnerabilities = | ||||
| traces.getTraces().stream().map(vulnerabilityMapper::toVulnLight).toList(); | ||||
| // Convert to VulnLight | ||||
| vulnerabilities = | ||||
| traces.getTraces().stream().map(vulnerabilityMapper::toVulnLight).toList(); | ||||
| } | ||||
|
|
||||
| // Apply in-memory agent session ID filtering if requested | ||||
| if (agentSessionId != null) { | ||||
|
|
@@ -802,7 +826,9 @@ public PaginatedResponse<VulnLight> searchAppVulnerabilities( | |||
| } | ||||
|
|
||||
| // Apply pagination to in-memory filtered results | ||||
| if (agentSessionId != null || StringUtils.hasText(sessionMetadataName)) { | ||||
| // Use needsInMemorySessionFiltering to determine if we fetched all pages | ||||
| // This handles the case where useLatestSession=true but no sessions were found | ||||
| if (needsInMemorySessionFiltering) { | ||||
| var startIndex = pagination.offset(); | ||||
| var endIndex = Math.min(startIndex + pagination.pageSize(), finalVulns.size()); | ||||
| var pagedVulns = | ||||
|
|
@@ -862,6 +888,59 @@ private List<Metadata> getMetadataFromApp(Application app) { | |||
| return metadata; | ||||
| } | ||||
|
|
||||
| /** | ||||
| * Fetches all traces from the SDK by iterating through all pages. This is needed when in-memory | ||||
| * session filtering is required, because we must have the complete dataset before filtering. | ||||
| * | ||||
| * @param sdk The ContrastSDK instance | ||||
| * @param orgId The organization ID | ||||
| * @param appId The application ID | ||||
| * @param filterForm The filter form (will be modified to set limit/offset for pagination) | ||||
| * @return List of all traces across all pages | ||||
| * @throws IOException If an API error occurs | ||||
| */ | ||||
| private List<Trace> fetchAllTracesForSessionFiltering( | ||||
| ContrastSDK sdk, String orgId, String appId, TraceFilterForm filterForm) throws IOException { | ||||
| final int PAGE_SIZE = 500; | ||||
|
ChrisEdwards marked this conversation as resolved.
Resolved
|
||||
| var allTraces = new ArrayList<Trace>(); | ||||
| int offset = 0; | ||||
|
|
||||
| while (true) { | ||||
| filterForm.setLimit(PAGE_SIZE); | ||||
| filterForm.setOffset(offset); | ||||
|
|
||||
| Traces pageResult; | ||||
| try { | ||||
| pageResult = sdk.getTraces(orgId, appId, filterForm); | ||||
| } catch (Exception e) { | ||||
| throw new IOException("Failed to fetch traces page at offset " + offset, e); | ||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. We may want log statement here.
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This is logged in an upcoming overhaul of exception handling: mcp-contrast/src/main/java/com/contrast/labs/ai/mcp/contrast/utils/ExceptionHandler.java Line 124 in 9d4d202
|
||||
| } | ||||
|
|
||||
| if (pageResult == null | ||||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This could use the apache collections lb to check size or array/list:
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'll do a replace of all these in a single pass before release. |
||||
| || pageResult.getTraces() == null | ||||
| || pageResult.getTraces().isEmpty()) { | ||||
| break; | ||||
| } | ||||
|
|
||||
| allTraces.addAll(pageResult.getTraces()); | ||||
| log.debug( | ||||
| "Fetched {} traces at offset {} (total so far: {})", | ||||
| pageResult.getTraces().size(), | ||||
| offset, | ||||
| allTraces.size()); | ||||
|
|
||||
| // If we got fewer than PAGE_SIZE, we've reached the last page | ||||
| if (pageResult.getTraces().size() < PAGE_SIZE) { | ||||
| break; | ||||
| } | ||||
|
|
||||
| offset += PAGE_SIZE; | ||||
| } | ||||
|
|
||||
| log.debug("Fetched total of {} traces for session filtering", allTraces.size()); | ||||
| return allTraces; | ||||
| } | ||||
|
|
||||
| @Tool( | ||||
| name = "list_vulnerability_types", | ||||
| description = | ||||
|
|
||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,6 +7,7 @@ | |
| import com.contrast.labs.ai.mcp.contrast.sdkextension.data.routecoverage.RouteCoverageResponse; | ||
| import com.contrastsecurity.models.RouteCoverageMetadataLabelValues; | ||
| import java.io.IOException; | ||
| import java.util.Collections; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.ai.tool.annotation.Tool; | ||
| import org.springframework.beans.factory.annotation.Value; | ||
|
|
@@ -61,9 +62,11 @@ public class RouteCoverageService { | |
| + " not exercised) or EXERCISED (received HTTP traffic). All filter parameters are" | ||
| + " truly optional - if none provided (null or empty strings), returns all routes" | ||
| + " across all sessions. Parameters: appId (required), sessionMetadataName" | ||
| + " (optional), sessionMetadataValue (optional). NOTE: sessionMetadataName and" | ||
| + " sessionMetadataValue must be provided together or both omitted - providing" | ||
| + " only one will result in an error. useLatestSession (optional).") | ||
| + " (optional), sessionMetadataValue (optional), useLatestSession (optional). NOTE:" | ||
| + " sessionMetadataName and sessionMetadataValue must be provided together or both" | ||
| + " omitted. IMPORTANT: useLatestSession and sessionMetadataName/Value are mutually" | ||
| + " exclusive - if both are provided, useLatestSession takes precedence and the" | ||
| + " session metadata filter is ignored.") | ||
| public RouteCoverageResponse getRouteCoverage( | ||
| String appId, | ||
| String sessionMetadataName, | ||
|
|
@@ -87,6 +90,17 @@ public RouteCoverageResponse getRouteCoverage( | |
| throw new IllegalArgumentException(errorMsg); | ||
| } | ||
|
|
||
| // Warn if mutually exclusive parameters are both provided | ||
| if (Boolean.TRUE.equals(useLatestSession) && StringUtils.hasText(sessionMetadataName)) { | ||
| log.atWarn() | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Why the spring structured logging use here but not other log statements? Just to get the key/value logging?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Seems so. This class is getting overhauled soon for consistent handling of validation. This will go away. AIML-303. Its in flight. New rules will apply. If you provide conflicting params it will warn the user in the response directly, no need to log. This is an intermediate state to get there. |
||
| .setMessage( | ||
| "Both useLatestSession and sessionMetadataName provided - these are mutually" | ||
| + " exclusive. Using useLatestSession and ignoring sessionMetadataName/Value.") | ||
| .addKeyValue("sessionMetadataName", sessionMetadataName) | ||
| .addKeyValue("sessionMetadataValue", sessionMetadataValue) | ||
| .log(); | ||
| } | ||
|
|
||
| // Initialize SDK | ||
| var contrastSDK = | ||
| SDKHelper.getSDK(hostName, apiKey, serviceKey, userName, httpProxyHost, httpProxyPort); | ||
|
|
@@ -133,6 +147,20 @@ public RouteCoverageResponse getRouteCoverage( | |
| // Call SDK to get route coverage | ||
| log.debug("Fetching route coverage data for application ID: {}", appId); | ||
| var response = sdkExtension.getRouteCoverage(orgID, appId, requestExtended); | ||
|
|
||
| // Defensive null checks - API may return null on errors or permission issues | ||
| if (response == null) { | ||
| log.error("Route coverage API returned null for app {}", appId); | ||
| var errorResponse = new RouteCoverageResponse(); | ||
| errorResponse.setSuccess(false); | ||
| return errorResponse; | ||
| } | ||
|
|
||
| if (response.getRoutes() == null) { | ||
| log.warn("No routes returned for app {} - returning empty response", appId); | ||
| response.setRoutes(Collections.emptyList()); | ||
| } | ||
|
|
||
| log.debug("Found {} routes for application", response.getRoutes().size()); | ||
|
|
||
| // Fetch route details for each route | ||
|
|
||
Uh oh!
There was an error while loading. Please reload this page.