#!/usr/bin/env python3 """ FleetBridge Order Source API — self-certification script. Run this against YOUR OWN staging FleetBridge credentials to verify your integration matches the contract documented in index.html / ORDER_SOURCE_INTEGRATION_API.md. It exercises only externally observable HTTP behavior — no FleetBridge source access is required or used. Usage: python3 certify.py config.json [--out results.json] config.json fields (see config.example.json): baseUrl e.g. "https://staging.your-fleetbridge-host" apiKey your staging Order Source API key ("key_" + 64 hex chars) externalBranchId a real branch reference your Order Source is configured with webhookTestSupported set true only if you have already registered a webhook endpoint for this Order Source and want /webhooks/test exercised Exit code is 0 only if every REQUIRED check passes. A human-readable summary is printed to stdout; a full machine-readable report is written to results.json (or --out). Requires Python 3.8+ standard library only — no pip install. """ import argparse import json import ssl import sys import time import urllib.error import urllib.request from datetime import datetime, timedelta, timezone class Check: def __init__(self, name, required=True): self.name = name self.required = required self.passed = None self.detail = "" class Certifier: def __init__(self, config): self.base_url = config["baseUrl"].rstrip("/") self.api_key = config["apiKey"] self.external_branch_id = config.get("externalBranchId", "MAIN-BRANCH") self.webhook_test_supported = config.get("webhookTestSupported", False) self.checks = [] self.ctx = ssl.create_default_context() self._run_suffix = str(int(time.time())) def _request(self, method, path, body=None, headers=None, include_key=True): url = self.base_url + path data = None req_headers = {"Content-Type": "application/json"} if headers: req_headers.update(headers) if include_key: req_headers["X-Api-Key"] = self.api_key if body is not None: data = json.dumps(body).encode("utf-8") req = urllib.request.Request(url, data=data, headers=req_headers, method=method) try: with urllib.request.urlopen(req, context=self.ctx, timeout=15) as resp: raw = resp.read() parsed = json.loads(raw) if raw else None return resp.status, dict(resp.headers), parsed except urllib.error.HTTPError as e: raw = e.read() parsed = None if raw: try: parsed = json.loads(raw) except ValueError: parsed = raw.decode("utf-8", errors="replace") return e.code, dict(e.headers or {}), parsed def _record(self, name, required, passed, detail): c = Check(name, required) c.passed = passed c.detail = detail self.checks.append(c) status = "PASS" if passed else ("FAIL" if required else "WARN") print(f"[{status}] {name} — {detail}") return passed def run(self): print(f"Certifying against {self.base_url}\n") # 1. Missing API key must be rejected (bare 401, no ProblemDetails body) status, _, body = self._request( "GET", "/api/v1/orders/by-external-id/does-not-exist", include_key=False ) self._record( "auth.missing_key_rejected", True, status == 401, f"expected 401 with no key, got {status}", ) # 2. Valid key is accepted (404 on unknown external id, not 401) status, _, body = self._request( "GET", f"/api/v1/orders/by-external-id/nonexistent-{self._run_suffix}" ) self._record( "auth.valid_key_accepted", True, status == 404, f"expected 404 (unknown order, valid key) got {status}", ) # 3. Create — minimal valid order external_order_id = f"CERT-{self._run_suffix}" idem_key = f"cert-{self._run_suffix}" create_body = { "externalOrderId": external_order_id, "externalBranchId": self.external_branch_id, "pickup": {"address": "Certification Pickup", "lat": 31.9021, "lng": 35.2034}, "dropoff": { "customerName": "Certification Tester", "customerPhone": "+10000000000", "address": "Certification Dropoff", "lat": 31.9080, "lng": 35.2050, }, "payment": {"method": "Cash", "amount": 10, "currency": "USD"}, "preparationTimeMinutes": 5, } status, _, body = self._request( "POST", "/api/v1/orders", body=create_body, headers={"Idempotency-Key": idem_key} ) create_ok = status == 201 and isinstance(body, dict) and "platformOrderId" in body self._record( "create.minimal_order", True, create_ok, f"status={status}, platformOrderId present={isinstance(body, dict) and 'platformOrderId' in body}", ) if not create_ok: self._record("abort", True, False, "create failed — skipping dependent checks") return self._finish() platform_order_id = body["platformOrderId"] # 4. Idempotent replay — same key, same body → same platformOrderId, 201 again status2, _, body2 = self._request( "POST", "/api/v1/orders", body=create_body, headers={"Idempotency-Key": idem_key} ) self._record( "idempotency.same_key_same_body_replay", True, status2 == 201 and isinstance(body2, dict) and body2.get("platformOrderId") == platform_order_id, f"status={status2}, platformOrderId matches={isinstance(body2, dict) and body2.get('platformOrderId') == platform_order_id}", ) # 5. GetById status, _, body = self._request("GET", f"/api/v1/orders/{platform_order_id}") self._record( "read.get_by_id", True, status == 200 and isinstance(body, dict) and body.get("externalOrderId") == external_order_id, f"status={status}", ) # 6. GetByExternalId status, _, body = self._request( "GET", f"/api/v1/orders/by-external-id/{external_order_id}" ) self._record( "read.get_by_external_id", True, status == 200 and isinstance(body, dict) and body.get("platformOrderId") == platform_order_id, f"status={status}", ) # 7. GetStatus status, _, body = self._request("GET", f"/api/v1/orders/{platform_order_id}/status") self._record( "read.get_status", True, status == 200 and isinstance(body, dict) and "orderStatus" in body, f"status={status}", ) # 8. GetTrackingHistory — must be 200 with an array, even if empty, not an error status, _, body = self._request( "GET", f"/api/v1/orders/{platform_order_id}/tracking-history" ) self._record( "read.get_tracking_history", True, status == 200 and isinstance(body, list), f"status={status}, is_array={isinstance(body, list)}", ) # 9. Update — partial patch of a single field status, _, body = self._request( "PATCH", f"/api/v1/orders/{platform_order_id}", body={"notes": "Certification update check"}, ) self._record( "update.partial_patch", True, status == 200, f"status={status}", ) # 10. Cancel status, _, body = self._request( "POST", f"/api/v1/orders/{platform_order_id}/cancel", body={"reason": "certification run"} ) cancel_ok = status == 200 and isinstance(body, dict) and body.get("status") in ( "Cancelled", "CancellationRequested", ) self._record( "cancel.first_call", True, cancel_ok, f"status={status}, resultStatus={body.get('status') if isinstance(body, dict) else None}", ) # 11. Cancel again — must stay idempotent (still 2xx), never a 5xx or duplicate side effect status, _, body = self._request( "POST", f"/api/v1/orders/{platform_order_id}/cancel", body={"reason": "certification run repeat"} ) self._record( "cancel.idempotent_repeat", True, status == 200, f"expected 200 on repeat cancel, got {status}", ) # 12. Invalid create — missing required field must yield 400 with an errorCode invalid_body = dict(create_body) invalid_body["externalOrderId"] = f"CERT-INVALID-{self._run_suffix}" del invalid_body["dropoff"] status, _, body = self._request("POST", "/api/v1/orders", body=invalid_body) self._record( "validation.missing_required_field", True, status == 400 and isinstance(body, dict) and "errorCode" in body, f"status={status}, errorCode={body.get('errorCode') if isinstance(body, dict) else None}", ) # 13. Unknown order lookup after a real one exists — still isolated 404, not leaked info status, _, body = self._request( "GET", f"/api/v1/orders/by-external-id/definitely-not-mine-{self._run_suffix}" ) self._record( "isolation.unknown_order_404", True, status == 404, f"status={status}", ) # 14. Optional — webhook test trigger, only if the integrator has a registered endpoint if self.webhook_test_supported: status, _, body = self._request("POST", "/api/v1/webhooks/test") self._record( "webhooks.test_trigger", False, status == 200, f"status={status} (requires a webhook endpoint already registered for this Order Source)", ) else: self._record( "webhooks.test_trigger", False, True, "skipped — webhookTestSupported=false in config", ) return self._finish() def _finish(self): required_failed = [c for c in self.checks if c.required and not c.passed] return required_failed def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("config", help="Path to your config.json (see config.example.json)") parser.add_argument("--out", default="results.json", help="Where to write the machine-readable report") args = parser.parse_args() with open(args.config) as f: config = json.load(f) certifier = Certifier(config) required_failed = certifier.run() report = { "baseUrl": certifier.base_url, "ranAtUtc": datetime.now(timezone.utc).isoformat(), "checks": [ {"name": c.name, "required": c.required, "passed": c.passed, "detail": c.detail} for c in certifier.checks ], "result": "PASS" if not required_failed else "FAIL", } with open(args.out, "w") as f: json.dump(report, f, indent=2) print(f"\nWrote {args.out}") if required_failed: print(f"\nFAILED — {len(required_failed)} required check(s) did not pass.") sys.exit(1) else: print("\nPASSED — all required checks succeeded.") sys.exit(0) if __name__ == "__main__": main()