Skip to content

AIML-358: Fix session metadata filtering 400 Bad Request error - #65

Merged
ChrisEdwards merged 1 commit into
mainfrom
AIML-358-fix-session-metadata-filtering
Jan 9, 2026
Merged

ChrisEdwards merged 1 commit into
mainfrom
AIML-358-fix-session-metadata-filtering

Conversation

@ChrisEdwards

Copy link
Copy Markdown
Collaborator

Why

The search_app_vulnerabilities tool was failing with HTTP 400 Bad Request errors when using session metadata filtering (sessionMetadataName and sessionMetadataValue parameters).

Root cause: The TeamServer API requires numeric field IDs for metadata filtering (e.g., "fieldID": "87"), but the tool was passing human-readable field names (e.g., "fieldID": "branch").

This blocked AI agents from using a key feature for filtering vulnerabilities by session metadata like branch name, commit hash, or build ID.

What

This PR:

  1. Fixes session metadata filtering - Resolves field names to numeric IDs before making API calls
  2. Migrates to POST endpoints - Uses /traces/{appId}/filter and /orgtraces/filter POST endpoints with TraceFilterBody instead of deprecated GET endpoints with query parameters
  3. Fixes tracked/untracked filtering - The old TraceFilterForm defaulted to tracked=true, filtering out untracked vulnerabilities. The new TraceFilterBody uses primitive defaults (false, false) meaning "return all"
  4. Adds comprehensive test coverage - Unit tests verify SDK communication contracts, integration tests verify real API behavior

How

1. Session Metadata Field Resolution (SearchAppVulnerabilitiesTool.java)

Added resolveSessionMetadataFieldId() method that:

  • Calls getSessionMetadataForApplication() API to get available metadata fields
  • Finds the field with matching label (case-insensitive)
  • Returns the numeric ID or throws a clear error if not found
private String resolveSessionMetadataFieldId(ContrastSDK sdk, String orgId, String appId, String fieldName) {
    var metadata = sdk.getSessionMetadataForApplication(orgId, appId, null);
    return metadata.getFilters().stream()
        .filter(group -> group.getLabel().equalsIgnoreCase(fieldName))
        .findFirst()
        .map(group -> group.getId())
        .orElse(null);
}

2. POST Endpoint Migration (SDKExtension.java)

Added two new methods using body-based filtering:

  • getTraces() - For app-scoped vulnerability search
  • getTracesInOrg() - For org-wide vulnerability search

These use TraceFilterBody which has the correct primitive defaults for tracked/untracked.

3. Extended Filter Body (ExtendedTraceFilterBody.java)

New helper class that:

  • Copies all base filters from TraceFilterBody
  • Adds session-specific parameters (agentSessionId, metadataFilters)
  • Uses already-resolved numeric field IDs

4. Test Refactoring

Refactored tests to mock at the SDK boundary (HTTP layer) instead of internal SDK methods:

  • mockSdkWithTracesResponse() - Mocks makeRequestWithBody() to return JSON responses
  • TracesJsonFixture - Provides JSON fixtures for test responses
  • Contract verification tests ensure correct parameters are passed to the SDK

Step-by-Step Walkthrough

SDK Layer Changes

  1. SDKExtension.java - Added getTraces() and getTracesInOrg() methods

    • Line 344-370: getTraces() for app-scoped search with POST body
    • Line 381-407: getTracesInOrg() for org-wide search with POST body
    • Line 495-509: toExpandString() helper for expand query parameter
  2. ExtendedTraceFilterBody.java (new file)

    • Extends TraceFilterBody with session-aware factory method
    • fromWithSession() copies base filters and adds session params
    • Accepts already-resolved numeric field IDs

Tool Layer Changes

  1. SearchAppVulnerabilitiesTool.java

    • Line 180-186: Routes to appropriate execution method based on session filtering
    • Line 188-229: executeWithServerSidePagination() - non-session path using POST
    • Line 231-320: executeWithInMemorySessionFiltering() - session path with field resolution
    • Line 512-535: resolveSessionMetadataFieldId() - resolves field name to numeric ID
  2. SearchVulnerabilitiesTool.java

    • Line 149-165: Migrated to POST endpoint via SDKExtension.getTracesInOrg()

Params Layer Changes

  1. VulnerabilityFilterParams.java

    • Line 116-139: toTraceFilterBody() replaces deprecated toTraceFilterForm()
    • Note: tracked/untracked NOT set - primitive defaults return all vulns
  2. SearchAppVulnerabilitiesParams.java

    • Line 152-174: toTraceFilterBody() for base filters
    • Line 183-203: toTraceFilterBodyWithSessionId() adds session params

Test Changes

  1. SearchAppVulnerabilitiesToolTest.java

    • Line 63-91: Helper methods for SDK mocking
    • Line 210-289: Contract verification tests (verify correct params sent to SDK)
    • Tests now mock at HTTP layer instead of SDK internals
  2. SearchVulnerabilitiesToolTest.java

    • Similar refactoring to mock at SDK boundary
    • Contract tests verify POST body contents
  3. TracesJsonFixture.java (new file)

    • JSON test fixtures for trace responses
    • singleTrace(), emptyTraces(), tracesWithTotal(), etc.
  4. ExtendedTraceFilterBodyTest.java (new file)

    • Unit tests for the new helper class
    • Verifies filter copying and session parameter handling
  5. SearchAppVulnerabilitiesToolIT.java

    • Line 347-407: Integration test verifying session metadata filtering works
    • Line 409-449: Test verifying error for invalid field names

Testing

Unit Tests

  • 584 tests passing (3.9s)
  • Contract tests verify SDK communication:
    • should_pass_resolved_field_id_to_sdk - verifies numeric ID sent
    • should_return_error_when_field_name_not_found - verifies clear error message
    • should_resolve_field_name_case_insensitively - verifies case-insensitive matching

Integration Tests

  • searchAppVulnerabilities_should_support_sessionMetadataName_filter - verifies no 400 error
  • searchAppVulnerabilities_should_return_error_for_invalid_sessionMetadataName - verifies error handling

Manual Testing

  • Verified with real TeamServer that session metadata filtering no longer returns 400 Bad Request
  • Confirmed both tracked and untracked vulnerabilities are now returned (fixing the hidden default filter bug)

Files Changed: 15 files (+1,163 / -190)

The session metadata filtering feature was returning 400 Bad Request because
the SDK was sending string field names (e.g., "branch") instead of numeric
IDs (e.g., "87") that TeamServer expects.

- Add ExtendedTraceFilterBody with fromWithSession() factory method
- Add resolveSessionMetadataFieldId() to look up numeric ID from field name
- Return user-friendly error if field name not found
- Update tests to mock session metadata resolution

@JacobMagesHaskinsContrast JacobMagesHaskinsContrast left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

One small idea. Otherwise, I think it looks ok

@ChrisEdwards
ChrisEdwards merged commit 126c368 into main Jan 9, 2026
4 checks passed
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.

2 participants