80 lines
2.8 KiB
Python
80 lines
2.8 KiB
Python
"""Read-only Postmark prerequisite verifier. Never prints tokens or response bodies."""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import sys
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
|
|
BASE = "https://api.postmarkapp.com"
|
|
|
|
|
|
def build_readonly_request(path: str, token: str) -> urllib.request.Request:
|
|
"""Construct a server-token GET request without logging credential material."""
|
|
return urllib.request.Request(
|
|
f"{BASE}{path}",
|
|
headers={
|
|
"Accept": "application/json",
|
|
"X-Postmark-Server-Token": token,
|
|
},
|
|
)
|
|
|
|
|
|
def get(path: str, token: str) -> object:
|
|
request = build_readonly_request(path, token)
|
|
with urllib.request.urlopen(request, timeout=15) as response:
|
|
return json.loads(response.read())
|
|
|
|
|
|
def safe_http_failure(error: urllib.error.HTTPError, path: str) -> str:
|
|
"""Return only documented Postmark error fields; never emit request data."""
|
|
error_code = None
|
|
message = None
|
|
try:
|
|
body = json.loads(error.read())
|
|
if isinstance(body, dict):
|
|
raw_code = body.get("ErrorCode")
|
|
raw_message = body.get("Message")
|
|
error_code = raw_code if isinstance(raw_code, int) else None
|
|
message = raw_message if isinstance(raw_message, str) else None
|
|
except (OSError, UnicodeDecodeError, json.JSONDecodeError):
|
|
pass
|
|
detail = f" endpoint={path}"
|
|
if error_code is not None:
|
|
detail += f" postmark_error_code={error_code}"
|
|
if message:
|
|
detail += f" postmark_message={message!r}"
|
|
return f"FAIL Postmark HTTP {error.code}{detail}"
|
|
|
|
|
|
def main() -> int:
|
|
token = os.environ.get("POSTMARK_SERVER_TOKEN", "")
|
|
if not token:
|
|
print("FAIL token unavailable")
|
|
return 1
|
|
for path in ("/server", "/message-streams/outbound"):
|
|
try:
|
|
response = get(path, token)
|
|
except urllib.error.HTTPError as error:
|
|
print(safe_http_failure(error, path))
|
|
return 1
|
|
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError):
|
|
print(f"FAIL Postmark read-only request unavailable endpoint={path}")
|
|
return 1
|
|
if path == "/server":
|
|
server = response
|
|
else:
|
|
stream = response
|
|
server_ok = isinstance(server, dict) and bool(server.get("Name"))
|
|
stream_ok = isinstance(stream, dict) and stream.get("ID") == "outbound" and stream.get("MessageStreamType") == "Transactional"
|
|
# Sender-signature inspection is deliberately excluded: /senders requires
|
|
# an account token, while this component is restricted to a server token.
|
|
print(f"server={'ok' if server_ok else 'fail'} stream={'ok' if stream_ok else 'fail'}")
|
|
return 0 if server_ok and stream_ok else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|