Make legacy payment delivery retryable and keep gateway paths responsive
This commit is contained in:
@@ -37,3 +37,171 @@ def test_tg_login_refuses_cross_site_origin():
|
||||
resp = asyncio.run(ns["tg_login"](req))
|
||||
assert resp.status == 403
|
||||
assert json.loads(resp.body)["error"] == "bad_origin"
|
||||
|
||||
|
||||
def test_tg_login_never_holds_the_store_open_across_provisioning():
|
||||
"""connect+DDL must not run on the loop, and no connection may span a network await."""
|
||||
import asyncio
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import tempfile
|
||||
from contextlib import closing
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = os.path.join(tmp, "tg-provision.db")
|
||||
token_file = os.path.join(tmp, "admin.token")
|
||||
with open(token_file, "w", encoding="utf-8") as fh:
|
||||
fh.write("bearer-token\n")
|
||||
|
||||
state = {"opened": 0, "closed": 0, "held": [], "links": []}
|
||||
|
||||
class _Conn:
|
||||
def __init__(self, con):
|
||||
self._con = con
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._con, name)
|
||||
|
||||
def close(self):
|
||||
state["closed"] += 1
|
||||
self._con.close()
|
||||
|
||||
class _Req:
|
||||
headers = {"Origin": "https://example.com"}
|
||||
host = "example.com"
|
||||
app = {"sess": object()}
|
||||
|
||||
async def text(self):
|
||||
return json.dumps({"id": 123, "auth_date": str(int(time.time())), "hash": "0" * 64})
|
||||
|
||||
async def _newapi_call(session, method, path, bearer, body=None):
|
||||
# the store must already be closed when the request goes out
|
||||
state["held"].append(state["opened"] - state["closed"])
|
||||
if path == "/api/user/login":
|
||||
return 200, b'{"success": false}', None
|
||||
return 200, b'{"success": true, "data": {"id": 7}}', None
|
||||
|
||||
ns = _load("tg_login", "_tg_store_conn", "_tg_store_password", "_tg_store_password_put",
|
||||
sqlite3=sqlite3, os=os, secrets=secrets, asyncio=asyncio,
|
||||
logging=logging, LOG=logging.getLogger("tg_login_store"),
|
||||
TG_PROVISION_DB=db, _TG_SCHEMA_READY=False, TG_ADMIN_TOKEN_FILE=token_file,
|
||||
CONTROL_SESSION_KEY="sess", _tg_normalize=lambda data: data,
|
||||
_tg_check_hash=lambda data: True, _newapi_call=_newapi_call,
|
||||
_json_ok=lambda status, body: status == 200 and json.loads(body).get("success") is True,
|
||||
_tg_link_upsert=lambda *args: state["links"].append(args))
|
||||
real_conn = ns["_tg_store_conn"]
|
||||
|
||||
def tracked_conn():
|
||||
state["opened"] += 1
|
||||
return _Conn(real_conn())
|
||||
|
||||
ns["_tg_store_conn"] = tracked_conn
|
||||
|
||||
resp = asyncio.run(ns["tg_login"](_Req()))
|
||||
|
||||
assert resp.status == 502
|
||||
assert json.loads(resp.body)["error"] == "login_failed"
|
||||
# a read for the missing password plus a write once provisioning succeeded
|
||||
assert state["opened"] >= 2
|
||||
assert state["held"] and set(state["held"]) == {0}, state["held"]
|
||||
assert state["opened"] == state["closed"]
|
||||
assert state["links"] == [(123, "tg123")]
|
||||
# `with sqlite3.connect(...)` commits but does not close: on Windows the open
|
||||
# handle would break TemporaryDirectory cleanup.
|
||||
with closing(sqlite3.connect(db)) as con:
|
||||
row = con.execute("SELECT username, length(password) FROM tg_users"
|
||||
" WHERE tg_id=123").fetchone()
|
||||
assert row[0] == "tg123" and row[1] >= 24
|
||||
|
||||
|
||||
def test_tg_login_provision_recovery_keeps_the_store_closed_across_awaits():
|
||||
"""create->search->get->put recovery runs four round trips; no connection may span one."""
|
||||
import logging
|
||||
import os
|
||||
import secrets
|
||||
import sqlite3
|
||||
import tempfile
|
||||
from contextlib import closing
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
db = os.path.join(tmp, "tg-provision.db")
|
||||
token_file = os.path.join(tmp, "admin.token")
|
||||
with open(token_file, "w", encoding="utf-8") as fh:
|
||||
fh.write("bearer-token\n")
|
||||
|
||||
state = {"opened": 0, "closed": 0, "held": [], "links": [], "calls": [], "put_body": None}
|
||||
|
||||
class _Conn:
|
||||
def __init__(self, con):
|
||||
self._con = con
|
||||
|
||||
def __getattr__(self, name):
|
||||
return getattr(self._con, name)
|
||||
|
||||
def close(self):
|
||||
state["closed"] += 1
|
||||
self._con.close()
|
||||
|
||||
class _Req:
|
||||
headers = {"Origin": "https://example.com"}
|
||||
host = "example.com"
|
||||
app = {"sess": object()}
|
||||
|
||||
async def text(self):
|
||||
return json.dumps({"id": 123, "auth_date": str(int(time.time())), "hash": "0" * 64})
|
||||
|
||||
async def _newapi_call(session, method, path, bearer, body=None):
|
||||
# the store must already be closed when each of the four requests goes out
|
||||
state["held"].append(state["opened"] - state["closed"])
|
||||
state["calls"].append((method, path))
|
||||
if method == "POST" and path == "/api/user/":
|
||||
return 200, b'{"success": false, "message": "username already exists"}', None
|
||||
if method == "GET" and path.startswith("/api/user/search"):
|
||||
return 200, b'{"success": true, "data": {"items": [{"id": 7, "username": "tg123"}]}}', None
|
||||
if method == "GET" and path == "/api/user/7":
|
||||
return 200, b'{"success": true, "data": {"id": 7, "username": "tg123", "display_name": "tg"}}', None
|
||||
if method == "PUT" and path == "/api/user/":
|
||||
state["put_body"] = body
|
||||
return 200, b'{"success": true}', None
|
||||
if path == "/api/user/login":
|
||||
return 200, b'{"success": false}', None
|
||||
return 404, b'{"success": false}', None
|
||||
|
||||
ns = _load("tg_login", "_tg_store_conn", "_tg_store_password", "_tg_store_password_put",
|
||||
"_find_user_id", "_json_ok",
|
||||
sqlite3=sqlite3, os=os, secrets=secrets, asyncio=asyncio,
|
||||
logging=logging, LOG=logging.getLogger("tg_login_recovery"),
|
||||
TG_PROVISION_DB=db, _TG_SCHEMA_READY=False, TG_ADMIN_TOKEN_FILE=token_file,
|
||||
CONTROL_SESSION_KEY="sess", _tg_normalize=lambda data: data,
|
||||
_tg_check_hash=lambda data: True, _newapi_call=_newapi_call,
|
||||
_tg_link_upsert=lambda *args: state["links"].append(args))
|
||||
real_conn = ns["_tg_store_conn"]
|
||||
|
||||
def tracked_conn():
|
||||
state["opened"] += 1
|
||||
return _Conn(real_conn())
|
||||
|
||||
ns["_tg_store_conn"] = tracked_conn
|
||||
|
||||
resp = asyncio.run(ns["tg_login"](_Req()))
|
||||
|
||||
assert resp.status == 502
|
||||
assert json.loads(resp.body)["error"] == "login_failed"
|
||||
# the whole recovery chain ran, in order, and the full user object was resent
|
||||
assert state["calls"] == [("POST", "/api/user/"),
|
||||
("GET", "/api/user/search?keyword=tg123"),
|
||||
("GET", "/api/user/7"),
|
||||
("PUT", "/api/user/"),
|
||||
("POST", "/api/user/login")]
|
||||
assert state["put_body"]["id"] == 7 and state["put_body"]["username"] == "tg123"
|
||||
assert len(state["put_body"]["password"]) >= 24
|
||||
# no connection was open while a request was in flight, and none leaked
|
||||
assert state["held"] and set(state["held"]) == {0}, state["held"]
|
||||
assert state["opened"] == state["closed"]
|
||||
assert state["links"] == [(123, "tg123")]
|
||||
# the recovered password is what the store will serve on the next login
|
||||
with closing(sqlite3.connect(db)) as con:
|
||||
stored = con.execute("SELECT password FROM tg_users WHERE tg_id=123").fetchone()[0]
|
||||
assert stored == state["put_body"]["password"]
|
||||
|
||||
Reference in New Issue
Block a user