Repository navigation
Expand file tree
/
Copy pathbanking_api.py
More file actions
245 lines (218 loc) · 10.2 KB
/
Copy pathbanking_api.py
File metadata and controls
245 lines (218 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
"""Loopback-first HTTP API for authenticated Butter Bank ledger operations.
The API accepts opaque bearer credentials only. Credential validation remains
in the injected BankingService resolver; this server never accepts account-owner
references from request bodies and does not implement external payment settlement.
"""
from __future__ import annotations
import ipaddress
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import threading
from urllib.parse import parse_qs, unquote, urlsplit
from banking_service import (
AuthenticationError,
BankingService,
CredentialProviderUnavailable,
)
from financial_ledger import (
AccountAccessDenied,
IdempotencyConflict,
InsufficientFunds,
LedgerError,
)
MAX_REQUEST_BYTES = 64 * 1024
DEFAULT_MAX_WORKERS = 32
REQUEST_SOCKET_TIMEOUT_SECONDS = 10
class BoundedThreadingHTTPServer(ThreadingHTTPServer):
"""Limit concurrent request threads and release slots on every exit path."""
daemon_threads = True
block_on_close = False
def __init__(self, server_address, handler_class, max_workers=DEFAULT_MAX_WORKERS):
if (not isinstance(max_workers, int) or isinstance(max_workers, bool)
or max_workers < 1):
raise ValueError("max_workers must be a positive integer")
self._request_slots = threading.BoundedSemaphore(max_workers)
super().__init__(server_address, handler_class)
def process_request(self, request, client_address):
if not self._request_slots.acquire(blocking=False):
self.shutdown_request(request)
return
try:
super().process_request(request, client_address)
except Exception:
self._request_slots.release()
raise
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self._request_slots.release()
class BankingAPIHandler(BaseHTTPRequestHandler):
service: BankingService | None = None
def setup(self):
super().setup()
self.connection.settimeout(REQUEST_SOCKET_TIMEOUT_SECONDS)
server_version = "ButterBankAPI/0.1"
sys_version = ""
def _send_json(self, status, payload):
body = json.dumps(payload, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
if self.close_connection:
self.send_header("Connection", "close")
self.end_headers()
self.wfile.write(body)
def _credential(self):
headers = self.headers.get_all("Authorization", [])
if len(headers) != 1:
raise AuthenticationError("exactly one bearer credential is required")
scheme, separator, credential = headers[0].partition(" ")
if scheme.lower() != "bearer" or not separator or not credential.strip():
raise AuthenticationError("bearer credential required")
return credential.strip()
def _json_body(self):
if len(self.headers.get_all("Content-Type", [])) != 1:
raise ValueError("exactly one Content-Type is required")
if self.headers.get_content_type() != "application/json":
raise ValueError("Content-Type must be application/json")
if self.headers.get_all("Transfer-Encoding", []):
raise ValueError("Transfer-Encoding is not supported")
if self.headers.get_all("Content-Encoding", []):
raise ValueError("Content-Encoding is not supported")
lengths = self.headers.get_all("Content-Length", [])
if len(lengths) != 1:
raise ValueError("exactly one Content-Length is required")
raw_length = lengths[0]
if not raw_length.isascii() or not raw_length.isdecimal():
raise ValueError("invalid Content-Length")
length = int(raw_length)
if not 0 <= length <= MAX_REQUEST_BYTES:
raise ValueError("request body exceeds the permitted size")
raw = self.rfile.read(length)
if len(raw) != length:
raise ValueError("incomplete request body")
payload = json.loads(raw.decode("utf-8"))
if not isinstance(payload, dict):
raise ValueError("JSON request body must be an object")
return payload
def _handle_errors(self, operation):
try:
operation()
except CredentialProviderUnavailable:
self.close_connection = True
self._send_json(503, {"error": "credential_provider_unavailable"})
except AuthenticationError:
self.close_connection = True
self._send_json(401, {"error": "unauthorized"})
except AccountAccessDenied:
self.close_connection = True
self._send_json(403, {"error": "forbidden"})
except (InsufficientFunds, IdempotencyConflict):
self.close_connection = True
self._send_json(409, {"error": "conflict"})
except (LedgerError, ValueError, UnicodeDecodeError, json.JSONDecodeError):
self.close_connection = True
self._send_json(400, {"error": "invalid_request"})
except Exception:
self.close_connection = True
self._send_json(500, {"error": "internal_error"})
def do_GET(self):
def operation():
credential = self._credential()
parsed = urlsplit(self.path)
if parsed.path == "/currencies":
if parsed.query:
raise ValueError("query parameters are not supported on this route")
self._send_json(200, {"currencies": self.service.currencies(credential)})
return
if parsed.path == "/accounts":
if parsed.query:
raise ValueError("query parameters are not supported on this route")
self._send_json(200, {"accounts": self.service.accounts(credential)})
return
parts = parsed.path.split("/")
if len(parts) == 4 and parts[1] == "accounts" and parts[3] == "statement":
query = parse_qs(parsed.query, keep_blank_values=True, strict_parsing=True)
if set(query) - {"limit"} or any(len(values) != 1 for values in query.values()):
raise ValueError("invalid statement query parameters")
limit = int(query["limit"][0]) if "limit" in query else 100
account_id = unquote(parts[2])
statement = self.service.statement(credential, account_id, limit)
self._send_json(200, statement)
return
self._send_json(404, {"error": "not_found"})
self._handle_errors(operation)
def do_POST(self):
def operation():
credential = self._credential()
parsed = urlsplit(self.path)
if parsed.query:
raise ValueError("query parameters are not supported on POST routes")
payload = self._json_body()
if parsed.path == "/accounts":
if set(payload) - {"currency_code", "account_type"}:
raise ValueError("unexpected account fields")
if "currency_code" not in payload:
raise ValueError("currency_code is required")
account_id = self.service.open_account(
credential,
payload["currency_code"],
payload.get("account_type", "deposit"),
)
self._send_json(201, {"account_id": account_id})
return
if parsed.path == "/transfers":
allowed = {
"source_account_id", "destination_account_id",
"amount_minor", "idempotency_key", "description",
}
if set(payload) - allowed or not {
"source_account_id", "destination_account_id",
"amount_minor", "idempotency_key",
} <= set(payload):
raise ValueError("invalid transfer fields")
transaction_id = self.service.transfer(
credential,
payload["source_account_id"],
payload["destination_account_id"],
payload["amount_minor"],
payload["idempotency_key"],
payload.get("description", "Account transfer"),
)
self._send_json(200, {"transaction_id": transaction_id})
return
self._send_json(404, {"error": "not_found"})
self._handle_errors(operation)
def do_PUT(self):
self._send_json(405, {"error": "method_not_allowed"})
def do_PATCH(self):
self._send_json(405, {"error": "method_not_allowed"})
def do_DELETE(self):
self._send_json(405, {"error": "method_not_allowed"})
def log_message(self, format, *args):
# Avoid writing request headers or account identifiers to default logs.
return
def create_server(
service: BankingService, host="127.0.0.1", port=8000,
max_workers=DEFAULT_MAX_WORKERS,
):
"""Create a bounded API server bound only to an IPv4 loopback address."""
if not isinstance(service, BankingService):
raise TypeError("service must be a BankingService")
if not isinstance(host, str):
raise TypeError("host must be an IPv4 loopback address")
try:
address = ipaddress.ip_address(host)
except ValueError as exc:
raise ValueError("banking API host must be an IPv4 loopback address") from exc
if not isinstance(address, ipaddress.IPv4Address) or not address.is_loopback:
raise ValueError("banking API host must be an IPv4 loopback address")
if not isinstance(port, int) or isinstance(port, bool) or not 0 <= port <= 65535:
raise ValueError("port must be an integer from 0 through 65535")
handler = type("ConfiguredBankingAPIHandler", (BankingAPIHandler,), {
"service": service,
})
return BoundedThreadingHTTPServer((host, port), handler, max_workers=max_workers)