Skip to content

Harden agent arg parsing to avoid accidental key matches and malformed token handling - #24

Open
ANANDHA007 wants to merge 1 commit into
AshutoshIWNL:masterfrom
ANANDHA007:master
Open

ANANDHA007 wants to merge 1 commit into
AshutoshIWNL:masterfrom
ANANDHA007:master

Conversation

@ANANDHA007

@ANANDHA007 ANANDHA007 commented May 22, 2026 •

Copy link
Copy Markdown
Collaborator

refac:

  1. Parsing made strict and Unknown keys are ignored with debug/warn logs
  2. Malformed tokens do not crash agent startup/attach.
  3. Unit tests cover valid, malformed, duplicate, and unknown-key cases.

Summary by Sourcery

Harden agent argument parsing to be strict and resilient to malformed input while centralizing validation logic.

New Features:

  • Introduce a centralized, strict key=value argument parser that supports a fixed set of known keys for agent launch options.

Bug Fixes:

  • Prevent crashes and incorrect option resolution caused by malformed tokens, unknown keys, or partial key matches in agent arguments.
  • Ensure invalid log levels and nonexistent or invalid file/directory paths are rejected with clear errors instead of being silently accepted.

Enhancements:

  • Refactor argument parsing into dedicated validation methods for each option, improving readability and testability.
  • Make log level validation case-insensitive and add basic warning logging for malformed and unknown argument tokens.

Tests:

  • Expand unit tests to cover missing, valid, malformed, duplicate, unknown-key, and invalid-path/log-level scenarios for agent argument parsing.

@sourcery-ai

sourcery-ai Bot commented May 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Refactors agent argument parsing into a strict key=value map-based parser with explicit validation methods, adds handling for malformed/unknown tokens and duplicate keys, and updates unit tests to cover the new behavior and error conditions.

Flow diagram for strict agent argument parsing and validation

flowchart TD
    A[agentArgs string] --> B[parseArgs]
    B --> C[Split by comma into tokens]
    C --> D[For each token]

    D --> E{Empty or null token?}
    E -- Yes --> D
    E -- No --> F[Split token by = into parts]

    F --> G{parts length == 2?}
    G -- No --> H[warn Ignoring malformed token]
    H --> D

    G -- Yes --> I[Trim key and value]
    I --> J{key empty?}
    J -- Yes --> K[warn Ignoring token with empty key]
    K --> D

    J -- No --> L{key in SUPPORTED_KEYS?}
    L -- No --> M[warn Ignoring unknown key]
    M --> D

    L -- Yes --> N{key already in parsed map?}
    N -- Yes --> O[throw IllegalArgumentException Duplicate argument]
    N -- No --> P[parsed.put key,value]
    P --> D

    D -->|All tokens processed| Q[parsed Map<String,String>]

    Q --> R[validateConfigFile]
    Q --> S[validateAgentLogFileDir]
    Q --> T[validateAgentLogLevel]
    Q --> U[validateSmtpProperties]
    Q --> V[validateAgentJarPath]

    R --> W[AgentLaunchOptions]
    S --> W
    T --> W
    U --> W
    V --> W
Loading

File-Level Changes

Change Details Files
Refactor AgentArgsParser to use a strict key=value map with supported-key filtering, duplicate-key detection, and dedicated validation methods for each option.
  • Make AgentArgsParser final with a private constructor and introduce a SUPPORTED_KEYS set for known argument names.
  • Add parseArgs to split raw input into trimmed tokens, enforce key=value format, ignore malformed/empty tokens, warn on unknown keys, and throw on duplicate keys.
  • Replace per-field parse* methods with validate* methods that operate on the parsed map entries for config file, log dir, log level, SMTP properties, and agent JAR path.
  • Tighten filesystem validations for config file, log directory, and agent JAR path, returning null for missing/blank values instead of throwing.
  • Update isValidLogLevel to be null/blank-safe and case-insensitive, and add a temporary warn logger using System.err.
src/main/java/com/asm/mja/args/AgentArgsParser.java
Expand and adjust unit tests to validate new parsing rules, error messages, and log-level semantics.
  • Retain the happy-path test but adapt it to the new parser behavior for fully specified arguments.
  • Add tests to verify unknown keys and malformed tokens are ignored while valid keys are still parsed.
  • Add tests that exercise validation failures for non-existent config files, invalid log directories, and invalid/absent agent JAR paths, with updated exception messages.
  • Add tests to confirm validateAgentLogLevel throws on invalid levels and that isValidLogLevel correctly handles valid, invalid, and null/blank inputs.
src/test/java/com/asm/mja/args/AgentArgsParserTest.java

Possibly linked issues

  • #(not specified): PR refactors AgentArgsParser to strict key=value parsing, ignores unknown/malformed tokens, and adds comprehensive unit tests as requested.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • The new validation methods treat empty-string values as null (e.g., configFile= or agentLogLevel=), which is a behavioral change from the previous implementation that rejected missing values; consider either preserving the old strictness or explicitly documenting/handling empty values as an error.
  • validateAgentLogLevel now accepts case-insensitive values but returns the original string, which may cause inconsistencies downstream (e.g., if consumers expect LogLevel-style upper case); consider normalizing to a canonical form (such as level.name()) before returning.
  • The warn helper currently uses System.err directly; if this parser is used in long-running or production contexts, consider integrating with the existing logging framework or injecting a logger to keep logging behavior consistent and configurable.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The new validation methods treat empty-string values as `null` (e.g., `configFile=` or `agentLogLevel=`), which is a behavioral change from the previous implementation that rejected missing values; consider either preserving the old strictness or explicitly documenting/handling empty values as an error.
- `validateAgentLogLevel` now accepts case-insensitive values but returns the original string, which may cause inconsistencies downstream (e.g., if consumers expect `LogLevel`-style upper case); consider normalizing to a canonical form (such as `level.name()`) before returning.
- The `warn` helper currently uses `System.err` directly; if this parser is used in long-running or production contexts, consider integrating with the existing logging framework or injecting a logger to keep logging behavior consistent and configurable.

## Individual Comments

### Comment 1
<location path="src/test/java/com/asm/mja/args/AgentArgsParserTest.java" line_range="21-28" />
<code_context>
  */
 public class AgentArgsParserTest {

     @Test
     void parseReturnsNullFieldsWhenAgentArgsMissing() {
+
</code_context>
<issue_to_address>
**issue (testing):** Test name suggests duplicate-key behavior, but the body only exercises `validateAgentLogFileDir` and not duplicate argument parsing

This asserts the `validateAgentLogFileDir` error for a non-existent directory, but the name (`parseThrowsForDuplicateKeys`) implies we’re testing `parse` rejecting duplicate keys. That both misleads and leaves `parseArgs`’s duplicate-key behavior untested. Please either rename the test to match its current behavior or, preferably, change it to pass a duplicate key (e.g. `agentLogLevel=INFO,agentLogLevel=DEBUG`) to `AgentArgsParser.parse(...)` and assert the expected `IllegalArgumentException` and message about duplicate arguments.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 21 to 28
@Test
void parseReturnsNullFieldsWhenAgentArgsMissing() {

AgentLaunchOptions options = AgentArgsParser.parse(null);

assertNull(options.getConfigFile());
assertNull(options.getAgentLogFileDir());
assertNull(options.getAgentLogLevel());

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue (testing): Test name suggests duplicate-key behavior, but the body only exercises validateAgentLogFileDir and not duplicate argument parsing

This asserts the validateAgentLogFileDir error for a non-existent directory, but the name (parseThrowsForDuplicateKeys) implies we’re testing parse rejecting duplicate keys. That both misleads and leaves parseArgs’s duplicate-key behavior untested. Please either rename the test to match its current behavior or, preferably, change it to pass a duplicate key (e.g. agentLogLevel=INFO,agentLogLevel=DEBUG) to AgentArgsParser.parse(...) and assert the expected IllegalArgumentException and message about duplicate arguments.

@AshutoshIWNL

Copy link
Copy Markdown
Owner

Follow-up with clean formatting (same requested changes):

Request changes before merge

  1. Centralize parser usage in LoggingBootstrap by consuming AgentArgsParser.parse(...) (or shared parser helpers) instead of local contains(...) parsing.

  2. Fix test parseThrowsForDuplicateKeys in AgentArgsParserTest.

    • It currently validates a missing directory path and does not test duplicate key handling.
    • Replace with a real duplicate-key parse case, e.g. configFile=a,configFile=b should throw Duplicate argument detected: configFile.
  3. Add/adjust LoggingBootstrap tests for malformed, unknown, and partial-match tokens.

    • This verifies no legacy substring-match behavior remains on startup path.

After these updates and green CI, this should be ready to merge.

This branch has not been deployed

No deployments
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