Skip to content

Conversation

@immortal71
Copy link

@immortal71 immortal71 commented Jan 6, 2026

Description

This PR fixes the IndexError bug reported in #1199 when parsing malformed --modules-extra-args without an equals sign.

Problem

The --modules-extra-args parser in nettacker/core/arg_parser.py would crash with an IndexError when users provided malformed arguments without an = sign, giving a cryptic error message with no guidance.

Example crash:

python nettacker.py -i owasp.org -m port_scan --modules-extra-args "api_key"
# IndexError: list index out of range

Root Cause

The code used args.split("=")[1] and args.split("=")[0] without validating that the split produced at least 2 elements. When a user provided key (without =), split("=") returned ["key"], and accessing index [1] raised IndexError.

Solution

Added comprehensive input validation and improved error handling:

  1. Check that each argument contains an = sign before splitting
  2. Validate that keys are not empty (reject inputs like "=value" or " =value")
  3. Provide clear, internationalized error messages when validation fails
  4. Use split("=", 1) with maxsplit to properly handle values that contain = characters
  5. Strip whitespace from keys for better handling

Changes Made

nettacker/core/arg_parser.py (lines 736-765):

  • Added validation: if "=" not in args:
  • Added empty key validation: if not key:
  • Used internationalized error messages with _() function
  • Changed from args.split("=") to args.split("=", 1)
  • Strip whitespace from keys: key = parts[0].strip()
  • Store key and value separately for clarity

nettacker/locale/en.yaml:

  • Added error_modules_extra_args_format message
  • Added error_modules_extra_args_empty_key message

Before (Buggy):

for args in options.modules_extra_args.split("&"):
    value = args.split("=")[1]  # Crashes if no '='
    all_args[args.split("=")[0]] = value

After (Fixed):

for args in options.modules_extra_args.split("&"):
    if "=" not in args:
        die_failure(_("error_modules_extra_args_format").format(args))
    
    parts = args.split("=", 1)  # maxsplit=1 handles values with '='
    key = parts[0].strip()
    value = parts[1]
    
    if not key:
        die_failure(_("error_modules_extra_args_empty_key"))
    
    # ... type conversion logic ...
    all_args[key] = value

Impact

  • Severity: Medium
  • User Experience: Much improved - clear, localized error messages with examples
  • Backward Compatibility: Fully compatible - only adds validation
  • Error Prevention: Catches common user typos/mistakes early
  • Code Quality: Follows project conventions (internationalization, validation)

Example Error Messages (After Fix)

Missing equals sign:

Invalid format for --modules-extra-args: 'api_key'
Expected format: key1=value1&key2=value2
Example: --modules-extra-args "x_api_key=123&xyz_passwd=abc"

Empty key:

Invalid --modules-extra-args: empty key is not allowed
Each argument must be in format: key=value

Fixes #1199

Copilot AI review requested due to automatic review settings January 6, 2026 02:53
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 6, 2026

Summary by CodeRabbit

Release Notes

  • New Features
    • Module extra arguments now support automatic type conversion for values (boolean, integer, float, JSON objects/arrays).
    • Enhanced validation for argument format with clearer error messages and usage examples.

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

Walkthrough

Fixes an IndexError when parsing malformed --modules-extra-args parameters. Adds validation to ensure arguments contain '=' signs, uses maxsplit=1 to preserve '=' in values, validates non-empty keys, and applies type conversion (bool, int, float, JSON) before assignment. Adds two localized error messages.

Changes

Cohort / File(s) Summary
Argument Parser Enhancement
nettacker/core/arg_parser.py
Validates each --modules-extra-args entry contains '='; splits with maxsplit=1 to handle '=' in values; extracts and trims key/value; validates non-empty keys; applies type conversion for boolean, integer, float, and JSON values; assigns converted values to all_args.
Localization Updates
nettacker/locale/en.yaml
Added error_modules_extra_args_format error message with format guidance and example; added error_modules_extra_args_empty_key error message for empty-key validation.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main fix: preventing IndexError when parsing --modules-extra-args without '=' sign.
Description check ✅ Passed The description is comprehensive and directly related to the changeset, explaining the bug, root cause, solution, and impact.
Linked Issues check ✅ Passed The PR fully addresses all objectives from issue #1199: validates '=' presence, provides clear error messages, uses split with maxsplit, rejects empty keys, and preserves type conversion.
Out of Scope Changes check ✅ Passed All changes are scoped to fixing the --modules-extra-args parsing bug; no unrelated modifications detected in the changeset.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0441367 and 55cfd7a.

📒 Files selected for processing (2)
  • nettacker/core/arg_parser.py
  • nettacker/locale/en.yaml
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: Use 4-space indents in Python code
Limit lines to 99 characters (ruff/ruff-format/isort profile=black)
Module and file names should use lower_snake_case
Function and variable names should use lower_snake_case
Class names should use PascalCase
Constants should use UPPER_SNAKE_CASE
Keep functions small and add type hints where practical

Files:

  • nettacker/core/arg_parser.py
nettacker/**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

Add docstrings for public APIs in the nettacker package

Files:

  • nettacker/core/arg_parser.py
nettacker/core/**

📄 CodeRabbit inference engine (AGENTS.md)

Place core libraries under nettacker/core/

Files:

  • nettacker/core/arg_parser.py
🔇 Additional comments (3)
nettacker/core/arg_parser.py (2)

739-750: LGTM! Robust validation for malformed arguments.

The validation logic correctly:

  1. Checks for = before splitting to prevent IndexError
  2. Uses split("=", 1) to preserve = characters in values
  3. Strips whitespace from keys while validating non-empty keys
  4. Uses internationalized error messages as suggested in past reviews

This addresses all objectives from issue #1199.


752-773: Type conversion and assignment logic is correct.

The existing type conversion logic handles booleans, floats, JSON, and integers with appropriate fallbacks. The key change of using the validated key variable (line 773) instead of the original args string correctly stores parsed values.

nettacker/locale/en.yaml (1)

40-41: LGTM! Clear and actionable error messages.

The new locale strings provide helpful context:

  • error_modules_extra_args_format shows the invalid input, expected format, and a concrete example
  • error_modules_extra_args_empty_key explains the constraint clearly

Both messages align with the Copilot suggestions from past reviews and match the usage in arg_parser.py.


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

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes an IndexError bug when users provide malformed --modules-extra-args without an equals sign, and includes an unrelated fix for UnboundLocalError in graph module tests.

Key Changes

  • Added validation to check for '=' character before parsing --modules-extra-args, preventing IndexError
  • Improved error messages to guide users on correct format (though not internationalized)
  • Fixed UnboundLocalError in graph.py tests by adding return statements after die_failure calls

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.

File Description
nettacker/core/arg_parser.py Main fix: validates format and provides clear error messages for malformed --modules-extra-args; uses split("=", 1) to handle values containing '='
nettacker/core/graph.py Unrelated fix: adds return statements after die_failure to prevent UnboundLocalError when mocked in tests
tests/core/test_graph.py Removes xfail markers and adds assertions for None return value now that graph.py functions return properly when die_failure is mocked

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines 748 to 746
parts = args.split("=", 1)
key = parts[0]
value = parts[1]
Copy link

Copilot AI Jan 6, 2026

Choose a reason for hiding this comment

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

Consider adding validation to reject empty keys. Currently, inputs like "=value" or "=" will pass validation since they contain an '=' character, but will result in an empty string as the key. This could cause confusing behavior later. Add a check like:

if not key or not key.strip():
die_failure(...)

Copilot uses AI. Check for mistakes.
Comment on lines 46 to 49
)
except ModuleNotFoundError:
die_failure(_("graph_module_unavailable").format(graph_name))
return
Copy link

Copilot AI Jan 6, 2026

Choose a reason for hiding this comment

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

These changes to graph.py appear to be unrelated to the main purpose of this PR (fixing IndexError in --modules-extra-args parsing). While the fix itself is valid (preventing UnboundLocalError when die_failure is mocked in tests), it should ideally be in a separate PR with its own description and justification. Consider splitting this into a separate PR or documenting why it's included in the PR description.

Copilot uses AI. Check for mistakes.
Comment on lines 741 to 746
die_failure(
f"Invalid format for --modules-extra-args: '{args}'\n"
f"Expected format: key1=value1&key2=value2\n"
f"Example: --modules-extra-args \"x_api_key=123&xyz_passwd=abc\""
)

Copy link

Copilot AI Jan 6, 2026

Choose a reason for hiding this comment

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

The error message should use the internationalization function _() for consistency with the rest of the codebase. Consider adding a localized message key to nettacker/locale/en.yaml (and other language files) and using it here. For example:

In nettacker/locale/en.yaml:
error_modules_extra_args: "Invalid format for --modules-extra-args: '{0}'\nExpected format: key1=value1&key2=value2\nExample: --modules-extra-args "x_api_key=123&xyz_passwd=abc""

Then use:
die_failure(_("error_modules_extra_args").format(args))

Suggested change
die_failure(
f"Invalid format for --modules-extra-args: '{args}'\n"
f"Expected format: key1=value1&key2=value2\n"
f"Example: --modules-extra-args \"x_api_key=123&xyz_passwd=abc\""
)
die_failure(_("error_modules_extra_args").format(args))

Copilot uses AI. Check for mistakes.
- Added validation to check for '=' sign before splitting
- Added validation to reject empty keys (e.g., '=value')
- Used internationalized error messages with _() function
- Added error_modules_extra_args_format and error_modules_extra_args_empty_key to locale
- Used split('=', 1) to properly handle values containing '=' characters
- Strip whitespace from keys
 Fixes issue OWASP#1199
@immortal71 immortal71 force-pushed the fix-indexerror-modules-extra-args branch from 0441367 to 55cfd7a Compare January 6, 2026 03:36
@pUrGe12
Copy link
Contributor

pUrGe12 commented Jan 7, 2026

lgmt. Please run make pre-commit to make the formatting changes

@immortal71
Copy link
Author

@pUrGe12 Can you check now, Is there something else I need to implement or any suggestion for me,
Can you review this ?

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.

IndexError when parsing malformed --modules-extra-args without '=' sign

2 participants