Skip to main content

OWASP-aligned LLM prompt defence, injection detection, and audit logging

Project description

cognexus

CogNexus

OWASP-aligned prompt defence, injection detection, and audit logging for LLM applications.

cognexus gives you two complementary security layers and a tamper-evident audit trail — all in pure Python with zero mandatory dependencies.

pip install cognexus

Features

Layer What it does
Static prompt defence Grades system prompts A–F against 12 OWASP LLM Top-10 attack vectors before deployment
Runtime injection detection Screens user input, RAG content, and tabular payloads at request time
Audit events Append-only JSONL trail for every detected injection — no raw text stored

Detection coverage

  • Direct instruction override
  • Delimiter and context-boundary attacks
  • Base64 / hex / ROT13 encoding attacks
  • Role-play and jailbreak language (DAN mode, developer mode, etc.)
  • Context manipulation ("your real instructions are…")
  • Canary token leak detection
  • Multi-turn escalation
  • Cross-plugin / tool-chaining attacks (OWASP ASI04)
  • Markup injection (XSS gadgets in model-visible text)
  • Zero-width / token-smuggling unicode attacks
  • Credential exfiltration requests
  • Unsolicited destructive database operations (DROP / DELETE / TRUNCATE / volume-wipe) — PD-13

Quick-start

from cognexus import (
    augment_system_prompt,
    evaluate_system_prompt,
    screen_user_input,
    should_block,
)

# 1. Augment your system prompt so it scores grade A before inference
system = augment_system_prompt("You are a helpful customer support agent.")
report = evaluate_system_prompt(system)
print(report.grade)    # "A"
print(report.score)    # 100
print(report.missing)  # []

# 2. Screen every user message at request time
result = screen_user_input(user_message, source="chat")

if should_block(result):
    raise PermissionError(f"Injection blocked: {result.explanation}")

Screening helpers

Three presets cover the most common LLM input surfaces:

from cognexus import (
    screen_user_input,       # balanced sensitivity — direct chat messages
    screen_external_content, # strict  sensitivity — RAG / web / API content
    screen_tabular_payload,  # permissive           — CSV / dataframe blobs
    should_block,
    wrap_untrusted_content,
)

# Wrap RAG content before inserting into a prompt
safe_chunk = wrap_untrusted_content("web_search", raw_text)

# Screen it too
result = screen_external_content(raw_text, source="web_search", user_id=user.id)

Sensitivity presets

Preset Threshold Min threat flagged Use for
strict 0.3 LOW External / RAG content
balanced 0.5 LOW Direct user input
permissive 0.7 HIGH CSV / tabular payloads

Override via environment variables:

COGNEXUS_PROMPT_INJECTION_USER_SENSITIVITY=balanced
COGNEXUS_PROMPT_INJECTION_EXTERNAL_SENSITIVITY=strict
COGNEXUS_PROMPT_INJECTION_TABULAR_SENSITIVITY=permissive
COGNEXUS_PROMPT_INJECTION_BLOCK=0   # set to 1 to block any hit, not just CRITICAL

Using the core classes directly

from cognexus import PromptInjectionDetector, DetectionConfig, InjectionType

detector = PromptInjectionDetector(
    config=DetectionConfig(
        sensitivity="strict",
        blocklist=["my-internal-keyword"],
        allowlist=["safe phrase"],
    )
)

result = detector.detect(text, source="api_gateway")
print(result.is_injection)       # True / False
print(result.threat_level)       # ThreatLevel.HIGH
print(result.injection_type)     # InjectionType.DIRECT_OVERRIDE
print(result.confidence)         # 0.9
print(result.matched_patterns)   # ["direct_override:..."]

Audit events

Detections are automatically written to a JSONL file (no raw input stored):

# Events go to $COGNEXUS_PROMPT_DEFENSE_EVENTS_DIR/prompt_defense_events.jsonl
# (falls back to $REPORTS_DIR, then /tmp)

from cognexus.events import read_recent_events

rows = read_recent_events(user_id=42, limit=20)
# [{"ts": "...", "kind": "prompt_injection", "threat": "high", ...}, ...]

Custom event sink (database, queue, dashboard)

Pass an on_event callback to mirror records into your own store:

def save_to_db(record: dict) -> None:
    db.execute("INSERT INTO security_events ...", record)

screen_user_input(text, source="chat", user_id=user.id, on_event=save_to_db)

Static prompt defence — standalone

from cognexus import PromptDefenseEvaluator, PromptDefenseConfig

evaluator = PromptDefenseEvaluator(
    config=PromptDefenseConfig(min_grade="B")
)
report = evaluator.evaluate(my_system_prompt)

print(report.grade)     # "C"
print(report.score)     # 58
print(report.missing)   # ["unicode-attack", "context-overflow"]

if report.is_blocking():
    print("System prompt is below minimum grade — fix before deploying.")

# Evaluate a file
report = evaluator.evaluate_file("prompts/assistant.txt")

# Batch evaluation
reports = evaluator.evaluate_batch({
    "chat": chat_prompt,
    "analyst": analyst_prompt,
})

Environment variables

Variable Default Purpose
COGNEXUS_PROMPT_DEFENSE_EVENTS_DIR /tmp JSONL audit file directory
COGNEXUS_PROMPT_INJECTION_LOG 1 Log clean scans at DEBUG
COGNEXUS_PROMPT_INJECTION_BLOCK 0 Block any injection (not just CRITICAL)
COGNEXUS_PROMPT_INJECTION_USER_SENSITIVITY balanced User-input preset
COGNEXUS_PROMPT_INJECTION_EXTERNAL_SENSITIVITY strict External/RAG preset
COGNEXUS_PROMPT_INJECTION_TABULAR_SENSITIVITY permissive CSV/tabular preset

Security notes

  • All detection is pure regex — deterministic, zero LLM calls, zero network access, < 5 ms per input.
  • Audit records store a SHA-256 hash and a 96-character redacted preview of the input. Raw user text is never written to disk.
  • The package ships sample rules that cover common attack patterns. Review and extend them for your production threat model using DetectionConfig.custom_patterns or a YAML config file loaded with load_prompt_injection_config().

License

MIT — see LICENSE.

Detection rules and evaluator logic originally derived from microsoft/agent-governance-toolkit (MIT).

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

cognexus-0.1.1.tar.gz (80.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

cognexus-0.1.1-py3-none-any.whl (28.6 kB view details)

Uploaded Python 3

File details

Details for the file cognexus-0.1.1.tar.gz.

File metadata

  • Download URL: cognexus-0.1.1.tar.gz
  • Upload date:
  • Size: 80.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for cognexus-0.1.1.tar.gz
Algorithm Hash digest
SHA256 55b9d0509cbd412ad3348af1584db0265017f113cdb30611d6bad072a8a3d7dc
MD5 c8c882bbba900281d2162fa0b5ced2ed
BLAKE2b-256 352e33bb8a48b75be64d3d885389038f24713eb1de2ba11995960bec31a66b18

See more details on using hashes here.

File details

Details for the file cognexus-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: cognexus-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 28.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.11

File hashes

Hashes for cognexus-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 30493dd9b8d61fdff0068dc8beb9b842b961b970746e97dadc0283d603c997ec
MD5 a34ce2d5b8c4980970c8ee3b41ccb622
BLAKE2b-256 4a586541c04a0953238c2d274fd34c515c24a006a7f3916957a10dd8229f1227

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page