diff --git a/examples/bruno-collection/Analyze/audio.bru b/examples/bruno-collection/Analyze/audio.bru new file mode 100644 index 0000000..8ee3953 --- /dev/null +++ b/examples/bruno-collection/Analyze/audio.bru @@ -0,0 +1,38 @@ +meta { + name: Analyze audio + type: http + seq: 2 +} + +post { + url: {{baseUrl}}/audio + body: multipartForm + auth: bearer +} + +auth:bearer { + token: {{SCAMSHIELD_API_KEY}} +} + +body:multipart-form { + file: @file(../../tests/test_audio.m4a) +} + +assert { + res.status: eq 200 + res.body.label: isString + res.body.score: isString + res.body.certainty: isNumber + res.body.reason: isString +} + +tests { + test("assessment uses the documented enums and ranges", function () { + const result = res.getBody(); + expect(["Scam", "Scam Likely", "Safe"]).to.include(result.label); + expect(["High", "Medium", "Low"]).to.include(result.score); + expect(Number.isInteger(result.certainty)).to.equal(true); + expect(result.certainty).to.be.within(0, 100); + expect(result.reason.length).to.be.within(1, 2000); + }); +} diff --git a/examples/bruno-collection/Analyze/text-invalid-token.bru b/examples/bruno-collection/Analyze/text-invalid-token.bru new file mode 100644 index 0000000..b771953 --- /dev/null +++ b/examples/bruno-collection/Analyze/text-invalid-token.bru @@ -0,0 +1,32 @@ +meta { + name: Analyze text (invalid token) + type: http + seq: 3 +} + +post { + url: {{baseUrl}}/text + body: json + auth: bearer +} + +auth:bearer { + token: invalid-fake-token-for-401-demo +} + +body:json { + { + "body": "This request is expected to be rejected." + } +} + +assert { + res.status: eq 401 + res.body.detail: eq Invalid or missing bearer token +} + +tests { + test("401 asks the client for a bearer token", function () { + expect(res.getHeader("www-authenticate")).to.equal("Bearer"); + }); +} diff --git a/examples/bruno-collection/Analyze/text.bru b/examples/bruno-collection/Analyze/text.bru new file mode 100644 index 0000000..eb210c2 --- /dev/null +++ b/examples/bruno-collection/Analyze/text.bru @@ -0,0 +1,40 @@ +meta { + name: Analyze text + type: http + seq: 1 +} + +post { + url: {{baseUrl}}/text + body: json + auth: bearer +} + +auth:bearer { + token: {{SCAMSHIELD_API_KEY}} +} + +body:json { + { + "body": "Congratulations! Pay a fee to claim your prize." + } +} + +assert { + res.status: eq 200 + res.body.label: isString + res.body.score: isString + res.body.certainty: isNumber + res.body.reason: isString +} + +tests { + test("assessment uses the documented enums and ranges", function () { + const result = res.getBody(); + expect(["Scam", "Scam Likely", "Safe"]).to.include(result.label); + expect(["High", "Medium", "Low"]).to.include(result.score); + expect(Number.isInteger(result.certainty)).to.equal(true); + expect(result.certainty).to.be.within(0, 100); + expect(result.reason.length).to.be.within(1, 2000); + }); +} diff --git a/examples/bruno-collection/Health/health.bru b/examples/bruno-collection/Health/health.bru new file mode 100644 index 0000000..6b306fe --- /dev/null +++ b/examples/bruno-collection/Health/health.bru @@ -0,0 +1,16 @@ +meta { + name: Health + type: http + seq: 1 +} + +get { + url: {{baseUrl}}/health + body: none + auth: none +} + +assert { + res.status: eq 200 + res.body.status: eq ok +} diff --git a/examples/bruno-collection/Health/ready.bru b/examples/bruno-collection/Health/ready.bru new file mode 100644 index 0000000..dee0afa --- /dev/null +++ b/examples/bruno-collection/Health/ready.bru @@ -0,0 +1,16 @@ +meta { + name: Ready + type: http + seq: 2 +} + +get { + url: {{baseUrl}}/ready + body: none + auth: none +} + +assert { + res.status: eq 200 + res.body.status: eq ready +} diff --git a/examples/bruno-collection/README.md b/examples/bruno-collection/README.md new file mode 100644 index 0000000..fbc1547 --- /dev/null +++ b/examples/bruno-collection/README.md @@ -0,0 +1,113 @@ +# ScamShield Bruno collection + +A [Bruno](https://www.usebruno.com/) collection for the ScamShield API, plus a small +offline mock server so you can try it without credentials, Redis, FFmpeg, model weights +or any paid provider call. + +## Contents + +| Path | Purpose | +| --- | --- | +| `bruno.json` | Collection definition | +| `environments/local.bru` | `baseUrl` and `SCAMSHIELD_API_KEY` for the `local` environment | +| `Health/health.bru` | `GET /health` (no auth) | +| `Health/ready.bru` | `GET /ready` (no auth) | +| `Analyze/text.bru` | `POST /text` (JSON body, bearer auth) | +| `Analyze/audio.bru` | `POST /audio` (multipart field `file`, bearer auth) | +| `Analyze/text-invalid-token.bru` | `POST /text` with a wrong token; expects 401 | +| `mock_server.py` | Standard-library mock of the four endpoints | +| `test_mock_server.py` | Standard-library `unittest` tests for the mock's authentication handling | + +## Local base URL and placeholder token + +The `local` environment sets: + +- `baseUrl` = `http://127.0.0.1:8000` +- `SCAMSHIELD_API_KEY` = `mock-local-token-not-a-real-credential` + +The token is a fake placeholder that only the mock server accepts. It is not a real +credential. The invalid-token request uses a different fake value +(`invalid-fake-token-for-401-demo`). + +To point the collection at a real server, do **not** commit a real token. Override +`SCAMSHIELD_API_KEY` locally, for example as a Bruno secret variable or in a file that +is not tracked by git. A real server enforces a quota (10 requests per 60 seconds per +token by default), so repeated runs can return 429, and live `/text` and `/audio` +calls incur provider usage. + +## Run the mock server + +Needs Python 3.13+ and nothing else. From the repository root: + +```bash +python3 examples/bruno-collection/mock_server.py +``` + +It listens only on `127.0.0.1:8000` and stops with Ctrl+C. + +> **Port warning:** the mock uses the same port as the real API's default +> (`8000`). If another service, including a real ScamShield server, is already using +> it, the mock exits with an error. Stop that service first so requests never reach +> a real server by mistake. + +### Mock behavior + +- `GET /health` returns `200 {"status":"ok"}`; `GET /ready` returns `200 {"status":"ready"}`. + Neither needs a token. +- `POST /text` and `POST /audio` require `Authorization: Bearer mock-local-token-not-a-real-credential`. + Any other token, or none, gets `401 {"detail":"Invalid or missing bearer token"}` with + `WWW-Authenticate: Bearer`. The token is checked from the headers before the body is + read; unauthorized requests get the 401 immediately and the connection is closed. +- With the right token both return the same fixed assessment + (`label`, `score`, `certainty`, `reason`) using the real field names and enum values. +- Bodies of unauthorized requests are not read or processed. Bodies of authorized + requests and uploads are read and discarded without parsing. Nothing is stored and nothing leaves your machine. +- Because unauthorized bodies are not consumed, a client sending a large unauthorized + upload may see a connection reset instead of receiving the complete 401 response. The + small invalid-token request in this collection is not affected. +- It does not simulate 413, 415, 422, 429, 502 or 503, or the Redis-unavailable `/ready` 503. + +## Import the collection in the Bruno app + +1. Open Bruno and choose **Open Collection**. +2. Select the `examples/bruno-collection` folder. +3. Choose the **local** environment in the environment selector. +4. Start the mock server, then send the requests. + +## Run the collection offline from the command line + +With the mock server running in one terminal, in a second terminal: + +```bash +cd examples/bruno-collection +bru run -r --env local +``` + +Expected: all requests pass. `/health` and `/ready` return 200, `/text` and `/audio` +return 200 with a valid assessment, and the invalid-token request returns 401. + +The audio request uploads the repository's existing `tests/test_audio.m4a` through the +relative path `../../tests/test_audio.m4a`, so run the collection from inside the +repository. Do not point the audio request at a real server with private recordings. + +## Test the mock server + +The mock's authentication behavior has its own standard-library tests. They start a +throwaway server on an ephemeral port, so the mock does not need to be running and +port 8000 is not used. From the repository root: + +```bash +python3 -m unittest discover -s examples/bruno-collection -p "test_*.py" +``` + +They check that a missing or invalid token with a JSON body gets `401` with +`WWW-Authenticate: Bearer`, that unauthorized bodies are not read (including a request +that declares a large body and never sends it), and that a valid token gets `200` with +the fixed assessment. + +## Assertions + +The requests check status codes, field types and the documented enums and ranges +(`label` is `Scam`, `Scam Likely` or `Safe`; `score` is `High`, `Medium` or `Low`; +`certainty` is an integer from 0 to 100). They do not assert specific labels, because +real model output varies. diff --git a/examples/bruno-collection/bruno.json b/examples/bruno-collection/bruno.json new file mode 100644 index 0000000..3e030ee --- /dev/null +++ b/examples/bruno-collection/bruno.json @@ -0,0 +1,9 @@ +{ + "version": "1", + "name": "ScamShield API", + "type": "collection", + "ignore": [ + "node_modules", + ".git" + ] +} diff --git a/examples/bruno-collection/environments/local.bru b/examples/bruno-collection/environments/local.bru new file mode 100644 index 0000000..8c28ff8 --- /dev/null +++ b/examples/bruno-collection/environments/local.bru @@ -0,0 +1,4 @@ +vars { + baseUrl: http://127.0.0.1:8000 + SCAMSHIELD_API_KEY: mock-local-token-not-a-real-credential +} diff --git a/examples/bruno-collection/mock_server.py b/examples/bruno-collection/mock_server.py new file mode 100644 index 0000000..3afe968 --- /dev/null +++ b/examples/bruno-collection/mock_server.py @@ -0,0 +1,120 @@ +"""Offline mock of the ScamShield API for the Bruno collection. + +Standard library only. Binds to 127.0.0.1:8000 and makes no outbound requests. +Bodies of unauthorized requests are not read or processed; bodies of authorized requests +(including uploaded audio) are read and dropped without parsing or storing them. +Responses are fixed so the collection is deterministic. +""" +import json +import secrets +import sys +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +HOST = "127.0.0.1" +PORT = 8000 + +# The only token this mock accepts. It is a fake value, not a real credential, +# and matches SCAMSHIELD_API_KEY in environments/local.bru. +MOCK_TOKEN = "mock-local-token-not-a-real-credential" + +PROTECTED_PATHS = {"/text", "/audio"} + +# Fixed response using the real field names, types and enum values. +ASSESSMENT = { + "label": "Safe", + "score": "Low", + "certainty": 80, + "reason": "Fixed mock response; no analysis was performed.", +} + + +def has_valid_token(header: str) -> bool: + """Return True for `Bearer `; the scheme is case-insensitive.""" + scheme, _, token = header.partition(" ") + return scheme.lower() == "bearer" and secrets.compare_digest( + token.encode(), MOCK_TOKEN.encode() + ) + + +class MockHandler(BaseHTTPRequestHandler): + """Serve fixed responses for /health, /ready, /text and /audio.""" + + server_version = "ScamShieldMock" + + def _send_json(self, status, payload, headers=None): + data = json.dumps(payload).encode() + self.send_response(status) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(data))) + for name, value in (headers or {}).items(): + self.send_header(name, value) + self.end_headers() + self.wfile.write(data) + + def _discard_body(self): + """Read and drop the body of an authorized request without storing it.""" + try: + remaining = int(self.headers.get("Content-Length", "0")) + except ValueError: + return + while remaining > 0: + chunk = self.rfile.read(min(remaining, 65536)) + if not chunk: + break + remaining -= len(chunk) + + def do_GET(self): # pylint: disable=invalid-name + """Handle the unauthenticated probes.""" + if self.path == "/health": + self._send_json(200, {"status": "ok"}) + elif self.path == "/ready": + self._send_json(200, {"status": "ready"}) + else: + self._send_json(404, {"detail": "Not Found"}) + + def do_POST(self): # pylint: disable=invalid-name + """Handle the protected analysis endpoints.""" + if self.path not in PROTECTED_PATHS: + self._reject(404, {"detail": "Not Found"}) + return + # Check the token from the headers alone, before touching the body. + if not has_valid_token(self.headers.get("Authorization", "")): + self._reject( + 401, + {"detail": "Invalid or missing bearer token"}, + {"WWW-Authenticate": "Bearer"}, + ) + return + self._discard_body() + self._send_json(200, ASSESSMENT) + + def _reject(self, status, payload, headers=None): + """Respond without reading the body, then close the connection. + + Closing tells the client not to reuse the connection, so the unread + request data is dropped with it instead of being parsed as a new request. + """ + self.close_connection = True + self._send_json(status, payload, {"Connection": "close", **(headers or {})}) + + +def main(): + """Run the mock until interrupted.""" + try: + server = ThreadingHTTPServer((HOST, PORT), MockHandler) + except OSError as exc: + sys.exit( + f"Could not bind {HOST}:{PORT} ({exc}). Another service may already be " + "using this port; stop it and try again." + ) + print(f"ScamShield mock listening on http://{HOST}:{PORT} (Ctrl+C to stop)") + try: + server.serve_forever() + except KeyboardInterrupt: + print("\nStopped.") + finally: + server.server_close() + + +if __name__ == "__main__": + main() diff --git a/examples/bruno-collection/test_mock_server.py b/examples/bruno-collection/test_mock_server.py new file mode 100644 index 0000000..a663d9e --- /dev/null +++ b/examples/bruno-collection/test_mock_server.py @@ -0,0 +1,85 @@ +"""Tests for the offline mock server's authentication handling. + +Standard library only. Each test talks to a real MockHandler over loopback on an +ephemeral port, so it cannot clash with a service on port 8000 and makes no +outbound requests. +""" +import http.client +import json +import socket +import threading +import unittest +from http.server import ThreadingHTTPServer +from unittest import mock + +import mock_server + +BODY = json.dumps({"body": "hello"}) +JSON_HEADERS = {"Content-Type": "application/json"} + + +class MockAuthTest(unittest.TestCase): + """Unauthorized requests get an immediate 401 without reading the body.""" + + @classmethod + def setUpClass(cls): + cls.server = ThreadingHTTPServer(("127.0.0.1", 0), mock_server.MockHandler) + cls.port = cls.server.server_address[1] + threading.Thread(target=cls.server.serve_forever, daemon=True).start() + + @classmethod + def tearDownClass(cls): + cls.server.shutdown() + cls.server.server_close() + + def post(self, headers): + """POST a small JSON body to /text and return (status, challenge, body).""" + conn = http.client.HTTPConnection("127.0.0.1", self.port, timeout=3) + try: + conn.request("POST", "/text", BODY, {**JSON_HEADERS, **headers}) + response = conn.getresponse() + return response.status, response.getheader("WWW-Authenticate"), response.read() + finally: + conn.close() + + def test_unauthorized_returns_401_and_never_reads_body(self): + cases = { + "missing token": {}, + "invalid token": {"Authorization": "Bearer wrong"}, + } + for name, headers in cases.items(): + with self.subTest(name), mock.patch.object( + mock_server.MockHandler, "_discard_body" + ) as discard: + status, challenge, data = self.post(headers) + self.assertEqual(status, 401) + self.assertEqual(challenge, "Bearer") + self.assertEqual( + json.loads(data), {"detail": "Invalid or missing bearer token"} + ) + discard.assert_not_called() + + def test_unsent_body_does_not_delay_401(self): + # The headers promise a large body that is never sent. If the server tried + # to read it, it would block and the recv below would time out. + request = ( + b"POST /text HTTP/1.1\r\nHost: localhost\r\n" + b"Content-Length: 1000000\r\n\r\n" + ) + with socket.create_connection(("127.0.0.1", self.port), timeout=3) as conn: + conn.sendall(request) + self.assertTrue(conn.recv(4096).startswith(b"HTTP/1.0 401")) + + def test_valid_token_returns_200_and_calls_discard_body(self): + token = "Bearer " + mock_server.MOCK_TOKEN + with mock.patch.object( + mock_server.MockHandler, "_discard_body", autospec=True + ) as discard: + status, _, data = self.post({"Authorization": token}) + self.assertEqual(status, 200) + self.assertEqual(json.loads(data), mock_server.ASSESSMENT) + discard.assert_called_once() + + +if __name__ == "__main__": + unittest.main()