Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions examples/bruno-collection/Analyze/audio.bru
Original file line number Diff line number Diff line change
@@ -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);
});
}
32 changes: 32 additions & 0 deletions examples/bruno-collection/Analyze/text-invalid-token.bru
Original file line number Diff line number Diff line change
@@ -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");
});
}
40 changes: 40 additions & 0 deletions examples/bruno-collection/Analyze/text.bru
Original file line number Diff line number Diff line change
@@ -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);
});
}
16 changes: 16 additions & 0 deletions examples/bruno-collection/Health/health.bru
Original file line number Diff line number Diff line change
@@ -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
}
16 changes: 16 additions & 0 deletions examples/bruno-collection/Health/ready.bru
Original file line number Diff line number Diff line change
@@ -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
}
113 changes: 113 additions & 0 deletions examples/bruno-collection/README.md
Original file line number Diff line number Diff line change
@@ -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.
9 changes: 9 additions & 0 deletions examples/bruno-collection/bruno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"version": "1",
"name": "ScamShield API",
"type": "collection",
"ignore": [
"node_modules",
".git"
]
}
4 changes: 4 additions & 0 deletions examples/bruno-collection/environments/local.bru
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
vars {
baseUrl: http://127.0.0.1:8000
SCAMSHIELD_API_KEY: mock-local-token-not-a-real-credential
}
120 changes: 120 additions & 0 deletions examples/bruno-collection/mock_server.py
Original file line number Diff line number Diff line change
@@ -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 <MOCK_TOKEN>`; 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()
Loading