Skip to content

fix: normalize scheme-less HTTP proxy settings#9235

Open
Last-emo-boy wants to merge 1 commit into
AstrBotDevs:masterfrom
Last-emo-boy:fix/8292-proxy-scheme
Open

fix: normalize scheme-less HTTP proxy settings#9235
Last-emo-boy wants to merge 1 commit into
AstrBotDevs:masterfrom
Last-emo-boy:fix/8292-proxy-scheme

Conversation

@Last-emo-boy

@Last-emo-boy Last-emo-boy commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Fixes #8292

Modifications / 改动点

  • Trim the global HTTP proxy setting before exporting it.

  • Default scheme-less proxy addresses to http://.

  • Preserve explicit HTTP, HTTPS, and SOCKS proxy schemes and the existing empty-value cleanup.

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

  • uv run pytest -q tests/unit/test_core_lifecycle.py: 33 passed
  • ruff format --check .: passed
  • ruff check .: passed

Checklist / 检查清单

  • This change is covered by the linked issue.
  • My changes have been well-tested, and verification results are provided above.
  • No new dependencies are introduced.
  • My changes do not introduce malicious code.

Summary by Sourcery

Normalize HTTP proxy configuration before exporting environment variables.

Bug Fixes:

  • Ensure scheme-less HTTP proxy settings are treated as http:// proxies instead of invalid values.
  • Trim whitespace-only or empty HTTP proxy values to avoid exporting meaningless environment variables.

Enhancements:

  • Align http_proxy and https_proxy environment variables to use a normalized, scheme-consistent proxy value.

Tests:

  • Add parameterized tests verifying proxy normalization, including scheme-less, trimmed, explicit scheme, and empty/None configurations.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code Review

This pull request introduces proxy configuration normalization in AstrBotCoreLifecycle by stripping whitespace and prepending a default http:// scheme if none is present. It also adds a comprehensive parameterized unit test suite to verify this behavior across various proxy string formats. There are no review comments, and I have no feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@Last-emo-boy Last-emo-boy force-pushed the fix/8292-proxy-scheme branch from 26f8ad5 to f67c0c3 Compare July 14, 2026 02:43
@Last-emo-boy Last-emo-boy marked this pull request as ready for review July 14, 2026 02:49
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@dosubot dosubot Bot added size:XS This PR changes 0-9 lines, ignoring generated files. area:core The bug / feature is about astrbot's core, backend labels Jul 14, 2026

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

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 scheme detection logic if proxy_config and "://" not in proxy_config is quite loose and may misclassify non-URL strings containing ://; consider using a more robust URL parse (e.g. urllib.parse.urlparse) or a stricter prefix check for known schemes instead.
  • The proxy normalization logic is now embedded directly in __init__; if similar normalization is or will be needed elsewhere, consider extracting this into a small helper function to keep lifecycle initialization focused and easier to read.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- The scheme detection logic `if proxy_config and "://" not in proxy_config` is quite loose and may misclassify non-URL strings containing `://`; consider using a more robust URL parse (e.g. `urllib.parse.urlparse`) or a stricter prefix check for known schemes instead.
- The proxy normalization logic is now embedded directly in `__init__`; if similar normalization is or will be needed elsewhere, consider extracting this into a small helper function to keep lifecycle initialization focused and easier to read.

## Individual Comments

### Comment 1
<location path="tests/unit/test_core_lifecycle.py" line_range="80-90" />
<code_context>
             assert "localhost" in os.environ.get("no_proxy", "")
             assert "127.0.0.1" in os.environ.get("no_proxy", "")

+    @pytest.mark.parametrize(
+        ("configured_proxy", "expected_proxy"),
+        [
+            ("127.0.0.1:7890", "http://127.0.0.1:7890"),
+            ("  proxy.example.com:8080  ", "http://proxy.example.com:8080"),
+            (" https://proxy.example.com:8080 ", "https://proxy.example.com:8080"),
+            ("socks5://proxy.example.com:1080", "socks5://proxy.example.com:1080"),
+            ("   ", None),
+            (None, None),
+        ],
+    )
</code_context>
<issue_to_address>
**suggestion (testing):** Add a case for already-schemed HTTP proxies to ensure they are left unchanged

The current parametrization covers scheme-less, trimmed, HTTPS, SOCKS5, and empty/None values. Please add a case like `("http://proxy.example.com:8080", "http://proxy.example.com:8080")` to verify that already-HTTP-schemed proxies are preserved and not double-prefixed by the normalization logic.

```suggestion
    @pytest.mark.parametrize(
        ("configured_proxy", "expected_proxy"),
        [
            ("127.0.0.1:7890", "http://127.0.0.1:7890"),
            ("  proxy.example.com:8080  ", "http://proxy.example.com:8080"),
            (" http://proxy.example.com:8080 ", "http://proxy.example.com:8080"),
            (" https://proxy.example.com:8080 ", "https://proxy.example.com:8080"),
            ("socks5://proxy.example.com:1080", "socks5://proxy.example.com:1080"),
            ("   ", None),
            (None, None),
        ],
    )
```
</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 thread tests/unit/test_core_lifecycle.py
@Last-emo-boy Last-emo-boy marked this pull request as draft July 14, 2026 02:52
@Last-emo-boy Last-emo-boy force-pushed the fix/8292-proxy-scheme branch from f67c0c3 to 54cc4eb Compare July 14, 2026 02:52
@Last-emo-boy Last-emo-boy marked this pull request as ready for review July 14, 2026 02:55
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

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

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="astrbot/core/core_lifecycle.py" line_range="68" />
<code_context>

         # 设置代理
-        proxy_config = self.astrbot_config.get("http_proxy", "")
+        proxy_config = str(self.astrbot_config.get("http_proxy", "") or "").strip()
+        if proxy_config and "://" not in proxy_config:
+            proxy_config = f"http://{proxy_config}"
</code_context>
<issue_to_address>
**suggestion (bug_risk):** Coercing any value to `str` may hide misconfigurations in `http_proxy`.

This change will silently stringify non-string values (e.g. dicts/lists) into something like `"{'host': 'x', 'port': 8080}"`, which will then be treated as a valid proxy URL instead of surfacing a configuration error. It would be safer to validate the type of `http_proxy` (accepting only `None`/empty or `str`) and raise or log on other types so misconfigurations fail explicitly.

Suggested implementation:

```python
        # 设置代理
        raw_http_proxy = self.astrbot_config.get("http_proxy", "")

        # 仅接受 None/空 或 str,其它类型视为配置错误
        if raw_http_proxy is None:
            proxy_config = ""
        elif isinstance(raw_http_proxy, str):
            proxy_config = raw_http_proxy.strip()
        else:
            raise ValueError(
                f"Invalid type for 'http_proxy' in astrbot_config: "
                f"expected str or None, got {type(raw_http_proxy).__name__}"
            )

        if proxy_config and "://" not in proxy_config:
            proxy_config = f"http://{proxy_config}"

        if proxy_config != "":
            os.environ["https_proxy"] = proxy_config
            os.environ["http_proxy"] = proxy_config

```

If your codebase prefers logging and continuing instead of raising on configuration errors, replace the `raise ValueError(...)` with a log call (e.g. `logger.error(...)`) and set `proxy_config = ""` so that no proxy is applied when the value is misconfigured.
</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 thread astrbot/core/core_lifecycle.py Outdated
@Last-emo-boy Last-emo-boy marked this pull request as draft July 14, 2026 03:00
@Last-emo-boy Last-emo-boy force-pushed the fix/8292-proxy-scheme branch from 54cc4eb to 0ed1e2d Compare July 14, 2026 03:01
@Last-emo-boy Last-emo-boy marked this pull request as ready for review July 14, 2026 03:04
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've reviewed your changes and they look great!


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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core The bug / feature is about astrbot's core, backend size:XS This PR changes 0-9 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

enhancement: auto-prepend http:// scheme to http_proxy config for httpx compatibility

1 participant