feat(guardrails): secure-by-default rule and /guardrails scanner

Always-on rules/secure-by-default.md: hosting, a11y, Supabase RLS,
SMS/email consent, cloud functions, API hygiene incl. password storage.
Stdlib scanner (FAIL/WARN/MANUAL) + skill, 89-check suite, auditor
gate wiring, profiles, routing row (plus Explore rows confirmed
through the router dialog).
This commit is contained in:
bchanot committed 2026-10-18 18:10:20 +02:00
1 parent c5fad5ee8f
commit 558c49e1a1
45 files changed
+2473 -5

No files matched your search

@@ -0,0 +1 @@
"""Static guardrail checks, one module per domain."""
+239
View File
@@ -0,0 +1,239 @@
"""Accessibility checks: keyboard, visible focus, alt text, field labels."""
import re
from collections import namedtuple
from .common import Rule, blank_markup_comments
DOMAIN = "a11y"
MARKUP_EXTS = (".html", ".htm", ".jsx", ".tsx", ".vue", ".svelte", ".astro")
STYLE_EXTS = (".css", ".scss", ".sass", ".less")
SCRIPT_EXTS = (".ts", ".js", ".mjs")
FIELD_TAGS = {"input", "select", "textarea"}
CLICK_TAGS = {"div", "span", "li", "p", "td", "tr", "section", "article"}
SKIP_INPUT_TYPES = {"hidden", "submit", "button", "reset", "image"}
INTERACTIVE = {"*", "a", "button", "input", "select", "textarea", "summary"}
_BRACES = r"\{(?:[^{}]|\{(?:[^{}]|\{[^{}]*\})*\})*\}"
TAG = re.compile(
r"<(?P<name>[A-Za-z][\w.:-]*)(?P<attrs>(?:[^<>{}]|" + _BRACES + r")*)>")
SPREAD = re.compile(r"\{\s*\.\.\.|v-bind\s*=")
CLICK = re.compile(
r"(?<![\w-])(?:onclick|@click|v-on:click|on:click)(?![\w-])", re.I)
KEYS = re.compile(
r"(?<![\w-])(?:onkey(?:down|up|press)|@key(?:down|up|press)"
r"|v-on:key(?:down|up|press)|on:key(?:down|up|press))(?![\w-])", re.I)
POSITIVE_TABINDEX = re.compile(
r"(?<![\w-])tabindex\s*=\s*[{\"']*\s*[1-9]", re.I)
STYLE_TAG = re.compile(r"<style\b[^>]*>(.*?)</style>", re.I | re.S)
CSS_RULE = re.compile(r"(?P<sel>[^{}]+)\{(?P<body>[^{}]*)\}")
OUTLINE_OFF = re.compile(r"outline(?:-style)?\s*:\s*(?:none|0)\b", re.I)
REPLACEMENT = re.compile(
r"(?:box-shadow|border(?:-color)?)\s*:\s*(?!none\b|0\b)", re.I)
NOT_A_CONTROL = re.compile(
r"role\s*=\s*[\"'{]\s*[\"']?(?:presentation|none|dialog|alertdialog)\b"
r"|stopPropagation", re.I)
TW_STRING = re.compile(
r"[\"'`]([^\"'`\n]*\boutline-(?:none|hidden)\b[^\"'`\n]*)[\"'`]")
TW_REPLACED = re.compile(
r"\bfocus(?:-visible|-within)?:(?:ring|outline\b(?!-none|-hidden)"
r"|shadow|border|underline|bg-)")
def applies(project):
return bool(project.with_ext(*MARKUP_EXTS, *STYLE_EXTS))
def has_attr(attrs, name):
pattern = (r"(?<![\w-])(?:v-bind:|bind:|:)?" + re.escape(name)
+ r"(?=[\s=/]|$)")
return re.search(pattern, attrs, re.I) is not None
def attr_value(attrs, name):
"""Literal value, '{expr}' for a braced value, None if absent."""
pattern = (r"(?<![\w:-])" + re.escape(name)
+ r"\s*=\s*(?:\"([^\"]*)\"|'([^']*)'|\{([^}]*)\})")
m = re.search(pattern, attrs, re.I)
if not m:
return None
literal = m.group(1) if m.group(1) is not None else m.group(2)
return literal if literal is not None else "{" + m.group(3) + "}"
def check(project):
out = []
for path in project.with_ext(*MARKUP_EXTS):
text = blank_markup_comments(project.text(path))
out += _tag_findings(project, path, text)
return out + _focus_css(project) + _focus_tailwind(project)
def _tag_findings(project, path, text):
out = []
for m in TAG.finditer(text):
for rule, severity, message in _tag_issues(m, text):
out.append(project.found(
Rule(DOMAIN, rule, severity), path, m.start(), message))
return out
def _tag_issues(m, text):
name, attrs = m["name"], m["attrs"]
if SPREAD.search(attrs):
return []
issues = [_tabindex_issue(attrs)]
if name.lower() == "img" or name == "Image":
issues.append(_img_issue(attrs))
elif name in FIELD_TAGS:
issues.append(_field_issue(m, text))
elif name in CLICK_TAGS:
issues.append(_click_issue(attrs))
return [issue for issue in issues if issue]
def _img_issue(attrs):
if has_attr(attrs, "alt"):
return None
return ("A11Y-IMG-ALT", "FAIL",
'image without alt: describe it, or alt="" when decorative')
def _tabindex_issue(attrs):
if not POSITIVE_TABINDEX.search(attrs):
return None
return ("A11Y-TABINDEX-POSITIVE", "WARN",
"positive tabindex breaks the natural keyboard order")
def _click_issue(attrs):
if not CLICK.search(attrs) or NOT_A_CONTROL.search(attrs):
return None
if attrs.rstrip().endswith("/"): # empty overlay, nothing to operate
return None
missing = [label for label, ok in (
("role", has_attr(attrs, "role")),
("tabindex", has_attr(attrs, "tabindex")),
("key handler", bool(KEYS.search(attrs))),
) if not ok]
if not missing:
return None
return ("A11Y-CLICK-NO-KEYBOARD", "FAIL",
"click handler on a non-interactive element, missing "
+ ", ".join(missing) + ": use a <button>")
def _field_issue(m, text):
attrs = m["attrs"]
kind = (attr_value(attrs, "type") or "text").lower()
if kind in SKIP_INPUT_TYPES or _is_hidden_field(attrs):
return None
if _is_labelled(attrs, text, m.start()):
return None
return ("A11Y-FIELD-LABEL", "FAIL",
"form field without a label: add <label for>, a wrapping "
"<label> or aria-label (a placeholder is not a label)")
def _is_hidden_field(attrs):
"""Fields that are never rendered need no label."""
if has_attr(attrs, "hidden"):
return True
classes = attr_value(attrs, "className") or attr_value(attrs, "class")
if "hidden" in (classes or "").split():
return True
return re.search(r"display\s*:\s*['\"]?none", attrs) is not None
def _is_labelled(attrs, text, position):
if has_attr(attrs, "aria-label") or has_attr(attrs, "aria-labelledby"):
return True
before = text[:position].lower()
if before.count("<label") > before.count("</label"):
return True
ident = attr_value(attrs, "id")
if ident is None:
return has_attr(attrs, "id") # bound id: cannot tell, assume ok
if not re.fullmatch(r"[\w-]+", ident):
return True
return re.search(
r"(?:for|htmlFor)\s*=\s*[\"']" + re.escape(ident) + r"[\"']",
text) is not None
Block = namedtuple("Block", "path css start")
def _style_blocks(project):
"""Yield a Block for each CSS source: stylesheets and <style> tags."""
for path in project.with_ext(*STYLE_EXTS):
yield Block(path, blank_markup_comments(project.text(path)), 0)
for path in project.with_ext(*MARKUP_EXTS):
for m in STYLE_TAG.finditer(project.text(path)):
yield Block(path, blank_markup_comments(m.group(1)), m.start(1))
def _targets_focus(selector):
for part in selector.split(","):
part = part.strip()
last = re.split(r"[\s>+~]+", part)[-1] if part else ""
if ":focus" in part or last in INTERACTIVE:
return True
if last.startswith("[tabindex"):
return True
return False
def _kills_focus_ring(selector, body):
return (OUTLINE_OFF.search(body) is not None
and _targets_focus(selector)
and ":not(:focus-visible)" not in selector
and REPLACEMENT.search(body) is None)
def _focus_visible_defined(project, blocks):
if any(":focus-visible" in block.css for block in blocks):
return True
return project.has(r"focus-visible:", project.with_ext(*MARKUP_EXTS))
def _lead(text):
return len(text) - len(text.lstrip())
def _css_findings(project, block, covered):
out = []
for rule in CSS_RULE.finditer(block.css):
if _kills_focus_ring(rule["sel"], rule["body"]):
offset = block.start + rule.start("sel") + _lead(rule["sel"])
out.append(_outline_finding(project, block.path, offset, covered))
return out
def _focus_css(project):
blocks = list(_style_blocks(project))
covered = _focus_visible_defined(project, blocks)
out = []
for block in blocks:
out += _css_findings(project, block, covered)
return out
def _outline_finding(project, path, offset, covered):
if covered:
return project.found(
Rule(DOMAIN, "A11Y-FOCUS-OUTLINE", "WARN"), path, offset,
"outline removed here: confirm a :focus-visible style covers it")
return project.found(
Rule(DOMAIN, "A11Y-FOCUS-OUTLINE", "FAIL"), path, offset,
"focus outline removed and no :focus-visible style exists")
def _focus_tailwind(project):
out = []
files = project.with_ext(*MARKUP_EXTS, *SCRIPT_EXTS)
for path, m in project.matches(TW_STRING.pattern, files, 0):
if not TW_REPLACED.search(m.group(1)):
out.append(project.found(
Rule(DOMAIN, "A11Y-FOCUS-OUTLINE", "FAIL"), path, m.start(),
"outline-none without a focus-visible ring replacement"))
return out
+173
View File
@@ -0,0 +1,173 @@
"""Checks for every project: secrets, public env vars, CORS, route auth."""
import fnmatch
import re
from . import passwords
from .common import Rule, SOURCE_EXTS, non_doc_files, redact
DOMAIN = "api"
SECRET_PATTERNS = [
("Stripe live key", r"sk_live_[0-9A-Za-z]{10,}"),
("AWS access key id", r"AKIA[0-9A-Z]{16}"),
("GitHub token", r"gh[pousr]_[A-Za-z0-9]{30,}"),
("Slack token", r"xox[abprs]-[A-Za-z0-9-]{10,}"),
("SendGrid key", r"SG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}"),
("Supabase secret key", r"sb_secret_[A-Za-z0-9_-]{10,}"),
("private key block", r"-----BEGIN (?:[A-Z]+ )?PRIVATE KEY-----"
r"(?:\\n|\s)*[A-Za-z0-9+/=]{20,}"),
]
PUBLIC_ENV = (
r"\b(?:NEXT_PUBLIC|VITE|REACT_APP|EXPO_PUBLIC|NUXT_PUBLIC|GATSBY"
r"|VUE_APP|PUBLIC)_\w*(?:SERVICE_ROLE|SECRET|PRIVATE|PASSWORD)\w*"
)
CORS_WILDCARD = (
r"Access-Control-Allow-Origin['\"]?\s*[:,=)]\s*['\"]\*['\"]"
r"|\borigin\s*:\s*(?:['\"]\*['\"]|true)\b"
r"|allow_origins\s*=\s*\[\s*['\"]\*['\"]"
r"|allow_any_origin\(\)|CorsLayer::permissive\(\)"
)
CORS_CREDENTIALS = (
r"credentials\s*:\s*true|Allow-Credentials|allow_credentials\s*=\s*True"
r"|allow_credentials\(true\)|supports_credentials"
)
ROUTE_PATH = re.compile(
r"(?:^|/)(?:api|routes|controllers|handlers)/"
r"|(?:^|/)route\.[jt]s$|\+server\.[jt]s$"
r"|(?:^|/)supabase/functions/[^/]+/index\.", re.I)
API_DIR = re.compile(r"(?:^|/)api/", re.I)
UI_EXTS = (".tsx", ".jsx", ".vue", ".svelte", ".astro")
ROUTE_SKIP = re.compile(
r"_shared|\.test\.|\.spec\.|health|ping|status|robots|sitemap"
r"|favicon|/og[./]"
r"|(?:^|/)(?:bin|scripts?|cron|jobs?|tests?|__tests__|migrations?"
r"|seeds?|public|config|helpers?|libs?|models?|utils?|services?"
r"|middleware|core|includes|types|schemas?|constants|templates?"
r"|views?)/", re.I)
AUTH_EVIDENCE = re.compile(
r"\b(?:auth\w*|getUser|getSession|session|jwt\w*|bearer|verify\w*"
r"|signature|hmac|login_required|Depends|requireAuth|requireUser"
r"|requireRole|guard|permission\w*|clerk\w*|csrf)\b", re.I)
ENV_NAME = re.compile(r"\.env(?:\.[\w.-]+)?")
ENV_SAMPLE = (".example", ".sample", ".template", ".dist")
def applies(project):
return True
def ignore_patterns(project):
"""Patterns from every .gitignore in the tree."""
patterns = []
for gitignore in project.named(".gitignore"):
for line in project.text(gitignore).splitlines():
line = line.strip()
if line and not line.startswith(("#", "!")):
patterns.append(line.strip("/"))
return patterns
def is_ignored_env(path, patterns):
"""True for an env file that .gitignore keeps out of git."""
return bool(ENV_NAME.fullmatch(path.name)) and any(
fnmatch.fnmatch(path.name, pat) for pat in patterns)
def _is_route(rel, ext):
if ROUTE_SKIP.search(rel) or not ROUTE_PATH.search(rel):
return False
return ext not in UI_EXTS or bool(API_DIR.search(rel))
def route_files(project):
return [
p for p in project.with_ext(*SOURCE_EXTS)
if _is_route(project.rel(p), p.suffix.lower())
]
def check(project):
return (_secret_literals(project) + _public_env(project)
+ _unignored_env(project) + _cors(project)
+ _routes_without_auth(project) + passwords.check(project))
def _unignored_files(project):
patterns = ignore_patterns(project)
return [p for p in non_doc_files(project)
if not is_ignored_env(p, patterns)]
def _literal_hits(project, files, label, pattern):
return [
project.found(
Rule(DOMAIN, "API-SECRET-LITERAL", "FAIL"), path, m.start(),
f"{label} hardcoded ({redact(m.group())}): "
"move it to env and rotate it")
for path, m in project.matches(pattern, files, 0)
]
def _secret_literals(project):
files = _unignored_files(project)
out = []
for label, pattern in SECRET_PATTERNS:
out += _literal_hits(project, files, label, pattern)
return out
def _public_env(project):
files = [p for p in project.files
if p.suffix.lower() not in (".md", ".mdx")]
return [
project.found(
Rule(DOMAIN, "API-PUBLIC-ENV-SECRET", "FAIL"), path, m.start(),
f"{m.group()} ships to the browser: secrets stay server-side")
for path, m in project.matches(PUBLIC_ENV, files, 0)
]
def _has_value(text):
return re.search(r"^\s*[A-Za-z_]\w*\s*=\s*\S", text, re.M) is not None
def _unignored_env(project):
patterns = ignore_patterns(project)
out = []
for path in project.files:
if not ENV_NAME.fullmatch(path.name):
continue
if path.name.endswith(ENV_SAMPLE) or not _has_value(project.text(path)):
continue
if not is_ignored_env(path, patterns):
out.append(project.found(
Rule(DOMAIN, "API-ENV-NOT-IGNORED", "FAIL"), path, 0,
f"{path.name} holds values and is not in .gitignore"))
return out
def _cors_finding(project, path, m):
creds = re.search(CORS_CREDENTIALS, project.text(path), re.I)
note = " with credentials" if creds else ""
return project.found(
Rule(DOMAIN, "API-CORS-WILDCARD", "FAIL" if creds else "WARN"),
path, m.start(),
f"CORS allows any origin{note}: use an explicit allowlist")
def _cors(project):
return [
_cors_finding(project, path, m)
for path, m in project.matches(CORS_WILDCARD, non_doc_files(project))
]
def _routes_without_auth(project):
return [
project.found(
Rule(DOMAIN, "API-ROUTE-NO-AUTH", "WARN"), path, 0,
"no authentication evidence in this route; if it is public "
"on purpose, say so and rate limit it")
for path in route_files(project)
if not AUTH_EVIDENCE.search(project.text(path))
]
+163
View File
@@ -0,0 +1,163 @@
"""Shared types and file helpers for the guardrails checks."""
import os
import re
from dataclasses import asdict, dataclass
from pathlib import Path
SKIP_DIRS = {
".git", "node_modules", "dist", "build", ".next", ".astro", "target",
"vendor", ".venv", "venv", "coverage", "__pycache__", ".svelte-kit",
".nuxt", ".output", ".turbo", ".vercel", ".cache", ".phpunit.cache",
".pytest_cache", ".mypy_cache",
}
SKIP_FILES = {
"package-lock.json", "pnpm-lock.yaml", "yarn.lock", "Cargo.lock",
"bun.lockb", "poetry.lock", "composer.lock",
}
BINARY_EXTS = {
".png", ".jpg", ".jpeg", ".gif", ".webp", ".avif", ".ico", ".pdf",
".woff", ".woff2", ".ttf", ".otf", ".zip", ".gz", ".mp4", ".mov",
".mp3", ".wasm", ".log",
}
MAX_BYTES = 1_000_000
SOURCE_EXTS = {
".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".py", ".rs", ".go",
".php", ".rb", ".vue", ".svelte", ".astro",
}
@dataclass(frozen=True)
class Rule:
domain: str
id: str
severity: str # FAIL | WARN | MANUAL
@dataclass(frozen=True)
class Finding:
domain: str
rule: str
severity: str # FAIL | WARN | MANUAL
path: str
line: int
message: str
def as_dict(self):
return asdict(self)
def line_of(text, offset):
return text.count("\n", 0, offset) + 1
def redact(value):
return value[:6] + "..."
SQL_COMMENT = re.compile(r"--[^\n]*|/\*.*?\*/", re.S)
MARKUP_COMMENT = re.compile(
r"<!--.*?-->|/\*.*?\*/|(?:^|(?<=\s))//[^\n]*", re.S | re.M)
def _blank(pattern, text):
"""Replace matches with spaces, keeping offsets and newlines."""
return pattern.sub(lambda m: re.sub(r"[^\n]", " ", m.group()), text)
def blank_comments(text):
return _blank(SQL_COMMENT, text)
def blank_markup_comments(text):
return _blank(MARKUP_COMMENT, text)
def _is_scannable(path):
if path.name in SKIP_FILES or path.suffix.lower() in BINARY_EXTS:
return False
try:
return (path.is_file() and not path.is_symlink()
and path.stat().st_size <= MAX_BYTES)
except OSError:
return False
def _excluded(root, path, prefixes):
rel = Path(path).relative_to(root).as_posix()
return any(rel == p or rel.startswith(p + "/") for p in prefixes)
def _kept_dirs(root, base, dirs, prefixes):
return [
d for d in dirs
if d not in SKIP_DIRS and not _excluded(root, Path(base) / d, prefixes)
]
def _kept_files(root, base, names, prefixes):
for name in names:
path = Path(base) / name
if _is_scannable(path) and not _excluded(root, path, prefixes):
yield path
def _walk(root, prefixes):
for base, dirs, names in os.walk(root):
dirs[:] = _kept_dirs(root, base, dirs, prefixes)
yield from _kept_files(root, base, names, prefixes)
class Project:
"""A directory tree read as data. Nothing in it is ever executed."""
def __init__(self, root, exclude=()):
self.root = Path(root).resolve()
prefixes = [e.strip("/") for e in exclude if e.strip("/")]
self.files = sorted(_walk(self.root, prefixes))
self._text = {}
def rel(self, path):
return path.relative_to(self.root).as_posix()
def text(self, path):
if path not in self._text:
try:
self._text[path] = path.read_text(
encoding="utf-8", errors="ignore")
except OSError:
self._text[path] = ""
return self._text[path]
def with_ext(self, *exts):
return [p for p in self.files if p.suffix.lower() in exts]
def named(self, *names):
return [p for p in self.files if p.name in names]
def segments(self, path):
return self.rel(path).split("/")[:-1]
def matches(self, pattern, files=None, flags=re.I):
"""Yield (path, match) for each regex hit in the given files."""
regex = re.compile(pattern, flags)
for path in (self.files if files is None else files):
for match in regex.finditer(self.text(path)):
yield path, match
def has(self, pattern, files=None, flags=re.I):
return next(self.matches(pattern, files, flags), None) is not None
def found(self, rule, path, offset, message):
line = line_of(self.text(path), offset) if offset else 1
return Finding(
rule.domain, rule.id, rule.severity, self.rel(path), line,
message)
def found_at_root(self, domain, rule, severity, message):
return Finding(domain, rule, severity, ".", 1, message)
def non_doc_files(project):
"""Files that can hold behavior: everything except docs and samples."""
skip = (".md", ".mdx", ".txt", ".example", ".sample", ".template")
return [p for p in project.files if not p.name.endswith(skip)]
@@ -0,0 +1,242 @@
"""Cloud function checks: no self-trigger, instance cap, budget stop."""
import re
from dataclasses import dataclass
from .common import Rule, SOURCE_EXTS, non_doc_files
from .supabase import function_statement, sql_files, split_name
DOMAIN = "functions"
INFRA_EXTS = (".yml", ".yaml", ".tf", ".toml", ".json", ".sh")
AWS_PATTERN = r"AWS::Serverless|AWS::Lambda|aws_lambda_function|lambda_runtime"
GCP_PATTERN = (
r"google_cloudfunctions|google_cloud_run"
r"|gcloud\s+(?:functions|run)\s+deploy"
)
CAPS = {
"Firebase": r"maxInstances|max_instances",
"AWS Lambda": r"reserved_?concurren\w*",
"Google Cloud": (
r"max[-_]instances|max_instance_count|maxInstanceCount|maxInstances"
),
}
_NAME = r'(?:"?\w+"?\.)?"?\w+"?'
TRIGGER = re.compile(
r"create\s+(?:or\s+replace\s+)?trigger\s+(?P<name>\w+)\s+"
r"(?:before|after|instead\s+of)\s+[^;]*?\bon\s+(?P<table>" + _NAME
+ r")\s+(?P<rest>[^;]*?)execute\s+(?:function|procedure)\s+"
r"(?P<func>" + _NAME + r")\s*\((?P<args>[^;]*)\)\s*;", re.I | re.S)
CREATE_FUNCTION = re.compile(
r"create\s+(?:or\s+replace\s+)?function\s+(" + _NAME + r")\s*\(", re.I)
FN_URL = re.compile(r"/functions/v1/([\w-]+)")
FIREBASE_V2 = re.compile(
r"(onDocument\w+)\(\s*(?:\{[^}]*\}\s*,\s*)?['\"`]([^'\"`]+)['\"`]")
FIREBASE_V1 = re.compile(
r"\.document\(\s*['\"`]([^'\"`]+)['\"`]\s*\)\s*\.(on\w+)\(")
REWRITES_SELF = ("Written", "Updated", "onWrite", "onUpdate")
def supabase_functions(project):
"""Map edge function name to its files."""
found = {}
for path in project.files:
parts = project.rel(path).split("/")
if parts[:2] == ["supabase", "functions"] and len(parts) > 3:
if parts[2] != "_shared":
found.setdefault(parts[2], []).append(path)
return found
def _infra(project):
return project.with_ext(*INFRA_EXTS)
def _firebase(project):
return bool(project.named("firebase.json")) and project.has(
r'"functions"|firebase-functions', project.files)
def _vercel(project):
return bool(project.named("vercel.json")) and any(
"api" in project.segments(p) for p in project.with_ext(*SOURCE_EXTS))
def detect(project):
on = {
"Supabase Edge Functions": bool(supabase_functions(project)),
"Firebase": _firebase(project),
"AWS Lambda": project.has(AWS_PATTERN, _infra(project)),
"Google Cloud": project.has(GCP_PATTERN, _infra(project)),
"Vercel Functions": _vercel(project),
"Netlify Functions": any(
"netlify/functions/" in project.rel(p) for p in project.files),
"Cloudflare Workers": bool(
project.named("wrangler.toml", "wrangler.json", "wrangler.jsonc")),
}
return [label for label, enabled in on.items() if enabled]
def applies(project):
return bool(detect(project))
def check(project):
platforms = detect(project)
out = _instance_caps(project, platforms)
out += _budget_stop(project, platforms)
out += _supabase_loops(project) + _self_invoke(project)
return out + _firebase_loops(project)
def _instance_caps(project, platforms):
out = []
docs = non_doc_files(project)
for label in platforms:
pattern = CAPS.get(label)
if pattern is None:
out.append(project.found_at_root(
DOMAIN, "FN-CAP-UNVERIFIED", "MANUAL",
f"{label}: no instance cap to verify from code; check the "
"provider docs for a concurrency limit, and rely on the "
"spend cap, rate limiting and a short timeout"))
elif not project.has(pattern, docs):
out.append(project.found_at_root(
DOMAIN, "FN-NO-MAX-INSTANCES", "FAIL",
f"{label}: no max instances or reserved concurrency set"))
return out
def _budget_stop(project, platforms):
return [
project.found_at_root(
DOMAIN, "FN-BUDGET-STOP", "MANUAL",
f"{label}: wire a budget alert to an automatic stop (throttle "
"concurrency to zero, revoke invoke rights or disable billing); "
"verify it in the console")
for label in platforms
]
def _function_bodies(sql):
"""Map function name to the text of its CREATE FUNCTION statement."""
bodies = {}
for _, text in sql:
for m in CREATE_FUNCTION.finditer(text):
bodies[split_name(m.group(1))[1]] = function_statement(
text, m.start())
return bodies
@dataclass(frozen=True)
class Loop:
"""An edge function fired by a database trigger on `table`."""
function: str
table: str
trigger: str
guarded: bool
def _loops_of(m, bodies):
func = split_name(m["func"])[1]
source = m["args"] if func == "http_request" else bodies.get(func, "")
guarded = bool(re.search(r"\bwhen\b", m["rest"], re.I))
table = split_name(m["table"])[1]
return [Loop(u.group(1), table, m["name"], guarded)
for u in FN_URL.finditer(source)]
def _triggered_edge_functions(sql):
"""Yield a Loop per edge function that a database trigger calls."""
bodies = _function_bodies(sql)
for _, text in sql:
for m in TRIGGER.finditer(text):
yield from _loops_of(m, bodies)
def _writes_table(table):
return re.compile(
r"\.(?:from|table)\(\s*['\"`](?:public\.)?" + re.escape(table)
+ r"['\"`]\s*\)\s*\.(?:insert|update|upsert|delete)\s*\("
r"|(?:update|insert\s+into|delete\s+from)\s+(?:public\.)?"
+ re.escape(table) + r"\b", re.I)
def _supabase_loops(project):
functions = supabase_functions(project)
out = []
for loop in _triggered_edge_functions(sql_files(project)):
for path in functions.get(loop.function, []):
out += _loop_findings(project, path, loop)
return out
def _loop_findings(project, path, loop):
m = _writes_table(loop.table).search(project.text(path))
return [_loop_finding(project, path, m.start(), loop)] if m else []
def _loop_finding(project, path, offset, loop):
head = (f'"{loop.function}" writes "{loop.table}" which fires trigger '
f"{loop.trigger}")
if loop.guarded:
return project.found(
Rule(DOMAIN, "FN-SELF-TRIGGER", "WARN"), path, offset,
head + ", guarded by WHEN: confirm the write cannot satisfy it")
return project.found(
Rule(DOMAIN, "FN-SELF-TRIGGER", "FAIL"), path, offset,
head + ": infinite loop; add a WHEN guard or an idempotency flag")
def _invocations(project, name, paths):
pattern = (r"functions/v1/" + re.escape(name)
+ r"\b|invoke\(\s*['\"]" + re.escape(name) + r"['\"]")
return [
project.found(
Rule(DOMAIN, "FN-SELF-INVOKE", "FAIL"), path, m.start(),
f'"{name}" invokes itself: cap the depth or remove the call')
for path, m in project.matches(pattern, paths)
]
def _self_invoke(project):
out = []
for name, paths in supabase_functions(project).items():
out += _invocations(project, name, paths)
return out
def _firebase_handlers(text):
"""Yield (collection, kind, offset) for each Firestore trigger."""
for m in FIREBASE_V2.finditer(text):
yield m.group(2).split("/")[0], m.group(1), m.start()
for m in FIREBASE_V1.finditer(text):
yield m.group(1).split("/")[0], m.group(2), m.start()
def _file_loops(project, path):
text = project.text(path)
return [
project.found(
Rule(DOMAIN, "FN-SELF-TRIGGER", "WARN"), path, offset,
f'trigger on "{collection}" also writes it in this file: '
"confirm the write cannot fire the trigger again")
for collection, kind, offset in _firebase_handlers(text)
if _rewrites_trigger(text, collection, kind)
]
def _firebase_loops(project):
out = []
for path in project.with_ext(".js", ".ts", ".mjs"):
if not project.rel(path).startswith("supabase/"):
out += _file_loops(project, path)
return out
def _rewrites_trigger(text, collection, kind):
own_ref = re.search(r"\.ref\.(?:set|update)\(", text)
if own_ref and kind.endswith(REWRITES_SELF):
return True
return re.search(
r"collection\(\s*['\"`]" + re.escape(collection)
+ r"['\"`]\s*\)(?:\s*\.doc\([^)]*\))?\s*\.(?:add|set|update)\(",
text) is not None
+101
View File
@@ -0,0 +1,101 @@
"""Hosting checks: rate limit, CDN and firewall, spend cap."""
from .apis import route_files
from .common import Rule, non_doc_files
DOMAIN = "hosting"
PLATFORMS = {
"vercel.json": ("Vercel", True),
"netlify.toml": ("Netlify", True),
"wrangler.toml": ("Cloudflare", True),
"wrangler.json": ("Cloudflare", True),
"wrangler.jsonc": ("Cloudflare", True),
"firebase.json": ("Firebase Hosting", True),
"amplify.yml": ("AWS Amplify", True),
"fly.toml": ("Fly.io", False),
"render.yaml": ("Render", False),
"railway.json": ("Railway", False),
"railway.toml": ("Railway", False),
"docker-compose.yml": ("Docker Compose", False),
"docker-compose.yaml": ("Docker Compose", False),
"compose.yml": ("Docker Compose", False),
"compose.yaml": ("Docker Compose", False),
"nginx.conf": ("nginx", False),
"Caddyfile": ("Caddy", False),
".htaccess": ("Apache", False),
"app.yaml": ("App Engine", False),
}
RATE_LIMIT = (
r"rate[-_ ]?limit|ratelimit|limit_req|throttl|governor|slowapi"
r"|flask[-_]limiter|django[-_]ratelimit|@vercel/firewall|fail2ban"
r"|\blimiter\b"
)
CDN_MENTION = (
r"cloudflare|cloudfront|fastly|bunny\.net|akamai|cf-connecting-ip"
r"|set_real_ip_from"
)
SPEND_HINTS = {
"Vercel": "set a Spend Management amount with automatic pause",
}
SPEND_DEFAULT = (
"check the plan for a hard spend cap and enable it; if there is none, "
"set a budget alert and write the kill-switch step in the deploy notes"
)
def detect(project):
"""Map platform label to (has_cdn, config path)."""
found = {}
for path in project.files:
entry = ("Docker", False) if path.name.startswith("Dockerfile") \
else PLATFORMS.get(path.name)
if entry:
found.setdefault(entry[0], (entry[1], path))
return found
def applies(project):
return bool(detect(project)) or bool(route_files(project))
def check(project):
platforms = detect(project)
return (_rate_limit(project, platforms)
+ _origin_exposure(project, platforms)
+ _manual_items(project, platforms))
def _rate_limit(project, platforms):
if project.has(RATE_LIMIT, non_doc_files(project)):
return []
return [project.found_at_root(
DOMAIN, "HOST-NO-RATE-LIMIT", "FAIL",
"no rate limiting found: add it per IP and per account on login, "
"signup, reset, send and upload")]
def _origin_exposure(project, platforms):
origins = sorted(
label for label, (has_cdn, _) in platforms.items() if not has_cdn)
if not origins or project.has(CDN_MENTION):
return []
return [project.found_at_root(
DOMAIN, "HOST-ORIGIN-EXPOSED", "WARN",
", ".join(origins) + ": the origin is served directly; put a CDN "
"and firewall in front (Cloudflare, CloudFront, Fastly)")]
def _manual_items(project, platforms):
out = [project.found_at_root(
DOMAIN, "HOST-WAF-DDOS", "MANUAL",
"enable the CDN firewall: DDoS protection, bot rules, rate rules "
"(dashboard setting, not visible from code)")]
if not platforms:
out.append(project.found_at_root(
DOMAIN, "HOST-SPEND-CAP", "MANUAL",
"no hosting config found: " + SPEND_DEFAULT))
for label, (_, path) in platforms.items():
out.append(project.found(
Rule(DOMAIN, "HOST-SPEND-CAP", "MANUAL"), path, 0,
f"{label}: " + SPEND_HINTS.get(label, SPEND_DEFAULT)))
return out
@@ -0,0 +1,164 @@
"""SMS and email checks: recorded consent, unsubscribe, STOP handling."""
import re
from dataclasses import dataclass
from .common import Rule, SOURCE_EXTS, non_doc_files
DOMAIN = "messaging"
MANIFESTS = (
"package.json", "Cargo.toml", "requirements.txt", "pyproject.toml",
"composer.json", "go.mod", "deno.json",
)
EMAIL_SENDER = (
r"nodemailer|@sendgrid/mail|sendgrid\.com|api\.resend\.com"
r"|new Resend\(|from ['\"]resend['\"]|postmark|mailgun|sib-api-v3"
r"|sendinblue|brevo|mailjet|mandrill|client-ses|SendEmailCommand"
r"|smtplib|use lettre|lettre::|PHPMailer|mailchimp"
)
SMS_SENDER = (
r"twilio|vonage|nexmo|messagebird|sns\.publish|@aws-sdk/client-sns"
r"|PublishCommand|ovh.{0,20}sms|plivo|sinch|clicksend|smsapi"
r"|sendTransacSms|telnyx|infobip|africastalking"
)
CONSENT_STORED = (
r"consent(?:ed)?_?(?:at|date|ts|timestamp|source|status|given|version"
r"|text)|opt_?in_?(?:at|date|source|ts|timestamp)|opted_?in|double_?opt"
r"|marketing_consent|has_consented|sms_consent|email_consent"
)
CONSENT_CHECKED = (
r"consent|opt_?in|opted|subscribed|unsubscrib|suppress|allowed_to_contact"
)
UNSUBSCRIBE = r"unsubscrib|d[ée]sinscri"
OPT_OUT_STORED = (
r"opt_?out|unsubscribed|stopped|suppress|blocklist|do_not_(?:contact|text)"
)
TRANSACTIONAL = re.compile(
r"contact|reset|verif|otp|password|confirm|receipt|invoice|welcome"
r"|magic|login|signin|2fa|mfa|booking|reservation", re.I)
MARKETING = re.compile(
r"newsletter|campaign|subscriber|mailing|broadcast|promo|marketing"
r"|bulk|audience|relance|blast", re.I)
TRANSACTIONAL_NOTE = " (only transactional senders found: confirm no marketing)"
TEST_PATH = re.compile(
r"(?:^|/)(?:tests?|__tests__|spec)/|\.(?:test|spec)\.|Test\.php$", re.I)
BULK_STORAGE = (
r"subscriber|newsletter|mailing[_ ]?list|contact_list|audience"
)
def sender_files(project):
files = project.with_ext(*SOURCE_EXTS) + project.named(*MANIFESTS)
return [p for p in files if not TEST_PATH.search(project.rel(p))]
def _sends(project, path):
return project.has(EMAIL_SENDER, [path]) or project.has(SMS_SENDER, [path])
def _kind(project, path):
rel = project.rel(path)
if MARKETING.search(rel):
return "marketing"
return "transactional" if TRANSACTIONAL.search(rel) else "unknown"
def _severity(project, senders):
"""FAIL unless a sender looks transactional and nothing bulk exists."""
code = [p for p in senders if p.suffix.lower() in SOURCE_EXTS] or senders
kinds = {_kind(project, p) for p in code}
if "marketing" in kinds or "transactional" not in kinds:
return "FAIL"
if project.has(BULK_STORAGE, non_doc_files(project)):
return "FAIL"
return "WARN"
def applies(project):
files = sender_files(project)
return project.has(EMAIL_SENDER, files) or project.has(SMS_SENDER, files)
@dataclass(frozen=True)
class Sending:
senders: list
severity: str
email: object
sms: object
def _first_hit(project, pattern, files):
return next(project.matches(pattern, files), None)
def _context(project):
files = sender_files(project)
senders = [p for p in files if _sends(project, p)]
return Sending(
senders, _severity(project, senders),
_first_hit(project, EMAIL_SENDER, files),
_first_hit(project, SMS_SENDER, files))
def check(project):
ctx = _context(project)
out = _consent(project, ctx.email or ctx.sms, ctx.senders, ctx.severity)
if ctx.email:
out += _email_rules(project, ctx.email, ctx.severity)
if ctx.sms:
out += _sms_rules(project, ctx.sms, ctx.severity)
return out
def _note(severity):
return TRANSACTIONAL_NOTE if severity == "WARN" else ""
def _consent(project, hit, senders, severity):
path, m = hit
if not project.has(CONSENT_STORED, non_doc_files(project), 0):
return [project.found(
Rule(DOMAIN, "MSG-NO-CONSENT-RECORD", severity), path, m.start(),
"messages are sent but no consent record exists: store who, "
"when, channel, source and wording per contact" + _note(severity))]
return [
project.found(
Rule(DOMAIN, "MSG-SEND-UNCHECKED", "WARN"), p, 0,
"sends messages without checking consent or the suppression "
"list in this file")
for p in senders
if p.suffix.lower() in SOURCE_EXTS
and _kind(project, p) != "transactional"
and not project.has(CONSENT_CHECKED, [p])
]
def _email_rules(project, hit, severity):
path, m = hit
docs = non_doc_files(project)
if not project.has(UNSUBSCRIBE, docs):
return [project.found(
Rule(DOMAIN, "MSG-NO-UNSUBSCRIBE", severity), path, m.start(),
"emails are sent but no unsubscribe link exists" + _note(severity))]
if not project.has(r"list-unsubscribe", docs):
return [project.found(
Rule(DOMAIN, "MSG-NO-LIST-UNSUBSCRIBE", "WARN"), path, m.start(),
"add the List-Unsubscribe header (one-click); Gmail and Yahoo "
"require it from bulk senders")]
return []
def _sms_rules(project, hit, severity):
path, m = hit
docs = non_doc_files(project)
out = []
if not project.has(r"\bSTOP\b", docs, 0):
out.append(project.found(
Rule(DOMAIN, "MSG-SMS-NO-STOP", severity), path, m.start(),
"SMS are sent but nothing tells the recipient to reply STOP"
+ _note(severity)))
if not project.has(OPT_OUT_STORED, docs):
out.append(project.found(
Rule(DOMAIN, "MSG-SMS-NO-OPTOUT-STORE", severity), path, m.start(),
"no opt-out storage: a STOP reply must be recorded and "
"checked before every send" + _note(severity)))
return out
@@ -0,0 +1,137 @@
"""Password handling: clear storage or compare, fast hash, log, literal."""
import re
from .common import Rule, SOURCE_EXTS, non_doc_files, redact
DOMAIN = "api"
NAME = r"(?:password|passwd|pwd|mot_de_passe)"
CONFIG_EXTS = {".yml", ".yaml", ".toml", ".ini", ".cfg", ".conf", ".sh",
".properties", ".json"}
SKIP_PATH = re.compile(
r"\.(?:test|spec|e2e|stories)\.|(?:^|/)(?:tests?|__tests__|spec|e2e"
r"|fixtures?|i18n|locales?|lang|translations?|messages)/", re.I)
HASH_EVIDENCE = (
r"bcrypt|argon2|scrypt|pbkdf2|password_hash\(|password_verify\("
r"|Hash::make|make_password|hashpw|PasswordHasher|hash_password"
r"|verify_password|\bphpass\b")
COLUMN = (
rf"\b{NAME}\s+(?:text|varchar|character varying|char|citext|string)\b"
rf"|->string\(\s*['\"]{NAME}['\"]"
rf"|\b{NAME}\s*=\s*models\.(?:Char|Text)Field"
rf"|\b{NAME}\s*:\s*(?:text|varchar)\(")
COMPARE = (
rf"(?:\.|->|\[['\"]){NAME}['\"]?\]?\s*[!=]==?\s*[\w$]"
rf"|[\w$\]\)]\s*[!=]==?\s*\$?\w+(?:\.|->){NAME}\b"
rf"|\b(?:where|and)\s+(?:\w+\.)?{NAME}\s*=\s*(?:\$\d+|\?|:\w+|%s)")
COMPARE_SKIP = re.compile(
r"confirm|repeat|again|undefined|null|hash|digest|length", re.I)
WEAK_HASH = (
rf"\b(?:md5|sha1|sha256|sha512|crc32|hashlib\.\w+)\s*\(\s*[^()\n]*{NAME}"
rf"|createHash\([^)\n]*\)\s*\.update\(\s*[^()\n]*{NAME}"
rf"|\bhash\(\s*['\"](?:md5|sha1|sha256|sha512)['\"]\s*,\s*[^()\n]*{NAME}")
WEAK_SKIP = re.compile(r"token|reset|otp|nonce|session", re.I)
LOG_CALL = (
r"\b(?:console\.\w+|logger?\.\w+|log\.\w+|logging\.\w+|print(?:ln!?)?"
r"|error_log|Log::\w+|tracing::\w+!|dbg!|var_dump|print_r)\s*\(([^\n]*)")
STRING = re.compile(r"'[^'\n]*'|\"[^\"\n]*\"|`[^`\n]*`")
LOGGED_NAME = re.compile(
rf"\b(?:(?:new|old|plain|raw|user|current)_?)?{NAME}\b|\bcredentials\b",
re.I)
LITERAL = rf"\b(\w*{NAME})['\"]?\s*(?:[:=]|=>)\s*['\"]([^'\"\n]{{8,}})['\"]"
BARE_LITERAL = rf"\b(\w*{NAME})(?:=\s*|:\s+)([^'\"\s#]{{8,}})"
PLACEHOLDER = re.compile(
r"change|your|xxx|\*\*|example|placeholder|dummy|sample|secret[-_ ]?here"
r"|^[$%<{.*/]|\||required|^\$argon|^[0-9a-f]{32,}$|^[a-z]+(?:_[a-z]+)+$| ",
re.I)
PLAINTEXT = Rule(DOMAIN, "API-PASSWORD-PLAINTEXT", "FAIL")
LITERAL_RULE = Rule(DOMAIN, "API-PASSWORD-LITERAL", "WARN")
def _line(text, offset):
start = text.rfind("\n", 0, offset) + 1
end = text.find("\n", offset)
return text[start:] if end < 0 else text[start:end]
def _files(project):
return [p for p in non_doc_files(project)
if not SKIP_PATH.search(project.rel(p))]
def check(project):
files = _files(project)
return (_columns(project, files) + _compares(project, files)
+ _weak_hash(project, files) + _logged(project, files)
+ _literals(project, files))
def _columns(project, files):
if project.has(HASH_EVIDENCE, files):
return []
return [
project.found(
PLAINTEXT, path, m.start(),
"password column and no hashing library anywhere: store an "
"argon2id or bcrypt hash, never the password")
for path, m in project.matches(COLUMN, files)
]
def _compares(project, files):
return [
project.found(
PLAINTEXT, path, m.start(),
"stored password compared in clear: verify a hash with the "
"library's constant-time check")
for path, m in project.matches(COMPARE, files)
if not COMPARE_SKIP.search(_line(project.text(path), m.start()))
]
def _weak_hash(project, files):
return [
project.found(
Rule(DOMAIN, "API-PASSWORD-WEAK-HASH", "FAIL"), path, m.start(),
"password through a fast hash: use argon2id, scrypt or bcrypt")
for path, m in project.matches(WEAK_HASH, files)
if not WEAK_SKIP.search(_line(project.text(path), m.start()))
]
def _log_args(args):
"""Call arguments with string literals reduced to their interpolations."""
return STRING.sub(
lambda m: " ".join(re.findall(r"\{([^}]*)\}", m.group())), args)
def _logged(project, files):
return [
project.found(
Rule(DOMAIN, "API-PASSWORD-LOGGED", "FAIL"), path, m.start(),
"password reaches a log: never log credentials")
for path, m in project.matches(LOG_CALL, files)
if LOGGED_NAME.search(_log_args(m.group(1)))
]
def _is_placeholder(key, value):
return value.lower() == key.lower() or bool(PLACEHOLDER.search(value))
def _literal_hits(project, files, pattern):
return [
project.found(
LITERAL_RULE, path, m.start(),
f"{m.group(1)} set to a literal ({redact(m.group(2))}): a real "
"credential moves to env and gets rotated; a dev default is "
"documented as such")
for path, m in project.matches(pattern, files)
if not _is_placeholder(m.group(1), m.group(2))
]
def _literals(project, files):
config = [p for p in files if p.suffix.lower() in CONFIG_EXTS]
source = [p for p in files if p.suffix.lower() in SOURCE_EXTS]
return (_literal_hits(project, source + config, LITERAL)
+ _literal_hits(project, config, BARE_LITERAL))
@@ -0,0 +1,332 @@
"""Supabase checks: RLS, owner-scoped policies, keys kept off the client."""
import base64
import json
import re
from dataclasses import dataclass
from .apis import ignore_patterns, is_ignored_env
from .common import Rule, SOURCE_EXTS, blank_comments
DOMAIN = "supabase"
_NAME = r'(?:"?\w+"?\.)?"?\w+"?'
TABLE = re.compile(
r"create\s+(?:unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?(?P<name>"
+ _NAME + r")", re.I)
RLS_ON = re.compile(
r"alter\s+table\s+(?:only\s+)?(?:if\s+exists\s+)?(?P<name>" + _NAME
+ r")\s+enable\s+row\s+level\s+security", re.I)
DROP = re.compile(
r"drop\s+table\s+(?:if\s+exists\s+)?(?P<name>" + _NAME + r")", re.I)
POLICY = re.compile(
r"create\s+policy\s+(?P<pname>\"[^\"]+\"|\w+)\s+on\s+(?P<table>"
+ _NAME + r")(?P<rest>[^;]*);", re.I)
VIEW = re.compile(
r"create\s+(?:or\s+replace\s+)?(?P<mat>materialized\s+)?view\s+"
r"(?P<name>" + _NAME + r")(?P<rest>[^;]*);", re.I)
FUNCTION = re.compile(
r"create\s+(?:or\s+replace\s+)?function\s+(?P<name>" + _NAME + r")\s*\(",
re.I)
BUCKET_SQL = re.compile(
r"(?:insert\s+into|update)\s+storage\.buckets[^;]*;", re.I)
OPEN_EXPR = re.compile(r"\b(?:using|with\s+check)\s*\(\s*true\s*\)")
OWNER = re.compile(r"auth\.(?:uid|jwt|role)\s*\(")
WRITE_CMDS = {"all", "insert", "update", "delete"}
ANON_ROLES = {"anon", "public"}
PRIVILEGED_ROLES = {"service_role", "postgres", "supabase_admin"}
SERVICE_REF = r"service_role|SERVICE_ROLE|SUPABASE_SECRET_KEY|sb_secret_"
SERVER_SEGMENTS = {
"functions", "api", "server", "scripts", "tests", "test", "migrations",
"seed", ".github", "supabase", "tools",
}
CLIENT_SEGMENTS = {
"components", "public", "static", "client", "browser", "www", "islands",
}
CLIENT_EXTS = (".vue", ".svelte", ".html", ".htm")
SCRIPT_EXTS = (".ts", ".tsx", ".js", ".jsx", ".mjs")
JWT = r"eyJ[\w-]{8,}\.(eyJ[\w-]{8,})\.[\w-]{8,}"
MANIFESTS = (
"package.json", "Cargo.toml", "requirements.txt", "pyproject.toml",
"pubspec.yaml", "composer.json", "go.mod", "deno.json",
)
@dataclass(frozen=True)
class Policy:
name: str
table: str
cmd: str
roles: tuple
open_expr: bool
owner: bool
offset: int
def split_name(raw):
"""Return (schema, name), schema defaulting to public."""
parts = raw.replace('"', "").lower().split(".")
return (parts[0], parts[1]) if len(parts) == 2 else ("public", parts[0])
def function_statement(text, start):
"""Text of a CREATE FUNCTION from `start` to its closing semicolon."""
tag = re.compile(r"\bas\s+(\$\w*\$)", re.I).search(text, start)
if not tag:
end = text.find(";", start)
else:
close = text.find(tag.group(1), tag.end())
end = text.find(";", close if close != -1 else tag.end())
return text[start:end if end != -1 else len(text)]
def sql_files(project):
return [(p, blank_comments(project.text(p)))
for p in project.with_ext(".sql")]
def applies(project):
if (project.root / "supabase").is_dir():
return True
return project.has(r"supabase", project.named(*MANIFESTS))
def check(project):
sql = sql_files(project)
out = _rls(project, sql)
for path, text in sql:
out += (_policies(project, path, text) + _views(project, path, text)
+ _functions(project, path, text, sql)
+ _buckets(project, path, text))
out += _config(project) + _client_leaks(project) + _jwt_literals(project)
return _dedupe_last(out)
def _dedupe_last(findings):
"""An object redefined by a later migration is reported once, there."""
latest = {(f.rule, f.message): f for f in findings}
return [f for f in findings if latest[(f.rule, f.message)] is f]
LIVE_NOTE = (
"static check sees migrations only: run the RLS query from "
"references/checks.md against the live project")
def _public_name(m):
schema, name = split_name(m["name"])
return name if schema == "public" else None
def _created_tables(sql):
created = {}
for path, text in sql:
for m in TABLE.finditer(text):
name = _public_name(m)
if name:
created.setdefault(name, (path, m.start()))
return created
def _all_names(pattern, sql):
return {split_name(m["name"])[1]
for _, text in sql for m in pattern.finditer(text)}
def _rls(project, sql):
live = project.found_at_root(DOMAIN, "SB-RLS-LIVE", "MANUAL", LIVE_NOTE)
covered = _all_names(RLS_ON, sql) | _all_names(DROP, sql)
return [live] + [
project.found(
Rule(DOMAIN, "SB-RLS-MISSING", "FAIL"), path, offset,
f'table "{name}" never enables row level security')
for name, (path, offset) in _created_tables(sql).items()
if name not in covered
]
def _roles(rest):
to = re.search(r"\bto\s+(.+?)(?=\s+(?:using|with\s+check)\b|$)", rest, re.S)
listed = to.group(1).split(",") if to else ["public"]
return tuple(r.strip(' "') for r in listed)
def parse_policy(m):
rest = m["rest"].lower()
cmd = re.search(r"\bfor\s+(all|select|insert|update|delete)\b", rest)
return Policy(
m["pname"].strip('"'), split_name(m["table"])[1],
cmd.group(1) if cmd else "all", _roles(rest),
bool(OPEN_EXPR.search(rest)), bool(OWNER.search(rest)), m.start())
def policy_issues(pol):
"""Return (Rule, message) pairs for one policy."""
if set(pol.roles) <= PRIVILEGED_ROLES:
return []
writes = pol.cmd in WRITE_CMDS
anon = bool(ANON_ROLES & set(pol.roles))
where = f'policy "{pol.name}" on "{pol.table}"'
if pol.open_expr and writes:
return [(Rule(DOMAIN, "SB-POLICY-OPEN-WRITE", "FAIL"),
f"{where}: true on a write lets anyone change rows")]
if writes and anon and not pol.owner:
return [(Rule(DOMAIN, "SB-POLICY-ANON-WRITE", "FAIL"),
f"{where}: anon can write; scope it to auth.uid()")]
if pol.open_expr:
return [(Rule(DOMAIN, "SB-POLICY-PUBLIC-READ", "WARN"),
f"{where}: open read; confirm the data is public")]
if not pol.owner:
return [(Rule(DOMAIN, "SB-POLICY-NOT-OWNER", "WARN"),
f"{where}: not tied to auth.uid(); confirm owner scoping")]
return []
def _policies(project, path, text):
out = []
for m in POLICY.finditer(text):
pol = parse_policy(m)
for rule, message in policy_issues(pol):
out.append(project.found(rule, path, pol.offset, message))
return out
def _views(project, path, text):
out = []
for m in VIEW.finditer(text):
schema, name = split_name(m["name"])
if schema != "public":
continue
if m["mat"]:
out.append(project.found(
Rule(DOMAIN, "SB-MATVIEW-EXPOSED", "WARN"), path, m.start(),
f'materialized view "{name}" ignores RLS: do not expose it'))
elif "security_invoker" not in m["rest"].lower():
out.append(project.found(
Rule(DOMAIN, "SB-VIEW-INVOKER", "WARN"), path, m.start(),
f'view "{name}" runs as its owner: add security_invoker'))
return out
def _statements(sql, word):
return " ".join(t for _, t in sql if word in t.lower())
def _revoked(revokes, name):
pattern = r"revoke\s+(?:all|execute)[^;]*\b" + re.escape(name) + r"\b"
return re.search(pattern, revokes, re.I) is not None
def _execute_issue(revokes, grants, name, stmt):
if "returns trigger" in stmt or _revoked(revokes, name):
return None
granted = r"grant\s+(?:all|execute)[^;]*\b" + re.escape(name)
if re.search(granted + r"\b[^;]*\banon\b", grants, re.I):
return (f'definer function "{name}" is explicitly granted to anon: '
"confirm it is meant to be public")
return (f'definer function "{name}" is callable by anon by default: '
"revoke execute from public, anon")
def _definer_findings(project, path, m, text, privileges):
schema, name = split_name(m["name"])
stmt = function_statement(text, m.start()).lower()
if schema != "public" or "security definer" not in stmt:
return []
out = []
if "set search_path" not in stmt:
out.append(project.found(
Rule(DOMAIN, "SB-DEFINER-SEARCH-PATH", "WARN"), path, m.start(),
f'definer function "{name}" must pin search_path'))
issue = _execute_issue(*privileges, name, stmt)
if issue:
out.append(project.found(
Rule(DOMAIN, "SB-DEFINER-EXECUTE", "WARN"), path, m.start(),
issue))
return out
def _functions(project, path, text, sql):
privileges = (_statements(sql, "revoke"), _statements(sql, "grant"))
out = []
for m in FUNCTION.finditer(text):
out += _definer_findings(project, path, m, text, privileges)
return out
def _buckets(project, path, text):
return [
project.found(
Rule(DOMAIN, "SB-BUCKET-PUBLIC", "WARN"), path, m.start(),
"storage bucket set public: confirm every file is meant "
"to be world-readable")
for m in BUCKET_SQL.finditer(text)
if re.search(r"\btrue\b", m.group(), re.I)
]
def _config(project):
out = []
for path in project.named("config.toml"):
if path.parent.name != "supabase":
continue
text = project.text(path)
for m in re.finditer(
r"\[functions\.([\w-]+)\][^\[]*?verify_jwt\s*=\s*false",
text, re.S):
out.append(project.found(
Rule(DOMAIN, "SB-EDGE-NO-JWT", "WARN"), path, m.start(),
f'function "{m.group(1)}" skips JWT verification: confirm '
"it checks a webhook signature instead"))
for m in re.finditer(
r"\[storage\.buckets\.([\w-]+)\][^\[]*?public\s*=\s*true",
text, re.S):
out.append(project.found(
Rule(DOMAIN, "SB-BUCKET-PUBLIC", "WARN"), path, m.start(),
f'bucket "{m.group(1)}" is public: confirm it is intended'))
return out
def _client_reachable(project, path):
segments = set(project.segments(path))
if segments & SERVER_SEGMENTS:
return False
if path.suffix.lower() in CLIENT_EXTS:
return True
if path.suffix.lower() not in SCRIPT_EXTS:
return False
head = project.text(path)[:300]
return bool(segments & CLIENT_SEGMENTS) or "use client" in head
def _client_leaks(project):
files = project.with_ext(*SOURCE_EXTS, *CLIENT_EXTS)
return [
project.found(
Rule(DOMAIN, "SB-SERVICE-ROLE-CLIENT", "FAIL"), path, m.start(),
"service role or secret key referenced in client-reachable "
"code: it bypasses RLS for anyone who reads the bundle")
for path, m in project.matches(SERVICE_REF, files, 0)
if _client_reachable(project, path)
]
def _jwt_role(payload):
try:
raw = base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))
data = json.loads(raw)
except ValueError:
return None
return data.get("role") if isinstance(data, dict) else None
def _jwt_literals(project):
patterns = ignore_patterns(project)
return [
project.found(
Rule(DOMAIN, "SB-SERVICE-ROLE-LITERAL", "FAIL"), path, m.start(),
"service_role JWT hardcoded: rotate the key, keep it in "
"server env only")
for path, m in project.matches(JWT, None, 0)
if _jwt_role(m.group(1)) == "service_role"
and not is_ignored_env(path, patterns)
]
+129
View File
@@ -0,0 +1,129 @@
#!/usr/bin/env python3
"""Static guardrails scan: API, hosting, a11y, Supabase, messaging, functions.
Reads a project tree as data and never executes it. Exit codes:
0 no FAIL, 1 at least one FAIL, 2 usage error.
"""
import argparse
import json
import sys
from dataclasses import dataclass
from pathlib import Path
from checks import a11y, apis, functions, hosting, messaging, supabase
from checks.common import Project
DOMAINS = {
"api": apis,
"hosting": hosting,
"a11y": a11y,
"supabase": supabase,
"messaging": messaging,
"functions": functions,
}
SEVERITY_RANK = {"FAIL": 0, "WARN": 1, "MANUAL": 2}
@dataclass(frozen=True)
class Result:
findings: list
applicable: list
skipped: list
def parse_args(argv):
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("path", help="project root to scan")
parser.add_argument(
"--domain", default=",".join(DOMAINS),
help="comma list among: " + ", ".join(DOMAINS))
parser.add_argument(
"--exclude", default="",
help="comma list of relative paths to skip (copies, vendored code)")
parser.add_argument("--json", action="store_true", help="JSON output")
return parser.parse_args(argv)
def _split(value):
return [part.strip() for part in value.split(",") if part.strip()]
def run_checks(project, names):
findings, applicable, skipped = [], [], []
for name in names:
module = DOMAINS[name]
if module.applies(project):
applicable.append(name)
findings += module.check(project)
else:
skipped.append(name)
findings.sort(key=lambda f: (
SEVERITY_RANK[f.severity], f.domain, f.path, f.line))
return Result(findings, applicable, skipped)
def summarize(findings):
return {sev: sum(f.severity == sev for f in findings)
for sev in SEVERITY_RANK}
def _domain_lines(domain, findings):
rows = [f for f in findings if f.domain == domain]
return [f"\n[{domain}]"] + (
[f" {f.severity:<6} {f.rule:<24} {f.path}:{f.line} {f.message}"
for f in rows] or [" no finding"])
def _summary_line(findings):
totals = summarize(findings)
return "\nsummary: " + ", ".join(
f"{n} {sev}" for sev, n in totals.items())
def render_text(project, result):
lines = [
f"guardrails scan: {project.root} ({len(project.files)} files)",
"scanned: " + (", ".join(result.applicable) or "none"),
]
if result.skipped:
lines.append("not applicable: " + ", ".join(result.skipped))
for domain in result.applicable:
lines += _domain_lines(domain, result.findings)
return "\n".join(lines + [_summary_line(result.findings)])
def render_json(project, result):
return json.dumps({
"root": str(project.root), "files": len(project.files),
"applicable": result.applicable, "not_applicable": result.skipped,
"summary": summarize(result.findings),
"findings": [f.as_dict() for f in result.findings],
}, indent=2)
def _usage_error(path, names):
unknown = [n for n in names if n not in DOMAINS]
if unknown:
return f"unknown domain {unknown}"
return "" if Path(path).is_dir() else f"not a directory: {path}"
def _scan(args):
project = Project(Path(args.path), _split(args.exclude))
result = run_checks(project, _split(args.domain))
render = render_json if args.json else render_text
print(render(project, result))
return 1 if any(f.severity == "FAIL" for f in result.findings) else 0
def main(argv):
args = parse_args(argv)
error = _usage_error(args.path, _split(args.domain))
if error:
print(f"usage error: {error}", file=sys.stderr)
return 2
return _scan(args)
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))