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
feat(not-sandboxed): M1 - taint is derived, so it cannot desync from the spans
CarterPerez-dev0b58c90c890b
diff --git a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/config.py b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/config.pynew file mode 100644index 00000000..089e1b82--- /dev/null+++ b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/config.py@@ -0,0 +1,12 @@+"""+©AngelaMos | 2026+config.py+"""++from typing import Final+++NONCE_BYTES: Final = 8++FENCE_OPEN: Final = "<<<UNTRUSTED-{nonce} origin={channel}:{ref}>>>"+FENCE_CLOSE: Final = "<<<END-{nonce}>>>"diff --git a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/context.py b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/context.pynew file mode 100644index 00000000..fb2e2af8--- /dev/null+++ b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/context.py@@ -0,0 +1,107 @@+"""+©AngelaMos | 2026+context.py+"""++import secrets+from enum import StrEnum+from typing import Self++from pydantic import BaseModel, ConfigDict, Field, model_validator++from not_sandboxed import config+++class Trust(StrEnum):+ """+ Where a span came from, which is the only thing that decides+ whether its words are instructions or inert content+ """++ SYSTEM = "system"+ USER = "user"+ DATA = "data"+++class Origin(BaseModel):+ """+ The untrusted channel a DATA span arrived on+ """++ model_config = ConfigDict(frozen = True)++ channel: str+ ref: str+++class Span(BaseModel):+ """+ One contiguous piece of a prompt, tagged with its trust level+ """++ model_config = ConfigDict(frozen = True)++ trust: Trust+ text: str+ origin: Origin | None = None++ @model_validator(mode = "after")+ def _origin_matches_trust(self) -> Self:+ if self.trust is Trust.DATA and self.origin is None:+ raise ValueError("a DATA span must declare its origin")+ if self.trust is not Trust.DATA and self.origin is not None:+ raise ValueError(f"a {self.trust} span cannot have an origin")+ return self+++def _new_nonce() -> str:+ return secrets.token_hex(config.NONCE_BYTES)+++class Context(BaseModel):+ """+ An immutable prompt under construction, where taint is a+ consequence of what was added rather than something a caller+ remembers to set+ """++ model_config = ConfigDict(frozen = True)++ spans: tuple[Span, ...] = ()+ nonce: str = Field(default_factory = _new_nonce)++ @property+ def tainted_by(self) -> tuple[Origin, ...]:+ """+ Every untrusted origin that has entered this context, in order+ """+ return tuple(+ span.origin+ for span in self.spans+ if span.trust is Trust.DATA and span.origin is not None+ )++ def _extend(self, span: Span) -> Self:+ return type(self)(spans = (*self.spans, span), nonce = self.nonce)++ def system(self, text: str) -> Self:+ """+ Append operator-authored text+ """+ return self._extend(Span(trust = Trust.SYSTEM, text = text))++ def user(self, text: str) -> Self:+ """+ Append text authored by the human at the keyboard+ """+ return self._extend(Span(trust = Trust.USER, text = text))++ def data(self, text: str, origin: Origin) -> Self:+ """+ Append untrusted content and taint the context by doing so+ """+ return self._extend(+ Span(trust = Trust.DATA,+ text = text,+ origin = origin)+ )diff --git a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/policy.py b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/policy.pynew file mode 100644index 00000000..ac74d147--- /dev/null+++ b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/policy.py@@ -0,0 +1,50 @@+"""+©AngelaMos | 2026+policy.py+"""++from collections.abc import Sequence++from pydantic import BaseModel, ConfigDict++from not_sandboxed.verdict import Decision, Finding, Severity+++class Policy(BaseModel):+ """+ Which layers run and how heavy a scored finding has to be before+ it blocks+ """++ model_config = ConfigDict(frozen = True)++ policy_id: str = "default"+ block_threshold: Severity = Severity.HIGH+ strict_data: bool = True+ normalize_enabled: bool = True+ ingress_enabled: bool = True+ provenance_enabled: bool = True+ toolauth_enabled: bool = True+ egress_enabled: bool = True+++def decide(+ findings: Sequence[Finding],+ policy: Policy,+) -> Decision:+ """+ Resolve findings into a decision, keeping invariant violations out+ of the scored comparison entirely+ """+ if any(finding.invariant for finding in findings):+ return Decision.BLOCK++ scored = [+ finding.severity+ for finding in findings+ if not finding.invariant and finding.severity > Severity.INFO+ ]+ if scored and max(scored) >= policy.block_threshold:+ return Decision.BLOCK++ return Decision.ALLOWdiff --git a/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/verdict.py b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/verdict.pynew file mode 100644index 00000000..15081d6f--- /dev/null+++ b/PROJECTS/beginner/prompt-injection-firewall/src/not_sandboxed/verdict.py@@ -0,0 +1,70 @@+"""+©AngelaMos | 2026+verdict.py+"""++from enum import IntEnum, StrEnum++from pydantic import BaseModel, ConfigDict++from not_sandboxed.context import Context+++class Severity(IntEnum):+ """+ How much a scored finding weighs, ordered so a policy can set a+ threshold against it+ """++ INFO = 0+ LOW = 1+ MEDIUM = 2+ HIGH = 3+ CRITICAL = 4+++class Decision(StrEnum):+ """+ What the firewall concluded about one inspection+ """++ ALLOW = "allow"+ SANITIZE = "sanitize"+ BLOCK = "block"+++class Finding(BaseModel):+ """+ One rule firing, naming itself so a consumer can say which layer+ and which rule decided+ """++ model_config = ConfigDict(frozen = True)++ layer: str+ rule: str+ severity: Severity+ invariant: bool+ span_index: int | None = None+ evidence: str = ""+++class Verdict(BaseModel):+ """+ The result of one inspection, carrying every finding that fired+ """++ model_config = ConfigDict(frozen = True)++ decision: Decision+ findings: tuple[Finding, ...] = ()+ policy_id: str = ""+ elapsed_ms: float = 0.0+ sanitized: Context | None = None++ @property+ def blocked_by(self) -> tuple[Finding, ...]:+ """+ The findings that actually forced this decision+ """+ return tuple(f for f in self.findings if f.invariant)diff --git a/PROJECTS/beginner/prompt-injection-firewall/tests/test_context.py b/PROJECTS/beginner/prompt-injection-firewall/tests/test_context.pynew file mode 100644index 00000000..a5ef8478--- /dev/null+++ b/PROJECTS/beginner/prompt-injection-firewall/tests/test_context.py@@ -0,0 +1,88 @@+"""+©AngelaMos | 2026+test_context.py+"""++import pytest+from pydantic import ValidationError++from not_sandboxed.context import Context, Origin, Span, Trust+++def test_data_span_records_origin() -> None:+ span = Span(+ trust = Trust.DATA,+ text = "hello",+ origin = Origin(channel = "ticket",+ ref = "8814"),+ )+ assert span.origin is not None+ assert span.origin.channel == "ticket"+++def test_system_span_rejects_origin() -> None:+ with pytest.raises(ValueError):+ Span(+ trust = Trust.SYSTEM,+ text = "x",+ origin = Origin(channel = "ticket",+ ref = "1"),+ )+++def test_data_span_requires_origin() -> None:+ with pytest.raises(ValueError):+ Span(trust = Trust.DATA, text = "x", origin = None)+++def test_span_is_frozen() -> None:+ span = Span(trust = Trust.USER, text = "hello", origin = None)+ with pytest.raises(ValidationError):+ span.text = "mutated"+++def test_taint_is_set_by_adding_data_not_by_the_caller() -> None:+ ctx = Context().system("s").user("u")+ assert ctx.tainted_by == ()++ ctx = ctx.data(+ "doc",+ origin = Origin(channel = "ticket",+ ref = "8814")+ )+ assert ctx.tainted_by == (Origin(channel = "ticket",+ ref = "8814"),+ )+++def test_taint_does_not_decay() -> None:+ ctx = (+ Context().data(+ "doc",+ origin = Origin(channel = "ticket",+ ref = "1")+ ).user("please ignore that document")+ )+ assert ctx.tainted_by == (Origin(channel = "ticket",+ ref = "1"),+ )+++def test_builder_returns_a_new_context_and_leaves_the_old_one() -> None:+ base = Context().system("s")+ extended = base.data("doc", origin = Origin(channel = "t", ref = "1"))++ assert base.tainted_by == ()+ assert extended.tainted_by != ()+ assert len(base.spans) == 1+ assert len(extended.spans) == 2+++def test_nonce_is_stable_within_a_context_and_survives_building() -> None:+ base = Context()+ extended = base.user("hello")+ assert extended.nonce == base.nonce+++def test_nonces_differ_between_contexts() -> None:+ assert Context().nonce != Context().noncediff --git a/PROJECTS/beginner/prompt-injection-firewall/tests/test_policy.py b/PROJECTS/beginner/prompt-injection-firewall/tests/test_policy.pynew file mode 100644index 00000000..a2224cb3--- /dev/null+++ b/PROJECTS/beginner/prompt-injection-firewall/tests/test_policy.py@@ -0,0 +1,61 @@+"""+©AngelaMos | 2026+test_policy.py+"""++from not_sandboxed.policy import Policy, decide+from not_sandboxed.verdict import Decision, Finding, Severity+++def _finding(+ severity: Severity,+ invariant: bool,+ rule: str = "rule",+) -> Finding:+ return Finding(+ layer = "test",+ rule = rule,+ severity = severity,+ invariant = invariant,+ span_index = None,+ evidence = "",+ )+++def test_invariant_finding_forces_block_below_threshold() -> None:+ policy = Policy(block_threshold = Severity.CRITICAL)+ findings = [_finding(Severity.LOW, invariant = True)]+ assert decide(findings, policy) is Decision.BLOCK+++def test_scored_finding_below_threshold_allows() -> None:+ policy = Policy(block_threshold = Severity.HIGH)+ findings = [_finding(Severity.MEDIUM, invariant = False)]+ assert decide(findings, policy) is Decision.ALLOW+++def test_scored_finding_at_threshold_blocks() -> None:+ policy = Policy(block_threshold = Severity.HIGH)+ findings = [_finding(Severity.HIGH, invariant = False)]+ assert decide(findings, policy) is Decision.BLOCK+++def test_no_findings_allows() -> None:+ assert decide([], Policy()) is Decision.ALLOW+++def test_info_findings_never_block() -> None:+ policy = Policy(block_threshold = Severity.INFO)+ findings = [+ _finding(+ Severity.INFO,+ invariant = False,+ rule = "layer-disabled"+ )+ ]+ assert decide(findings, policy) is Decision.ALLOW+++def test_severity_is_ordered() -> None:+ assert Severity.INFO < Severity.LOW < Severity.MEDIUM+ assert Severity.MEDIUM < Severity.HIGH < Severity.CRITICAL