# Python: selectively route IP-allowlisted API calls

요약: 봇·서버 코드에서 IP 허용 목록이 필요한 API 호출만 allowip로 보내세요.
대상이 불분명하면 수정 전에 물어보고, 검증을 위해 주문이나 메시지를 보내지 마세요.

## 1. What allowip is

allowip gives the project a fixed outbound IPv4 through an HTTPS CONNECT tunnel configured by the `ALLOWIP_TUNNEL_URL` environment variable. TLS to the destination stays end to end: allowip does not decrypt destination requests or receive destination API credentials.

## 2. Your task, agent

Inspect the codebase and decide which outbound HTTP calls go to services requiring an IP allowlist. Route **only those calls** through the tunnel, adapting to the bot/backend's actual client rather than changing all Python networking.

Typical signs include `GW.IP_NOT_ALLOWED`, `no_authorization_ip`, “IP not allowed”, 401/403 errors mentioning the IP, SDK documentation/settings about IP registration, or the user naming a service. Known examples include Naver Commerce, Coupang WING, Upbit, Bithumb, Kiwoom, Aligo, and 공공데이터포털. This is not exhaustive; requirements vary by API/key.

If it is unclear which calls qualify, ask the user **before changing anything**. Trace SDK transports and any token calls that also require IP registration. Do not invent endpoints, signing algorithms, or exchange SDK options.

## 3. Constraints (must)

- Do not proxy unrelated analytics, your own database, other APIs, or build/install traffic. No process-wide proxy or monkey-patching all requests.
- Keep TLS verification on for both proxy and destination; never use `verify=False`.
- Never log or hardcode the tunnel URL or credentials; read private env/platform secrets and exclude them from Git, notebooks, and error output.
- Fail with a sanitized error; never silently fall back to direct connections.
- Respect the Python runtime/library's HTTPS-proxy support and timeouts. Do not downgrade the issued proxy to plaintext if unsupported.

## 4. Recommended approach for this platform

Adapt this single `requests` reference to the project's HTTP client and layout. Its per-request `proxies` pattern is retained from the current Python guide and `web/trading.html`. **The repository has not live-tested the Python tunnel path**; do not claim otherwise. For a live-verified transport use [Node](node.md). A supported Python environment with `requests>=2.32` and `urllib3>=2` is recommended; retain the project's dependency-locking practice.

For example, a backend-only `allowip.py`:

```python
import os
from urllib.parse import urlsplit


class RequestsAllowip:
    def __init__(self, allowed_hosts=()):
        import requests
        try:
            proxy = os.environ["ALLOWIP_TUNNEL_URL"]
            parsed = urlsplit(proxy)
            if (parsed.scheme != "https" or not parsed.hostname
                    or not parsed.username or not parsed.password):
                raise ValueError()
        except Exception:
            raise RuntimeError("Invalid ALLOWIP_TUNNEL_URL configuration") from None
        self.session = requests.Session()
        self.session.trust_env = False
        self.proxies = {"https": proxy}
        self.allowed_hosts = set(allowed_hosts)

    def _send(self, method, url, **kwargs):
        kwargs.update(proxies=self.proxies, verify=True,
                      allow_redirects=False, timeout=15)
        response = None
        try:
            response = self.session.request(method, url, **kwargs)
            if 300 <= response.status_code < 400:
                raise RuntimeError("Redirect blocked")
            response.raise_for_status()
            return response
        except Exception:
            if response is not None:
                response.close()
            raise RuntimeError("allowip request failed; no direct fallback") from None

    def request(self, method, url, **kwargs):
        try:
            parsed = urlsplit(url)
            valid = (parsed.scheme == "https" and parsed.hostname
                     and parsed.port in (None, 443)
                     and not parsed.username and not parsed.password
                     and (not self.allowed_hosts
                          or parsed.hostname in self.allowed_hosts))
        except Exception:
            valid = False
        if not valid:
            raise RuntimeError("Target URL is not permitted")
        return self._send(method, url, **kwargs)

    def verify(self, dashboard_ip):
        with self._send("GET", "https://api.ipify.org?format=json") as response:
            ip = response.json().get("ip")
            if not dashboard_ip or ip != dashboard_ip:
                raise RuntimeError("Egress IPv4 mismatch")
            return ip

    def close(self):
        self.session.close()
```

Use `transport.request(method, existing_url, ...)` only for selected calls. Preserve signing, authentication, headers, body, token renewal, and response handling. Close responses and the transport using `finally` or the application's lifecycle. If you want a guard, supply an allowlist of hosts to `RequestsAllowip(...)`; `TARGET_API_HOST` is **not required**. Keep destinations controlled by application logic.

Do not assume ccxt or another SDK uses this session: inspect its documented transport hook. If the project already uses httpx, adapt to its supported `proxy=` API (singular in httpx 0.28), not requests' `proxies` argument. HTTPS-to-proxy/TLS-in-TLS support depends on library/backend versions. If it fails, stop and investigate a supported version or discuss Node; never disable TLS checks or retry directly.

Set `ALLOWIP_TUNNEL_URL` to the issued HTTPS URL in the bot/service's private environment: your IDE's private run configuration, a service manager environment file on a PC/server, or the hosting provider's Environment/Variables page. Restart/redeploy the process. Keep destination secrets there too, not in source, shell arguments, or tracked `.env` files. Ask the user to configure secrets privately, not paste them into chat. The dashboard IPv4 may optionally be stored in `ALLOWIP_EGRESS_IP`.

## 5. Verify

Run `transport.verify(dashboard_ip)` in the same virtual environment/runtime as the deployed bot. It calls `https://api.ipify.org` **through the tunnel** and compares with the IPv4 shown in the allowip dashboard. Stop on mismatch; a syntax check alone does not verify HTTPS proxy compatibility.

Then make one existing authenticated **read-only** call to each selected target through `transport.request` and check the result. Do not place/cancel orders, send messages, or write records. Close responses and the session; report only sanitized success/status, not API/account data.

Tunnel CONNECT codes: **407** authentication failed; **403** destination/port not allowed; **402** account expired/inactive; **502** upstream connection failed. Python may raise a proxy/transport exception rather than return these statuses. Classify safely without logging raw exceptions, which can contain credentials. A destination HTTP 403 is distinct.

## 6. Report back to the user

Say which calls you routed and why, which you left alone, what verification ran or remains unverified, and what the user still needs to do. Register the **allowip dashboard IPv4**, not a PC's changing IP or proxy hostname, in the target console if required.

Use the relevant solution page: [Naver Commerce](https://allowip.com/solutions/naver-commerce), [Coupang WING](https://allowip.com/solutions/coupang), [Upbit/Bithumb](https://allowip.com/solutions/upbit-bithumb), [Kiwoom](https://allowip.com/solutions/kiwoom), [Aligo](https://allowip.com/solutions/aligo), or [공공데이터포털](https://allowip.com/solutions/public-data). The last has provider-specific restrictions, not a universal registration field.
