Building 70 Projects ranging from beginner to advanced so anyone can — learn from, build upon, use as a reference, or even copy directly. Owned by my cybersecurity company 👇
Go aicertificationcloud-engineeringcybercybersecuritycybersecurity-analystcybersecurity-certificationcybersecurity-certificationscybersecurity-educationcybersecurity-jobscybersecurity-portfoliocybersecurity-projectscybersecurity-toolsgrchackinglearningpentestingproject-repositoryprojetcspython
fix(not-sandboxed): the tunnel could never have started, and three edge defects behind it
CarterPerez-dev28df5f374bf1
diff --git a/PROJECTS/beginner/prompt-injection-firewall/cloudflared.compose.yml b/PROJECTS/beginner/prompt-injection-firewall/cloudflared.compose.ymlindex c808964a..0df606d5 100644--- a/PROJECTS/beginner/prompt-injection-firewall/cloudflared.compose.yml+++ b/PROJECTS/beginner/prompt-injection-firewall/cloudflared.compose.yml@@ -1,18 +1,19 @@# =============================================================================-# AngelaMos | 2026+# ©AngelaMos | 2026# cloudflared.compose.yml# =============================================================================# Cloudflare Tunnel for production remote access-# Usage: docker compose -f compose.yml -f cloudflared.compose.yml up -d+# Usage: just tunnel+# The tunnel's public hostname must route to http://nginx:80# =============================================================================services:cloudflared:image: cloudflare/cloudflared:latest- container_name: arena-ui-tunnel- command: tunnel run --token ${CLOUDFLARE_TUNNEL_TOKEN}+ container_name: not-sandboxed-arena-tunnel+ command: tunnel --no-autoupdate run --token ${CLOUDFLARE_TUNNEL_TOKEN:?set CLOUDFLARE_TUNNEL_TOKEN in .env}networks:- - app+ - arenadepends_on:nginx:condition: service_starteddiff --git a/PROJECTS/beginner/prompt-injection-firewall/frontend/src/api/hooks/index.ts b/PROJECTS/beginner/prompt-injection-firewall/frontend/src/api/hooks/index.tsindex 13c33899..9ba1eb5d 100644--- a/PROJECTS/beginner/prompt-injection-firewall/frontend/src/api/hooks/index.ts+++ b/PROJECTS/beginner/prompt-injection-firewall/frontend/src/api/hooks/index.ts@@ -3,7 +3,7 @@// index.ts// ===================-import { useMutation, useQuery } from '@tanstack/react-query'+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'import {type AttemptRequest,type AttemptResponse,@@ -13,8 +13,9 @@ import {type SessionResponse,sessionResponseSchema,} from '@/api/types'-import { API_ENDPOINTS, QUERY_CONFIG, QUERY_KEYS } from '@/config'+import { API_ENDPOINTS, HTTP_STATUS, QUERY_CONFIG, QUERY_KEYS } from '@/config'import { apiClient } from '@/core/api'+import { ApiError } from '@/core/api/errors'export const useLevels = () =>useQuery<LevelsResponse>({@@ -40,11 +41,22 @@ export const useSession = () =>},})-export const useAttempt = () =>- useMutation<AttemptResponse, Error, AttemptRequest>({+export const useAttempt = () => {+ const client = useQueryClient()++ return useMutation<AttemptResponse, Error, AttemptRequest>({retry: QUERY_CONFIG.RETRY.NONE,mutationFn: async (request) => {const { data } = await apiClient.post(API_ENDPOINTS.ARENA.ATTEMPT, request)return attemptResponseSchema.parse(data)},+ onError: (error) => {+ if (+ error instanceof ApiError &&+ error.statusCode === HTTP_STATUS.NOT_FOUND+ ) {+ void client.refetchQueries({ queryKey: QUERY_KEYS.SESSION })+ }+ },})+}diff --git a/PROJECTS/beginner/prompt-injection-firewall/frontend/src/config.ts b/PROJECTS/beginner/prompt-injection-firewall/frontend/src/config.tsindex 39bd5181..47f34d9c 100644--- a/PROJECTS/beginner/prompt-injection-firewall/frontend/src/config.ts+++ b/PROJECTS/beginner/prompt-injection-firewall/frontend/src/config.ts@@ -179,7 +179,8 @@ export const COPY = {ERRORS: {[HTTP_STATUS.PAYLOAD_TOO_LARGE]: 'That ticket is too long.',[HTTP_STATUS.TOO_MANY_REQUESTS]: 'Too many attempts. Wait a moment.',- [HTTP_STATUS.NOT_FOUND]: 'Session expired. Reloading.',+ [HTTP_STATUS.NOT_FOUND]:+ 'That session is gone. A fresh one is open — send the ticket again.',DEFAULT: 'Something broke on our side.',},} as constdiff --git a/PROJECTS/beginner/prompt-injection-firewall/frontend/src/pages/arena/index.tsx b/PROJECTS/beginner/prompt-injection-firewall/frontend/src/pages/arena/index.tsxindex 6d58d388..f33ea920 100644--- a/PROJECTS/beginner/prompt-injection-firewall/frontend/src/pages/arena/index.tsx+++ b/PROJECTS/beginner/prompt-injection-firewall/frontend/src/pages/arena/index.tsx@@ -20,6 +20,7 @@ import {SEVERITY_SCALE_OFFSET,SEVERITY_WEIGHT,} from '@/config'+import { ApiError } from '@/core/api/errors'import { census, hiddenTotal, segments } from '@/core/lib'import styles from './arena.module.scss'@@ -34,6 +35,11 @@ function severityWidth(severity: string): string {return `${((weight + SEVERITY_SCALE_OFFSET) / span) * 100}%`}+function attemptMessage(error: Error | null): string {+ const status = error instanceof ApiError ? error.statusCode : 0+ return COPY.ERRORS[status as keyof typeof COPY.ERRORS] ?? COPY.ERRORS.DEFAULT+}+function firedFindings(result: AttemptResponse): Finding[] {return result.findings.filter((finding) => finding.rule !== RULE_LAYER_DISABLED)}@@ -402,7 +408,9 @@ export function Component(): React.ReactElement {<Specimen ticket={ticket} />- {attempt.isError && <p className={styles.error}>{COPY.ERRORS.DEFAULT}</p>}+ {attempt.isError && (+ <p className={styles.error}>{attemptMessage(attempt.error)}</p>+ )}{attempt.data ? (<Verdict result={attempt.data} />diff --git a/PROJECTS/beginner/prompt-injection-firewall/infra/nginx/nginx.prod.conf b/PROJECTS/beginner/prompt-injection-firewall/infra/nginx/nginx.prod.confindex 742e99e8..f2118cf1 100644--- a/PROJECTS/beginner/prompt-injection-firewall/infra/nginx/nginx.prod.conf+++ b/PROJECTS/beginner/prompt-injection-firewall/infra/nginx/nginx.prod.conf@@ -18,9 +18,22 @@ http {include /etc/nginx/mime.types;default_type application/octet-stream;+ # The only paths to this server are the Cloudflare tunnel container and+ # loopback, so the client address arrives in CF-Connecting-IP. Without+ # this the limit zones below would bucket every visitor on earth into+ # the tunnel container's single address.+ set_real_ip_from 10.0.0.0/8;+ set_real_ip_from 172.16.0.0/12;+ set_real_ip_from 192.168.0.0/16;+ set_real_ip_from 127.0.0.1;+ real_ip_header CF-Connecting-IP;+ real_ip_recursive on;+limit_req_zone $binary_remote_addr zone=api_limit:10m rate=10r/s;+ limit_req_zone $binary_remote_addr zone=session_limit:10m rate=10r/m;limit_conn_zone $binary_remote_addr zone=conn_limit:10m;limit_req_status 429;+ limit_conn_status 429;log_format main_timed '$remote_addr - $remote_user [$time_local] ''"$request" $status $body_bytes_sent 'diff --git a/PROJECTS/beginner/prompt-injection-firewall/infra/nginx/prod.nginx b/PROJECTS/beginner/prompt-injection-firewall/infra/nginx/prod.nginxindex 3d9f5f34..ba1b4188 100644--- a/PROJECTS/beginner/prompt-injection-firewall/infra/nginx/prod.nginx+++ b/PROJECTS/beginner/prompt-injection-firewall/infra/nginx/prod.nginx@@ -28,7 +28,22 @@ server {add_header Content-Type text/plain;}+ location /api/session {+ limit_req zone=session_limit burst=5 nodelay;+ limit_conn conn_limit 20;++ proxy_pass http://arena_api/api/session;+ proxy_http_version 1.1;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_read_timeout 30s;+ }+location /api/ {+ limit_req zone=api_limit burst=20 nodelay;+ limit_conn conn_limit 20;+proxy_pass http://arena_api/api/;proxy_http_version 1.1;proxy_set_header Host $host;diff --git a/PROJECTS/beginner/prompt-injection-firewall/pyproject.toml b/PROJECTS/beginner/prompt-injection-firewall/pyproject.tomlindex e63330ea..aa3eff38 100644--- a/PROJECTS/beginner/prompt-injection-firewall/pyproject.toml+++ b/PROJECTS/beginner/prompt-injection-firewall/pyproject.toml@@ -5,7 +5,38 @@name = "not-sandboxed"version = "0.1.0"description = "A prompt injection firewall that sandboxes effects, not prompts"+license = "AGPL-3.0-or-later"requires-python = ">=3.14"+authors = [+ { name = "Carter Perez", email = "[email protected]" },+]+maintainers = [+ { name = "Carter Perez", email = "[email protected]" },+]+keywords = [+ "prompt-injection",+ "llm-security",+ "ai-security",+ "firewall",+ "guardrails",+ "owasp-llm01",+ "agent-security",+ "unicode-smuggling",+]+classifiers = [+ "Development Status :: 4 - Beta",+ "Environment :: Web Environment",+ "Framework :: FastAPI",+ "Intended Audience :: Developers",+ "Intended Audience :: Information Technology",+ "License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)",+ "Operating System :: OS Independent",+ "Programming Language :: Python :: 3",+ "Programming Language :: Python :: 3.14",+ "Topic :: Security",+ "Topic :: Software Development :: Libraries :: Python Modules",+ "Typing :: Typed",+]dependencies = ["pydantic>=2.10.0","typer>=0.15.0",@@ -17,8 +48,11 @@ dependencies = ["uvicorn>=0.34.0",]-[project.scripts]-not-sandboxed = "not_sandboxed.cli:app"+[project.urls]+Homepage = "https://github.com/CarterPerez-dev/Cybersecurity-Projects"+Repository = "https://github.com/CarterPerez-dev/Cybersecurity-Projects"+Documentation = "https://github.com/CarterPerez-dev/Cybersecurity-Projects/tree/main/PROJECTS/beginner/prompt-injection-firewall"+Issues = "https://github.com/CarterPerez-dev/Cybersecurity-Projects/issues"[build-system]requires = ["hatchling"]diff --git a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/arena/session.py b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/arena/session.pyindex 3feb1567..6568f387 100644--- a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/arena/session.py+++ b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/arena/session.py@@ -39,16 +39,22 @@ class SessionStore:"""Per-visitor state with no shared mutable data between sessions"""- def __init__(self) -> None:+ def __init__(self, max_sessions: int | None = None) -> None:self._sessions: dict[str, Session] = {}+ self._max_sessions = (+ config.ARENA_MAX_SESSIONS+ if max_sessions is None else max_sessions+ )def create(self) -> Session:"""- Start a session with its own freshly generated secret+ Start a session with its own freshly generated secret,+ discarding the least recently used one when the store is full+ rather than the oldest, so a visitor mid-game outlives one who+ opened the page and left"""- if len(self._sessions) >= config.ARENA_MAX_SESSIONS:- oldest = next(iter(self._sessions))- del self._sessions[oldest]+ while len(self._sessions) >= self._max_sessions:+ del self._sessions[next(iter(self._sessions))]session = Session(session_id = secrets.token_urlsafe(@@ -61,9 +67,15 @@ class SessionStore:def get(self, session_id: str) -> Session | None:"""- Look up a session without creating one+ Look up a session without creating one, marking it as the most+ recently used"""- return self._sessions.get(session_id)+ session = self._sessions.pop(session_id, None)+ if session is None:+ return None++ self._sessions[session_id] = session+ return sessiondef charge(self, session: Session, now: float) -> None:"""diff --git a/PROJECTS/beginner/prompt-injection-firewall/tests/arena/test_arena.py b/PROJECTS/beginner/prompt-injection-firewall/tests/arena/test_arena.pyindex 7936013a..3df3d05e 100644--- a/PROJECTS/beginner/prompt-injection-firewall/tests/arena/test_arena.py+++ b/PROJECTS/beginner/prompt-injection-firewall/tests/arena/test_arena.py@@ -187,6 +187,32 @@ def test_unknown_level_is_refused() -> None:assert response.status_code == 404+def test_eviction_discards_the_idle_session_not_the_playing_one() -> None:+ store = SessionStore(max_sessions = 2)+ playing = store.create()+ idle = store.create()++ assert store.get(playing.session_id) is not None++ store.create()++ assert store.get(playing.session_id) is not None+ assert store.get(idle.session_id) is None+++def test_store_never_grows_past_its_ceiling() -> None:+ store = SessionStore(max_sessions = 3)++ created = [store.create() for _ in range(10)]++ survivors = [+ session for session in created+ if store.get(session.session_id) is not None+ ]++ assert len(survivors) == 3++def test_rate_limit_refuses_rather_than_throttles() -> None:store = SessionStore()session = store.create()