"""A provider 403 is not evidence that a user's rank is too low.""" import ast import importlib.util import json import os from contextlib import closing from pathlib import Path import re import sqlite3 import tempfile import unittest SOURCE = Path(__file__).resolve().parents[1] / 'gateway/gateway_errors.py' SPEC = importlib.util.spec_from_file_location('audited_gateway_errors', SOURCE) MOD = importlib.util.module_from_spec(SPEC) SPEC.loader.exec_module(MOD) class PublicErrorTests(unittest.TestCase): def error(self, status, message, balance=None): return MOD.public_error(status, json.dumps({'error': {'message': message}}).encode(), '/v1/chat/completions', user_balance=balance) def test_real_token_model_denial_is_specific_not_a_blanket_rank_claim(self): status, body = self.error(403, 'This token has no access to model gpt-6-luna (request id: audit-123)') self.assertEqual((status, body['error']['code']), (403, 'model_access_denied')) self.assertEqual(body['error']['request_id'], 'audit-123') self.assertIn('старые имена', body['error']['message']) self.assertIn('/profile', body['error']['message']) self.assertNotIn('повысьте ранг', body['error']['message']) def test_unknown_provider_forbidden_never_claims_rank_deficiency(self): status, body = self.error(403, 'Access forbidden by provider policy') self.assertEqual((status, body['error']['code']), (403, 'request_forbidden')) self.assertNotIn('повысьте ранг', body['error']['message']) self.assertNotIn('У вашего ключа нет доступа', body['error']['message']) def test_provider_billing_still_is_not_a_user_quota_error(self): status, body = self.error(403, 'Free quota exhausted') self.assertEqual((status, body['error']['code']), (503, 'upstream_billing_error')) def test_bare_upstream_quota_with_user_funds_retains_live_production_fix(self): status, body = self.error(403, 'insufficient_quota', 1000.0) self.assertEqual((status, body['error']['code']), (503, 'upstream_billing_error')) def test_invalid_key_and_transient_rate_limits_remain_distinct(self): self.assertEqual(self.error(401, 'bad key')[1]['error']['code'], 'invalid_api_key') status, body = self.error(429, 'too many requests') self.assertEqual(status, 429) self.assertTrue(body['error']['retryable']) def test_provider_401_never_revokes_the_client_key(self): for message in ( 'channel error (channel #20247, status code: 401)', 'Incorrect API key provided: sk-not-a-user-key'): with self.subTest(message=message): status, body = self.error(401, message) self.assertEqual((status, body['error']['code']), (503, 'upstream_auth_error')) self.assertTrue(body['error']['retryable']) self.assertNotIn('sk-', json.dumps(body)) self.assertNotIn('недействителен или отозван', body['error']['message']) def test_all_auth_aliases_accept_one_credential_only(self): headers = {'Authorization': 'bearer same', 'X-Api-Key': 'same', 'Api-Key': 'same'} self.assertEqual(MOD.normalize_auth_headers(headers), {'Authorization': 'Bearer same'}) self.assertEqual(MOD.normalize_auth_headers({'Api-Key': 'same'}), {'Authorization': 'Bearer same'}) with self.assertRaises(ValueError): MOD.normalize_auth_headers({'Authorization': 'Bearer first', 'Api-Key': 'second'}) def test_fullwidth_precharge_provider_wallet_is_not_the_clients_wallet(self): message = '预扣费额度失败, 用户剩余额度: $0.004652, 需要预扣费额度: $0.168556' status, body = self.error(403, message, 999.32) self.assertEqual((status, body['error']['code']), (503, 'upstream_billing_error')) self.assertNotIn('ранг', body['error']['message']) def test_real_precharge_shortage_remains_a_client_quota_denial(self): status, body = self.error(403, '预扣费额度失败, 用户剩余额度: $0.01, 需要预扣费额度: $0.50', 0.01) self.assertEqual((status, body['error']['code']), (402, 'insufficient_quota')) self.assertFalse(body['error']['retryable']) def test_provider_model_permission_is_not_the_clients_rank(self): status, body = self.error(403, 'Model "claude-sonnet-5-5" not allowed for this key. Allowed: claude') self.assertEqual((status, body['error']['code']), (503, 'upstream_model_denied')) def test_upstream_413_does_not_claim_our_40mb_limit_was_hit(self): status, body = MOD.public_error(413, b'not JSON', '/v1/chat/completions', from_upstream=True) self.assertEqual((status, body['error']['code']), (413, 'upstream_request_too_large')) self.assertNotIn('максимальный размер запроса', body['error']['message']) self.assertFalse(body['error']['retryable']) self.assertEqual(MOD.public_error(413, b'', '/v1/chat/completions')[1]['error']['code'], 'request_too_large') def test_text_only_route_image_rejection_is_honest_and_actionable(self): # glm-5.3 + скриншот: upstream 400 code 1210 «allowed values: ['text']» — не «проверьте имя модели». status, body = self.error(400, "contents.parts.type is invalid, allowed values: ['text'] (code 1210)") self.assertEqual((status, body['error']['code']), (400, 'vision_not_supported')) self.assertFalse(body['error']['retryable']) self.assertIn('не принимает изображения', body['error']['message']) self.assertIn('из истории', body['error']['message']) self.assertIn('другая модель не подставлялась', body['error']['message']) for removed in ('deepseek-v4.1-flash', 'gemini-3.5-flash', 'glm-5.3-prime'): self.assertNotIn(removed, body['error']['message']) def test_dead_upstream_route_404_is_retryable_gateway_problem(self): status, body = self.error(404, 'Not Found') self.assertEqual((status, body['error']['code']), (503, 'upstream_route_dead')) self.assertTrue(body['error']['retryable']) def test_route_404_mapping_is_scoped_to_relay_paths(self): status, body = MOD.public_error(404, b'Not Found', '/api/show') self.assertEqual((status, body['error']['code']), (404, 'invalid_request')) class ContentPolicyMessageTests(unittest.TestCase): """[POLICYMSG 2810] Вердикт модерации апстрима детерминирован: совет «повтори попытку» невыполним.""" def policy_error(self, code, message, path='/v1/chat/completions'): body = json.dumps({'error': {'code': code, 'message': message}}).encode() return MOD.public_error(400, body, path, from_upstream=True) def test_dashscope_inspection_failure_is_non_retryable_policy_code(self): status, body = self.policy_error( 'data_inspection_failed', 'DataInspectionFailed: Input data may contain inappropriate content.') err = body['error'] self.assertEqual((status, err['code'], err['retryable']), (400, 'content_policy_violation', False)) self.assertEqual(err['message'], MOD.CONTENT_POLICY_USERMSG) def test_policy_message_states_the_filter_and_a_real_alternative(self): _, body = self.policy_error('content_policy_violation', 'content_policy_violation') msg = body['error']['message'] self.assertIn('контент-фильтр', msg) self.assertIn('переформулируй', msg) self.assertIn('другого семейства', msg) self.assertNotIn('не обработала запрос', msg) def test_policy_message_does_not_promise_that_a_plain_retry_helps(self): _, body = self.policy_error('content_filter', 'rejected by safety system') msg = body['error']['message'] for misleading in ('Повтори попытку', 'повтори попытку', 'Повторите попытку', 'повторите попытку'): self.assertNotIn(misleading, msg) self.assertIn('не поможет', msg) def test_openai_content_filter_uses_the_same_honest_text(self): _, body = self.policy_error('content_filter', 'Your request was rejected as a result of our safety system.') self.assertEqual((body['error']['code'], body['error']['message']), ('content_policy_violation', MOD.CONTENT_POLICY_USERMSG)) def test_image_route_policy_rejection_keeps_the_same_contract(self): status, body = self.policy_error('DataInspectionFailed', 'DataInspectionFailed', '/v1/images/generations') self.assertEqual((status, body['error']['code'], body['error']['message']), (400, 'content_policy_violation', MOD.CONTENT_POLICY_USERMSG)) def test_unsupported_parameter_prose_is_not_a_policy_verdict(self): # [NOPOLICY 2810] структурный код важнее слабой прозы «content_filter» в message. status, body = self.policy_error('unsupported_parameter', 'content_filter unsupported: model-x') self.assertNotEqual(body['error']['code'], 'content_policy_violation') def test_strong_provider_marker_wins_over_a_generic_code(self): status, body = self.policy_error( 'invalid_request_error', 'DataInspectionFailed: Input data may contain inappropriate content.') self.assertEqual((status, body['error']['code'], body['error']['retryable']), (400, 'content_policy_violation', False)) def test_weak_marker_without_any_structured_code_still_maps_to_policy(self): raw = json.dumps({'error': {'message': 'request blocked by content_filter'}}).encode() status, body = MOD.public_error(400, raw, '/v1/chat/completions', from_upstream=True) self.assertEqual((status, body['error']['code'], body['error']['message']), (400, 'content_policy_violation', MOD.CONTENT_POLICY_USERMSG)) def test_bot_imports_the_gateway_text_instead_of_copying_it(self): root = Path(__file__).resolve().parents[1] bot_src = (root / 'bot/grok_bot.py').read_text(encoding='utf-8') self.assertIn('from gateway_errors import public_error, CONTENT_POLICY_USERMSG', bot_src) assigned = None for node in ast.walk(ast.parse(bot_src)): if isinstance(node, ast.Assign) and any(getattr(t, 'id', None) == '_POLICY_USERMSG' for t in node.targets): assigned = node.value self.assertIsInstance(assigned, ast.Name, 'бот обязан брать текст из gateway_errors, а не хранить копию') self.assertEqual(assigned.id, 'CONTENT_POLICY_USERMSG') def test_no_python_source_ships_the_misleading_retry_advice(self): root = Path(__file__).resolve().parents[1] stale_advice = 'Повтори попытку ' + 'или выбери другую модель' # собрано из частей: тест не содержит искомую строку stale = [] for path in root.rglob('*.py'): if 'build' in path.parts or '__pycache__' in path.parts: continue text = path.read_text(encoding='utf-8', errors='replace') if stale_advice in text: stale.append(str(path.relative_to(root))) self.assertEqual(stale, []) class PolicyCodeClassificationTests(unittest.TestCase): """[POLICYCODE 2810] Политика — точный код/тип вендора (в т.ч. вложенный), а не проза про параметры.""" def raw_error(self, status, payload, path='/v1/chat/completions'): body = payload if isinstance(payload, (bytes, bytearray)) else json.dumps(payload).encode() return MOD.public_error(status, body, path, from_upstream=True) def assert_policy(self, result): status, body = result err = body['error'] self.assertEqual((status, err['code'], err['retryable']), (400, 'content_policy_violation', False)) self.assertEqual(err['message'], MOD.CONTENT_POLICY_USERMSG) def assert_not_policy(self, body): self.assertNotEqual(body['error']['code'], 'content_policy_violation') self.assertNotEqual(body['error']['message'], MOD.CONTENT_POLICY_USERMSG) def test_nested_code_only_envelope_is_policy(self): self.assert_policy(self.raw_error(400, {'error': {'error': {'code': 'DataInspectionFailed'}}})) def test_type_only_envelope_is_policy(self): self.assert_policy(self.raw_error( 400, {'error': {'type': 'content_policy_violation', 'message': 'safety system'}})) def test_input_output_inspection_code_variants_are_policy(self): for code in ('InputDataInspectionFailed', 'OutputDataInspectionFailed', 'input_data_inspection_failed'): with self.subTest(code=code): self.assert_policy(self.raw_error(400, {'error': {'code': code}})) def test_json_string_message_envelope_is_decoded_to_policy(self): inner = json.dumps({'code': 'OutputDataInspectionFailed', 'message': 'Output data may contain inappropriate content.'}) self.assert_policy(self.raw_error(400, {'error': {'message': inner}})) def test_bare_code_string_payload_is_policy(self): self.assert_policy(self.raw_error(400, b'"data_inspection_failed"')) def test_vendor_prefixed_message_without_code_field_is_policy(self): self.assert_policy(self.raw_error( 400, {'error': {'message': 'DataInspectionFailed: Input data may contain inappropriate content.'}})) def test_classification_is_idempotent_on_normalized_output(self): status, body = self.raw_error( 400, {'error': {'code': 'data_inspection_failed', 'message': 'Input data may contain inappropriate content.'}}) self.assert_policy((status, body)) again = MOD.public_error(status, MOD.public_json_dumps(body).encode(), '/v1/chat/completions') self.assertEqual(again, (status, body)) def test_unsupported_parameter_prose_without_code_is_not_policy(self): _, body = self.raw_error(400, {'error': {'message': 'content_filter unsupported: model-x'}}) self.assert_not_policy(body) def test_unsupported_content_filter_and_reasoning_effort_mentions_are_not_policy(self): for payload in ( {'error': {'code': 'unsupported_parameter', 'message': 'content_filter is not supported by this endpoint; ' 'reasoning_effort also unsupported'}}, {'error': {'message': 'unsupported parameters: content_filter, reasoning_effort ' 'are not valid for this model'}}): with self.subTest(payload=payload['error']['message']): _, body = self.raw_error(400, payload) self.assert_not_policy(body) def test_false_marker_in_arbitrary_message_is_not_policy(self): _, body = self.raw_error(400, {'error': { 'code': 'model_not_found', 'message': 'Model content_filter-v2 does not exist, check content_policy_violation ' 'docs and data_inspection_failed FAQ'}}) self.assert_not_policy(body) def test_structured_policy_beats_billing_looking_message(self): self.assert_policy(self.raw_error(403, {'error': { 'code': 'data_inspection_failed', 'message': 'Free quota exhausted. Please top up your credit balance.'}})) def test_text_only_policy_marker_does_not_override_billing_markers(self): _, body = self.raw_error(403, {'error': { 'message': 'Free quota exhausted. DataInspectionFailed: retry later'}}) self.assertEqual((body['error']['code'], body['error']['retryable']), ('upstream_billing_error', True)) def test_safe_request_id_is_preserved_without_upstream_prose(self): status, body = self.raw_error(400, {'error': { 'code': 'DataInspectionFailed', 'message': 'Input data may contain inappropriate content.', 'request_id': 'req-7f3a-public'}}) self.assert_policy((status, body)) self.assertEqual(body['error']['request_id'], 'req-7f3a-public') self.assertNotIn('inappropriate', json.dumps(body)) def test_secret_looking_request_id_is_not_echoed(self): status, body = self.raw_error( 400, {'error': {'code': 'content_filter', 'request_id': 'sk-live-secret123'}}) self.assert_policy((status, body)) self.assertNotIn('request_id', body['error']) self.assertNotIn('sk-live', json.dumps(body)) def test_deeply_nested_envelope_stays_bounded_and_generic(self): payload = {'code': 'data_inspection_failed'} for _ in range(30): payload = {'error': payload} status, body = self.raw_error(400, payload) self.assertEqual((status, body['error']['code']), (400, 'invalid_request')) class TokenStateDatabaseTests(unittest.TestCase): """A 401 diagnostic must read the effective gateway DB, not a legacy literal.""" ENV = ("GW_NEWAPI_DB", "IISHKO_GW_DB", "GATE_NEWAPI_DB", "GROK_BOT_CFG") def setUp(self): self._saved = {name: os.environ.get(name) for name in self.ENV} for name in self.ENV: os.environ.pop(name, None) tmp = tempfile.TemporaryDirectory() self.addCleanup(tmp.cleanup) self.dir = tmp.name def tearDown(self): for name, value in self._saved.items(): if value is None: os.environ.pop(name, None) else: os.environ[name] = value def db(self, name, rows): path = os.path.join(self.dir, name) with closing(sqlite3.connect(path)) as con: con.execute('CREATE TABLE tokens(id INTEGER PRIMARY KEY, "key" TEXT, status INTEGER,' ' remain_quota INTEGER, unlimited_quota INTEGER, deleted_at INTEGER)') con.executemany('INSERT INTO tokens("key", status, remain_quota, unlimited_quota,' ' deleted_at) VALUES(?,?,?,?,?)', rows) con.commit() return path def auth_error(self, key): return MOD.public_error(401, b'{"error":{"message":"Invalid token"}}', '/v1/chat/completions', api_key=key) def write_config(self, newapi_db): path = os.path.join(self.dir, 'config.json') with open(path, 'w', encoding='utf-8-sig') as fh: json.dump({'newapi_db': newapi_db, 'bot_token': 'x'}, fh) os.environ['GROK_BOT_CFG'] = path return path def test_shared_resolver_is_wired_and_resolves_late(self): self.assertIsNotNone(MOD._gateway_db_path, 'gateway_errors fell back to the hardcoded legacy DB path') # behaviour, not module shape: an alias set after import must be honoured, # which an import-time snapshot could never do late = self.db('late.db', [('k', 1, 42, 0, None)]) os.environ['IISHKO_GW_DB'] = late self.assertEqual(MOD.token_state('k'), (1, 42, 0)) def test_config_json_gateway_db_beats_the_legacy_literal(self): """A deployment that sets the path only in bot/config.json must not misread 401s.""" self.db('legacy.db', [('k', 4, 0, 0, None)]) configured = self.db('configured.db', [('k', 1, 7000, 0, None)]) self.write_config(configured) self.assertEqual(MOD.token_state('k'), (1, 7000, 0)) # an explicit env alias still outvotes the config file os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('k', 2, 900, 0, None)]) self.assertEqual(MOD.token_state('k'), (2, 900, 0)) def test_missing_or_bogus_config_path_falls_back_without_raising(self): os.environ['GROK_BOT_CFG'] = os.path.join(self.dir, 'no-such-dir', 'config.json') self.assertIsNone(MOD.token_state('k')) broken = os.path.join(self.dir, 'broken.json') with open(broken, 'w', encoding='utf-8-sig') as fh: fh.write('{"newapi_db": ') os.environ['GROK_BOT_CFG'] = broken self.assertIsNone(MOD.token_state('k')) # a config that names a nonexistent DB is not an error either: no key state self.write_config(os.path.join(self.dir, 'absent.db')) self.assertIsNone(MOD.token_state('k')) def test_env_precedence_decides_which_token_table_is_read(self): stale = self.db('legacy.db', [('k', 4, 0, 0, None)]) live = self.db('effective.db', [('k', 1, 5000, 0, None)]) os.environ['GW_NEWAPI_DB'] = stale # legacy-only unit keeps working self.assertEqual(MOD.token_state('k'), (4, 0, 0)) # a stale legacy alias must not outvote the DB the rest of the stack serves os.environ['GATE_NEWAPI_DB'] = live self.assertEqual(MOD.token_state('k'), (1, 5000, 0)) del os.environ['GATE_NEWAPI_DB'] self.assertEqual(MOD.token_state('k'), (4, 0, 0)) del os.environ['GW_NEWAPI_DB'] os.environ['GATE_NEWAPI_DB'] = stale os.environ['IISHKO_GW_DB'] = live # canonical name wins over GATE_NEWAPI_DB self.assertEqual(MOD.token_state('k'), (1, 5000, 0)) def test_zero_balance_key_is_reported_as_empty_not_invalid(self): os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('deadbeef', 1, 0, 0, None)]) status, body = self.auth_error('deadbeef') self.assertEqual((status, body['error']['code']), (402, 'api_key_empty')) def test_foreign_database_never_makes_a_healthy_key_look_empty(self): # The old hardcoded path belonged to another deployment: a drained key there # must not change this gateway's verdict about its own healthy key. self.db('legacy.db', [('healthy', 4, 0, 0, None)]) os.environ['IISHKO_GW_DB'] = self.db('effective.db', [('healthy', 1, 900000, 0, None)]) status, body = self.auth_error('healthy') self.assertEqual((status, body['error']['code']), (401, 'invalid_api_key')) if __name__ == '__main__': unittest.main()