Repository navigation
fix(pool): enforce unique per-account device_mid to stop UNUSUAL_ACTIVITY 405 flags - #6
amirshaker000 wants to merge 1 commit into
Conversation
…VITY flags Z.ai risk control correlates accounts that share a device fingerprint. Older generator batches wrote the same hardcoded device_mid into every snapshot, so 126/149 accounts presented an identical x-device-mid from one egress IP and the whole pool was flagged UNUSUAL_ACTIVITY (HTTP 405 from the edge WAF). Rewrite any missing or duplicated device_mid to a stable per-account uuid5 derived from the access token (identical derivation to generator/plan_check.per_account_device_mid, so gateway and generator agree). Unique mids are preserved. Applied at load for every account source. Also align the generated-config default balance_poll_seconds (60 -> 300) with the code default so a fresh config does not sweep the whole pool every minute.
There was a problem hiding this comment.
6 issues found across 4 files
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="zcode_gateway/paths.py">
<violation number="1" location="zcode_gateway/paths.py:79">
P2: This changes the standalone bootstrap only; the Linux installer still generates `balance_poll_seconds: 60`. Fresh VPS deployments therefore keep the old one-minute pool-wide sweep despite the new 300-second generated-config default. Update the Linux installer template to keep all generated configs aligned.</violation>
</file>
<file name="tests/test_device_mid_uniqueness.py">
<violation number="1" location="tests/test_device_mid_uniqueness.py:14">
P2: This suite misses an order-dependent collision between a rewritten duplicate and a later preserved `device_mid`, so the claimed uniqueness guarantee can still fail while these tests pass. Add a regression fixture where the later preserved mid equals an earlier account’s derived ID.</violation>
<violation number="2" location="tests/test_device_mid_uniqueness.py:47">
P2: This does not test generator compatibility because it duplicates the generator’s current formula. Compare `_per_account_device_mid(token)` directly with `generator.plan_check.per_account_device_mid(token)` so drift is detected.</violation>
</file>
<file name="zcode_gateway/pool.py">
<violation number="1" location="zcode_gateway/pool.py:301">
P1: Applying this only during source loading leaves the live account-add path unprotected. A second dashboard login can still enter the pool with the shared fingerprint and trigger the same WAF before the next reload; enforce the per-account ID when registering or upserting an account as well.</violation>
<violation number="2" location="zcode_gateway/pool.py:311">
P2: A non-string `device_mid` in `pool.json` now crashes the whole account load because `.strip()` is unconditional; the app then starts with an empty pool. Normalize only string values and treat other values as missing so one malformed metadata field cannot disable every account.</violation>
<violation number="3" location="zcode_gateway/pool.py:318">
P1: This does not guarantee uniqueness when a generated ID collides with a unique `device_mid` later in the input. Check generated IDs against every original value, not only duplicated values, before preserving the later account's ID.</violation>
</file>
Tip: Get a Slack DM when cubic finishes reviewing your PRs. Connect Slack
View guided diff | Re-trigger cubic
| return str(_uuid.uuid5(_uuid.NAMESPACE_URL, "zcode-device:" + (token or ""))) | ||
|
|
||
|
|
||
| def _ensure_unique_device_mids(accounts: list[Account]) -> list[Account]: |
There was a problem hiding this comment.
P1: Applying this only during source loading leaves the live account-add path unprotected. A second dashboard login can still enter the pool with the shared fingerprint and trigger the same WAF before the next reload; enforce the per-account ID when registering or upserting an account as well.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/pool.py, line 301:
<comment>Applying this only during source loading leaves the live account-add path unprotected. A second dashboard login can still enter the pool with the shared fingerprint and trigger the same WAF before the next reload; enforce the per-account ID when registering or upserting an account as well.</comment>
<file context>
@@ -288,16 +288,51 @@ def load_from_pool_file(path: str) -> list[Account]:
+ return str(_uuid.uuid5(_uuid.NAMESPACE_URL, "zcode-device:" + (token or "")))
+
+
+def _ensure_unique_device_mids(accounts: list[Account]) -> list[Account]:
+ """Guarantee every account presents a distinct ``x-device-mid``.
+
</file context>
| if not mid or counts[mid] > 1: | ||
| seed = account.access_token or account.id | ||
| mid = _per_account_device_mid(seed) | ||
| while mid in seen or (mid in counts and counts[mid] > 1): |
There was a problem hiding this comment.
P1: This does not guarantee uniqueness when a generated ID collides with a unique device_mid later in the input. Check generated IDs against every original value, not only duplicated values, before preserving the later account's ID.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/pool.py, line 318:
<comment>This does not guarantee uniqueness when a generated ID collides with a unique `device_mid` later in the input. Check generated IDs against every original value, not only duplicated values, before preserving the later account's ID.</comment>
<file context>
@@ -288,16 +288,51 @@ def load_from_pool_file(path: str) -> list[Account]:
+ if not mid or counts[mid] > 1:
+ seed = account.access_token or account.id
+ mid = _per_account_device_mid(seed)
+ while mid in seen or (mid in counts and counts[mid] > 1):
+ mid = _per_account_device_mid(mid)
+ account.notes["device_mid"] = mid
</file context>
| while mid in seen or (mid in counts and counts[mid] > 1): | |
| while mid in seen or mid in counts: |
| # a lone binary work with nothing alongside it. Keys are per-install random, | ||
| # never a shared hardcoded default. | ||
| DEFAULT_CONFIG_YAML = 'server:\n host: 127.0.0.1\n port: 8788\n require_client_key: true\n admin_key: gw-admin-local\n client_keys:\n - key: gw-local-1\n name: local\nupstream:\n base_url: https://zcode.z.ai/api/v1\n chat_path: /zcode-plan/anthropic/v1/messages\n timeout_connect: 15\n timeout_read: 600\n max_attempts: 3\npool:\n strategy: drain_first\n cooldown_seconds: 30\n max_in_flight_per_account: 4\n acquire_wait_seconds: 5\n conversation_affinity_seconds: 600\n balance_poll_seconds: 60\naccounts:\n source: accounts_dir\n providers_json: "~/.zcode/v2/credentials.json"\n dir: ./accounts\n pool_file: ./pool.json\nmodels:\n aliases:\n glm-5.4: GLM-5.4\n glm-5.3-flash: GLM-5.3-Flash\n default: GLM-5.3-Flash\n default_anthropic: GLM-5.4\n default_max_tokens: 128000\n default_effort: high\n pacing:\n enabled: true\n min_gap_ms: 150\n max_gap_ms: 400\n auto_free_fallback:\n enabled: false\n chain: [GLM-5.4, GLM-5.3-Flash]\nlogging:\n level: INFO\n capture: false\n capture_dir: ./logs\nstore:\n sqlite_path: ./gateway.db\nupdate:\n enabled: false\n repo: B3hnamR/AutoZcoder\ngenerator:\n enabled: false\n zcodeauto_dir: ""\n python_exe: ""\n captcha: "manual"\n headless: false\n claim: true\n invite_code: "MT9GNDQ8"\n captcha_tickets: 0\n captcha_ticket_ttl_seconds: 75\n socks_only: true\n proxy_types: "socks"\nclaims:\n daily_enabled: false\n daily_time: "19:02"\n daily_utc_offset_hours: 8\n daily_mode: direct\n campaign_utc_offset_hours: 8\n campaign_gate: true\n' | ||
| DEFAULT_CONFIG_YAML = 'server:\n host: 127.0.0.1\n port: 8788\n require_client_key: true\n admin_key: gw-admin-local\n client_keys:\n - key: gw-local-1\n name: local\nupstream:\n base_url: https://zcode.z.ai/api/v1\n chat_path: /zcode-plan/anthropic/v1/messages\n timeout_connect: 15\n timeout_read: 600\n max_attempts: 3\npool:\n strategy: drain_first\n cooldown_seconds: 30\n max_in_flight_per_account: 4\n acquire_wait_seconds: 5\n conversation_affinity_seconds: 600\n balance_poll_seconds: 300\naccounts:\n source: accounts_dir\n providers_json: "~/.zcode/v2/credentials.json"\n dir: ./accounts\n pool_file: ./pool.json\nmodels:\n aliases:\n glm-5.4: GLM-5.4\n glm-5.3-flash: GLM-5.3-Flash\n default: GLM-5.3-Flash\n default_anthropic: GLM-5.4\n default_max_tokens: 128000\n default_effort: high\n pacing:\n enabled: true\n min_gap_ms: 150\n max_gap_ms: 400\n auto_free_fallback:\n enabled: false\n chain: [GLM-5.4, GLM-5.3-Flash]\nlogging:\n level: INFO\n capture: false\n capture_dir: ./logs\nstore:\n sqlite_path: ./gateway.db\nupdate:\n enabled: false\n repo: B3hnamR/AutoZcoder\ngenerator:\n enabled: false\n zcodeauto_dir: ""\n python_exe: ""\n captcha: "manual"\n headless: false\n claim: true\n invite_code: "MT9GNDQ8"\n captcha_tickets: 0\n captcha_ticket_ttl_seconds: 75\n socks_only: true\n proxy_types: "socks"\nclaims:\n daily_enabled: false\n daily_time: "19:02"\n daily_utc_offset_hours: 8\n daily_mode: direct\n campaign_utc_offset_hours: 8\n campaign_gate: true\n' |
There was a problem hiding this comment.
P2: This changes the standalone bootstrap only; the Linux installer still generates balance_poll_seconds: 60. Fresh VPS deployments therefore keep the old one-minute pool-wide sweep despite the new 300-second generated-config default. Update the Linux installer template to keep all generated configs aligned.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/paths.py, line 79:
<comment>This changes the standalone bootstrap only; the Linux installer still generates `balance_poll_seconds: 60`. Fresh VPS deployments therefore keep the old one-minute pool-wide sweep despite the new 300-second generated-config default. Update the Linux installer template to keep all generated configs aligned.</comment>
<file context>
@@ -76,7 +76,7 @@ def find_accounts_dir() -> Path:
# a lone binary work with nothing alongside it. Keys are per-install random,
# never a shared hardcoded default.
-DEFAULT_CONFIG_YAML = 'server:\n host: 127.0.0.1\n port: 8788\n require_client_key: true\n admin_key: gw-admin-local\n client_keys:\n - key: gw-local-1\n name: local\nupstream:\n base_url: https://zcode.z.ai/api/v1\n chat_path: /zcode-plan/anthropic/v1/messages\n timeout_connect: 15\n timeout_read: 600\n max_attempts: 3\npool:\n strategy: drain_first\n cooldown_seconds: 30\n max_in_flight_per_account: 4\n acquire_wait_seconds: 5\n conversation_affinity_seconds: 600\n balance_poll_seconds: 60\naccounts:\n source: accounts_dir\n providers_json: "~/.zcode/v2/credentials.json"\n dir: ./accounts\n pool_file: ./pool.json\nmodels:\n aliases:\n glm-5.4: GLM-5.4\n glm-5.3-flash: GLM-5.3-Flash\n default: GLM-5.3-Flash\n default_anthropic: GLM-5.4\n default_max_tokens: 128000\n default_effort: high\n pacing:\n enabled: true\n min_gap_ms: 150\n max_gap_ms: 400\n auto_free_fallback:\n enabled: false\n chain: [GLM-5.4, GLM-5.3-Flash]\nlogging:\n level: INFO\n capture: false\n capture_dir: ./logs\nstore:\n sqlite_path: ./gateway.db\nupdate:\n enabled: false\n repo: B3hnamR/AutoZcoder\ngenerator:\n enabled: false\n zcodeauto_dir: ""\n python_exe: ""\n captcha: "manual"\n headless: false\n claim: true\n invite_code: "MT9GNDQ8"\n captcha_tickets: 0\n captcha_ticket_ttl_seconds: 75\n socks_only: true\n proxy_types: "socks"\nclaims:\n daily_enabled: false\n daily_time: "19:02"\n daily_utc_offset_hours: 8\n daily_mode: direct\n campaign_utc_offset_hours: 8\n campaign_gate: true\n'
+DEFAULT_CONFIG_YAML = 'server:\n host: 127.0.0.1\n port: 8788\n require_client_key: true\n admin_key: gw-admin-local\n client_keys:\n - key: gw-local-1\n name: local\nupstream:\n base_url: https://zcode.z.ai/api/v1\n chat_path: /zcode-plan/anthropic/v1/messages\n timeout_connect: 15\n timeout_read: 600\n max_attempts: 3\npool:\n strategy: drain_first\n cooldown_seconds: 30\n max_in_flight_per_account: 4\n acquire_wait_seconds: 5\n conversation_affinity_seconds: 600\n balance_poll_seconds: 300\naccounts:\n source: accounts_dir\n providers_json: "~/.zcode/v2/credentials.json"\n dir: ./accounts\n pool_file: ./pool.json\nmodels:\n aliases:\n glm-5.4: GLM-5.4\n glm-5.3-flash: GLM-5.3-Flash\n default: GLM-5.3-Flash\n default_anthropic: GLM-5.4\n default_max_tokens: 128000\n default_effort: high\n pacing:\n enabled: true\n min_gap_ms: 150\n max_gap_ms: 400\n auto_free_fallback:\n enabled: false\n chain: [GLM-5.4, GLM-5.3-Flash]\nlogging:\n level: INFO\n capture: false\n capture_dir: ./logs\nstore:\n sqlite_path: ./gateway.db\nupdate:\n enabled: false\n repo: B3hnamR/AutoZcoder\ngenerator:\n enabled: false\n zcodeauto_dir: ""\n python_exe: ""\n captcha: "manual"\n headless: false\n claim: true\n invite_code: "MT9GNDQ8"\n captcha_tickets: 0\n captcha_ticket_ttl_seconds: 75\n socks_only: true\n proxy_types: "socks"\nclaims:\n daily_enabled: false\n daily_time: "19:02"\n daily_utc_offset_hours: 8\n daily_mode: direct\n campaign_utc_offset_hours: 8\n campaign_gate: true\n'
</file context>
| # Must match generator/plan_check.per_account_device_mid exactly so the | ||
| # gateway and generator agree on one stable id per account. | ||
| token = "eyJ.example.token" | ||
| expected = str(uuid.uuid5(uuid.NAMESPACE_URL, "zcode-device:" + token)) |
There was a problem hiding this comment.
P2: This does not test generator compatibility because it duplicates the generator’s current formula. Compare _per_account_device_mid(token) directly with generator.plan_check.per_account_device_mid(token) so drift is detected.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/test_device_mid_uniqueness.py, line 47:
<comment>This does not test generator compatibility because it duplicates the generator’s current formula. Compare `_per_account_device_mid(token)` directly with `generator.plan_check.per_account_device_mid(token)` so drift is detected.</comment>
<file context>
@@ -0,0 +1,49 @@
+ # Must match generator/plan_check.per_account_device_mid exactly so the
+ # gateway and generator agree on one stable id per account.
+ token = "eyJ.example.token"
+ expected = str(uuid.uuid5(uuid.NAMESPACE_URL, "zcode-device:" + token))
+ assert _per_account_device_mid(token) == expected
+ assert _per_account_device_mid(token) == _per_account_device_mid(token)
</file context>
|
|
||
| def test_shared_device_mid_is_replaced_for_every_account(): | ||
| shared = "234aefe2-3795-4cf2-95c6-7bd9291feb1f" | ||
| accounts = [_acct(str(i), f"tok{i}", shared) for i in range(5)] |
There was a problem hiding this comment.
P2: This suite misses an order-dependent collision between a rewritten duplicate and a later preserved device_mid, so the claimed uniqueness guarantee can still fail while these tests pass. Add a regression fixture where the later preserved mid equals an earlier account’s derived ID.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/test_device_mid_uniqueness.py, line 14:
<comment>This suite misses an order-dependent collision between a rewritten duplicate and a later preserved `device_mid`, so the claimed uniqueness guarantee can still fail while these tests pass. Add a regression fixture where the later preserved mid equals an earlier account’s derived ID.</comment>
<file context>
@@ -0,0 +1,49 @@
+
+def test_shared_device_mid_is_replaced_for_every_account():
+ shared = "234aefe2-3795-4cf2-95c6-7bd9291feb1f"
+ accounts = [_acct(str(i), f"tok{i}", shared) for i in range(5)]
+
+ _ensure_unique_device_mids(accounts)
</file context>
| counts = Counter((a.notes.get("device_mid") or "").strip() for a in accounts) | ||
| seen: set[str] = set() | ||
| for account in accounts: | ||
| mid = (account.notes.get("device_mid") or "").strip() |
There was a problem hiding this comment.
P2: A non-string device_mid in pool.json now crashes the whole account load because .strip() is unconditional; the app then starts with an empty pool. Normalize only string values and treat other values as missing so one malformed metadata field cannot disable every account.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At zcode_gateway/pool.py, line 311:
<comment>A non-string `device_mid` in `pool.json` now crashes the whole account load because `.strip()` is unconditional; the app then starts with an empty pool. Normalize only string values and treat other values as missing so one malformed metadata field cannot disable every account.</comment>
<file context>
@@ -288,16 +288,51 @@ def load_from_pool_file(path: str) -> list[Account]:
+ every snapshot, so we rewrite any missing or duplicated mid to a stable
+ per-account uuid5 derived from the access token. Unique mids are preserved.
+ """
+ counts = Counter((a.notes.get("device_mid") or "").strip() for a in accounts)
+ seen: set[str] = set()
+ for account in accounts:
</file context>
| counts = Counter((a.notes.get("device_mid") or "").strip() for a in accounts) | |
| seen: set[str] = set() | |
| for account in accounts: | |
| mid = (account.notes.get("device_mid") or "").strip() | |
| def _normalized_mid(account: Account) -> str: | |
| value = account.notes.get("device_mid") | |
| return value.strip() if isinstance(value, str) else "" | |
| counts = Counter(_normalized_mid(a) for a in accounts) | |
| seen: set[str] = set() | |
| for account in accounts: | |
| mid = _normalized_mid(account) |
Problem
Large generated pools get flagged by Z.ai's edge WAF with UNUSUAL_ACTIVITY / HTTP 405 on /zcode-plan/anthropic/v1/messages, even though the gateway itself is healthy.
Root cause: device fingerprint collapse. Older generator batches wrote the same hardcoded \device_mid\ into every account snapshot. In a 149-account pool, 126 files shared a single \device_mid\ (\234aefe2-...) and all requests left from one egress IP via round-robin. That shared fingerprint + single-IP fan-out is the exact cross-account correlation signal risk control keys on.
The gateway loads \device_mid\ verbatim from each snapshot (\�ccounts_dir.py) and falls back to the global fingerprint when it is empty, so nothing enforced uniqueness across the pool.
Fix
Why this is safe
Test plan
Summary by cubic
Fixes large pools being flagged
UNUSUAL_ACTIVITY(HTTP 405) by Z.ai's WAF because older generator batches wrote the same hardcodeddevice_midinto every account snapshot. Missing or duplicateddevice_midvalues are now rewritten at load to a deterministic per-account uuid5 derived from the access token, using the same derivation as the generator; unique mids are preserved.Also aligns the generated-config default
balance_poll_seconds(60 → 300) with the code default so a fresh config doesn't sweep the entire pool every minute.Written for commit fa41b48. Summary will update on new commits.