rlsproof 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CALIBRATION.md +63 -0
- package/LICENSE +21 -0
- package/README.md +151 -2
- package/SECURITY.md +23 -0
- package/action.yml +113 -0
- package/bin/rlsproof.js +230 -0
- package/package.json +50 -4
- package/src/core/findings.js +145 -0
- package/src/core/ignore.js +197 -0
- package/src/core/rules.js +155 -0
- package/src/index.js +186 -0
- package/src/reporters/json.js +25 -0
- package/src/reporters/markdown.js +95 -0
- package/src/reporters/sarif.js +101 -0
- package/src/sql/expr-analyzer.js +289 -0
- package/src/sql/parser.js +486 -0
- package/src/sql/sql-rules.js +360 -0
- package/src/sql/state-graph.js +694 -0
- package/src/surface/ai-api-scanner.js +337 -0
- package/src/surface/config-toml.js +137 -0
- package/src/surface/file-walker.js +105 -0
- package/src/surface/secret-scanner.js +247 -0
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import crypto from "node:crypto";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { RULES } from "./rules.js";
|
|
4
|
+
|
|
5
|
+
export const SEVERITY_ORDER = {
|
|
6
|
+
CRITICAL: 4,
|
|
7
|
+
HIGH: 3,
|
|
8
|
+
MEDIUM: 2,
|
|
9
|
+
LOW: 1,
|
|
10
|
+
INFO: 0,
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Redacts sensitive secret literals so no raw token ever leaves the local scanner.
|
|
15
|
+
* @param {string} value
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
export function redactSecret(value) {
|
|
19
|
+
if (!value || typeof value !== "string") return "";
|
|
20
|
+
let out = value;
|
|
21
|
+
|
|
22
|
+
// Mask JWTs (eyJ...eyJ...sig)
|
|
23
|
+
out = out.replace(
|
|
24
|
+
/\beyJ[A-Za-z0-9_-]{6,}\.eyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{4,}\b/g,
|
|
25
|
+
(m) => `${m.slice(0, 12)}...[REDACTED_JWT]...${m.slice(-4)}`
|
|
26
|
+
);
|
|
27
|
+
|
|
28
|
+
// Mask known secret key prefixes
|
|
29
|
+
out = out.replace(
|
|
30
|
+
/\b(sb_secret_|sk-proj-|sk-ant-api\d*-|sk-ant-|sk_live_|rk_live_|whsec_|AIza|sk-)([A-Za-z0-9_-]{8,})/g,
|
|
31
|
+
(_m, prefix, rest) => `${prefix}${rest.slice(0, 2)}...[REDACTED]`
|
|
32
|
+
);
|
|
33
|
+
|
|
34
|
+
// Mask Postgres URI passwords
|
|
35
|
+
out = out.replace(
|
|
36
|
+
/(postgres(?:ql)?:\/\/[^:\s/]+:)([^@\s/]+)(@)/gi,
|
|
37
|
+
"$1[REDACTED]$3"
|
|
38
|
+
);
|
|
39
|
+
|
|
40
|
+
return out;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Normalizes a snippet line safely and ensures secrets are redacted.
|
|
45
|
+
* @param {string} snippet
|
|
46
|
+
* @param {number} maxLen
|
|
47
|
+
* @returns {string}
|
|
48
|
+
*/
|
|
49
|
+
export function sanitizeSnippet(snippet, maxLen = 140) {
|
|
50
|
+
if (!snippet || typeof snippet !== "string") return "";
|
|
51
|
+
const redacted = redactSecret(snippet).replace(/\s+/g, " ").trim();
|
|
52
|
+
if (redacted.length <= maxLen) return redacted;
|
|
53
|
+
return `${redacted.slice(0, maxLen - 3)}...`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function toPosixRelPath(rootDir, filePath) {
|
|
57
|
+
if (!filePath) return "";
|
|
58
|
+
if (!path.isAbsolute(filePath)) {
|
|
59
|
+
return filePath.replace(/\\/g, "/");
|
|
60
|
+
}
|
|
61
|
+
const rel = path.relative(rootDir, filePath);
|
|
62
|
+
return (rel || path.basename(filePath)).replace(/\\/g, "/");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Generates a deterministic line-independent fingerprint so `--baseline` survives
|
|
67
|
+
* unrelated edits or line shifts in migration/source files.
|
|
68
|
+
*/
|
|
69
|
+
export function computeFingerprint(ruleId, relPath, objectKey) {
|
|
70
|
+
const normalizedPath = String(relPath || "").replace(/\\/g, "/");
|
|
71
|
+
const payload = `${ruleId}|${normalizedPath}|${String(objectKey || "")}`;
|
|
72
|
+
return crypto.createHash("sha256").update(payload).digest("hex").slice(0, 16);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Creates a normalized, redacted finding record from the canonical rule registry.
|
|
77
|
+
*/
|
|
78
|
+
export function createFinding({
|
|
79
|
+
ruleId,
|
|
80
|
+
severity,
|
|
81
|
+
file,
|
|
82
|
+
line = 1,
|
|
83
|
+
object,
|
|
84
|
+
title,
|
|
85
|
+
detail,
|
|
86
|
+
remediation,
|
|
87
|
+
snippet = "",
|
|
88
|
+
rootDir = process.cwd(),
|
|
89
|
+
evidence = undefined,
|
|
90
|
+
}) {
|
|
91
|
+
const rule = RULES[ruleId];
|
|
92
|
+
if (!rule) {
|
|
93
|
+
throw new Error(`Unknown ruleId: ${ruleId}`);
|
|
94
|
+
}
|
|
95
|
+
const relFile = toPosixRelPath(rootDir, file);
|
|
96
|
+
const safeObject = redactSecret(String(object || relFile || ruleId));
|
|
97
|
+
const safeSnippet = sanitizeSnippet(snippet);
|
|
98
|
+
const safeDetail = redactSecret(String(detail || rule.description));
|
|
99
|
+
const safeTitle = redactSecret(String(title || rule.title));
|
|
100
|
+
const safeRemediation = redactSecret(String(remediation || rule.remediation));
|
|
101
|
+
const sev = severity || rule.severity;
|
|
102
|
+
|
|
103
|
+
return {
|
|
104
|
+
ruleId,
|
|
105
|
+
fingerprint: computeFingerprint(ruleId, relFile, safeObject),
|
|
106
|
+
severity: sev,
|
|
107
|
+
category: rule.category,
|
|
108
|
+
file: relFile,
|
|
109
|
+
line: Number.isInteger(line) && line > 0 ? line : 1,
|
|
110
|
+
object: safeObject,
|
|
111
|
+
title: safeTitle,
|
|
112
|
+
detail: safeDetail,
|
|
113
|
+
remediation: safeRemediation,
|
|
114
|
+
snippet: safeSnippet,
|
|
115
|
+
cwe: rule.cwe,
|
|
116
|
+
owasp: rule.owasp,
|
|
117
|
+
...(evidence ? { evidence } : {}),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function sortFindings(findings) {
|
|
122
|
+
return [...findings].sort((a, b) => {
|
|
123
|
+
const sevDiff = (SEVERITY_ORDER[b.severity] ?? 0) - (SEVERITY_ORDER[a.severity] ?? 0);
|
|
124
|
+
if (sevDiff !== 0) return sevDiff;
|
|
125
|
+
if (a.file !== b.file) return a.file.localeCompare(b.file);
|
|
126
|
+
if (a.line !== b.line) return a.line - b.line;
|
|
127
|
+
return a.ruleId.localeCompare(b.ruleId);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function summarizeFindings(findings) {
|
|
132
|
+
const counts = {
|
|
133
|
+
total: findings.length,
|
|
134
|
+
critical: 0,
|
|
135
|
+
high: 0,
|
|
136
|
+
medium: 0,
|
|
137
|
+
low: 0,
|
|
138
|
+
info: 0,
|
|
139
|
+
};
|
|
140
|
+
for (const f of findings) {
|
|
141
|
+
const key = String(f.severity || "INFO").toLowerCase();
|
|
142
|
+
if (key in counts) counts[key] += 1;
|
|
143
|
+
}
|
|
144
|
+
return counts;
|
|
145
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Converts a simple gitignore/glob pattern into a safe RegExp for POSIX relative paths.
|
|
6
|
+
*/
|
|
7
|
+
function globToRegex(pattern) {
|
|
8
|
+
const clean = pattern.replace(/\\/g, "/").replace(/^\.\//, "").trim();
|
|
9
|
+
let regexStr = "";
|
|
10
|
+
let i = 0;
|
|
11
|
+
while (i < clean.length) {
|
|
12
|
+
const ch = clean[i];
|
|
13
|
+
const next = clean[i + 1];
|
|
14
|
+
if (ch === "*" && next === "*") {
|
|
15
|
+
if (clean[i + 2] === "/") {
|
|
16
|
+
regexStr += "(?:.*/)?";
|
|
17
|
+
i += 3;
|
|
18
|
+
} else {
|
|
19
|
+
regexStr += ".*";
|
|
20
|
+
i += 2;
|
|
21
|
+
}
|
|
22
|
+
continue;
|
|
23
|
+
}
|
|
24
|
+
if (ch === "*") {
|
|
25
|
+
regexStr += "[^/]*";
|
|
26
|
+
i += 1;
|
|
27
|
+
continue;
|
|
28
|
+
}
|
|
29
|
+
if (ch === "?") {
|
|
30
|
+
regexStr += "[^/]";
|
|
31
|
+
i += 1;
|
|
32
|
+
continue;
|
|
33
|
+
}
|
|
34
|
+
if ("/[].+^${}()|\\".includes(ch)) {
|
|
35
|
+
regexStr += `\\${ch}`;
|
|
36
|
+
} else {
|
|
37
|
+
regexStr += ch;
|
|
38
|
+
}
|
|
39
|
+
i += 1;
|
|
40
|
+
}
|
|
41
|
+
// If pattern has no slash and isn't already wildcard-prefixed, match basename or full relative path
|
|
42
|
+
if (!clean.includes("/")) {
|
|
43
|
+
return new RegExp(`^(?:.*/)?${regexStr}(?:/.*)?$`, "i");
|
|
44
|
+
}
|
|
45
|
+
return new RegExp(`^${regexStr}(?:/.*)?$`, "i");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Loads `.rlsproofignore` rules if present.
|
|
50
|
+
* Supported entries:
|
|
51
|
+
* - `# comment`
|
|
52
|
+
* - path glob (e.g. `supabase/seed.sql`, `tests/**`, `*.test.ts`)
|
|
53
|
+
* - rule-scoped ignore: `rule:<RULE_ID>:<pathOrObjectGlob>`
|
|
54
|
+
*/
|
|
55
|
+
export function loadIgnoreConfig(rootDir, customIgnoreFile = null, disabled = false) {
|
|
56
|
+
const empty = {
|
|
57
|
+
pathPatterns: [],
|
|
58
|
+
rulePatterns: [],
|
|
59
|
+
isPathIgnored: () => false,
|
|
60
|
+
isFindingIgnored: () => false,
|
|
61
|
+
};
|
|
62
|
+
if (disabled) return empty;
|
|
63
|
+
|
|
64
|
+
const ignorePath = customIgnoreFile
|
|
65
|
+
? path.resolve(customIgnoreFile)
|
|
66
|
+
: path.join(rootDir, ".rlsproofignore");
|
|
67
|
+
|
|
68
|
+
if (!fs.existsSync(ignorePath) || !fs.statSync(ignorePath).isFile()) {
|
|
69
|
+
return empty;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const lines = fs.readFileSync(ignorePath, "utf8").split(/\r?\n/);
|
|
73
|
+
const pathPatterns = [];
|
|
74
|
+
const rulePatterns = [];
|
|
75
|
+
|
|
76
|
+
for (const rawLine of lines) {
|
|
77
|
+
const line = rawLine.trim();
|
|
78
|
+
if (!line || line.startsWith("#")) continue;
|
|
79
|
+
|
|
80
|
+
if (line.toLowerCase().startsWith("rule:")) {
|
|
81
|
+
const rest = line.slice(5);
|
|
82
|
+
const colonIdx = rest.indexOf(":");
|
|
83
|
+
if (colonIdx !== -1) {
|
|
84
|
+
const ruleId = rest.slice(0, colonIdx).trim().toUpperCase();
|
|
85
|
+
const targetGlob = rest.slice(colonIdx + 1).trim();
|
|
86
|
+
if (ruleId && targetGlob) {
|
|
87
|
+
rulePatterns.push({
|
|
88
|
+
ruleId,
|
|
89
|
+
raw: line,
|
|
90
|
+
regex: globToRegex(targetGlob),
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
} else {
|
|
94
|
+
const ruleId = rest.trim().toUpperCase();
|
|
95
|
+
if (ruleId) {
|
|
96
|
+
rulePatterns.push({ ruleId, raw: line, regex: /^.*$/ });
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
pathPatterns.push({
|
|
103
|
+
raw: line,
|
|
104
|
+
regex: globToRegex(line),
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function isPathIgnored(relPosixPath) {
|
|
109
|
+
const normalized = String(relPosixPath || "").replace(/\\/g, "/").replace(/^\.\//, "");
|
|
110
|
+
return pathPatterns.some((p) => p.regex.test(normalized));
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isFindingIgnored(finding) {
|
|
114
|
+
const fileNorm = String(finding.file || "").replace(/\\/g, "/");
|
|
115
|
+
if (isPathIgnored(fileNorm)) return true;
|
|
116
|
+
|
|
117
|
+
for (const rp of rulePatterns) {
|
|
118
|
+
if (rp.ruleId !== "*" && rp.ruleId !== finding.ruleId) continue;
|
|
119
|
+
if (rp.regex.test(fileNorm) || rp.regex.test(String(finding.object || ""))) {
|
|
120
|
+
return true;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
return {
|
|
127
|
+
ignorePath,
|
|
128
|
+
pathPatterns,
|
|
129
|
+
rulePatterns,
|
|
130
|
+
isPathIgnored,
|
|
131
|
+
isFindingIgnored,
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Checks whether a finding has an inline `rlsproof-ignore <RULE_ID>` comment
|
|
137
|
+
* on the finding line or the line immediately preceding it.
|
|
138
|
+
*/
|
|
139
|
+
export function hasInlineSuppression(fileText, lineNumber, ruleId) {
|
|
140
|
+
if (!fileText || !lineNumber || lineNumber < 1) return false;
|
|
141
|
+
const lines = fileText.split(/\r?\n/);
|
|
142
|
+
const candidateIndexes = [lineNumber - 1, lineNumber - 2].filter(
|
|
143
|
+
(idx) => idx >= 0 && idx < lines.length
|
|
144
|
+
);
|
|
145
|
+
for (const idx of candidateIndexes) {
|
|
146
|
+
const match = lines[idx].match(/(?:--|\/\/|#)\s*rlsproof-ignore(?:-next-line)?\s*:?\s*([A-Z0-9_,\s*]+)/i);
|
|
147
|
+
if (!match) continue;
|
|
148
|
+
const tokens = match[1]
|
|
149
|
+
.split(/[\s,]+/)
|
|
150
|
+
.map((t) => t.trim().toUpperCase())
|
|
151
|
+
.filter(Boolean);
|
|
152
|
+
if (tokens.includes("*") || tokens.includes("ALL") || tokens.includes(ruleId.toUpperCase())) {
|
|
153
|
+
return true;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return false;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function loadBaseline(baselinePath) {
|
|
160
|
+
const abs = path.resolve(baselinePath);
|
|
161
|
+
if (!fs.existsSync(abs)) {
|
|
162
|
+
throw new Error(`Baseline file not found: ${abs}`);
|
|
163
|
+
}
|
|
164
|
+
const raw = JSON.parse(fs.readFileSync(abs, "utf8"));
|
|
165
|
+
const list = Array.isArray(raw?.fingerprints) ? raw.fingerprints : [];
|
|
166
|
+
return new Set(list.map((fp) => String(fp)));
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function writeBaseline(baselinePath, findings) {
|
|
170
|
+
const abs = path.resolve(baselinePath);
|
|
171
|
+
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
|
172
|
+
const fingerprints = [...new Set(findings.map((f) => f.fingerprint))].sort();
|
|
173
|
+
const payload = {
|
|
174
|
+
tool: "rlsproof",
|
|
175
|
+
version: 1,
|
|
176
|
+
generatedAt: new Date().toISOString(),
|
|
177
|
+
fingerprints,
|
|
178
|
+
};
|
|
179
|
+
fs.writeFileSync(abs, `${JSON.stringify(payload, null, 2)}\n`, "utf8");
|
|
180
|
+
return abs;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
export function filterFindingsByBaseline(findings, baselineSet) {
|
|
184
|
+
if (!baselineSet || baselineSet.size === 0) {
|
|
185
|
+
return { activeFindings: findings, baselinedCount: 0 };
|
|
186
|
+
}
|
|
187
|
+
const activeFindings = [];
|
|
188
|
+
let baselinedCount = 0;
|
|
189
|
+
for (const f of findings) {
|
|
190
|
+
if (baselineSet.has(f.fingerprint)) {
|
|
191
|
+
baselinedCount += 1;
|
|
192
|
+
} else {
|
|
193
|
+
activeFindings.push(f);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return { activeFindings, baselinedCount };
|
|
197
|
+
}
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Canonical rule registry for rlsproof v1.0.
|
|
3
|
+
* Twelve high-signal defensive rules covering PostgreSQL/Supabase cumulative
|
|
4
|
+
* migration state, hardcoded/client-exposed secrets, Edge Function JWT gates,
|
|
5
|
+
* and OWASP API4 AI endpoint cost protection.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export const RULES = {
|
|
9
|
+
RLS_DISABLED: {
|
|
10
|
+
id: "RLS_DISABLED",
|
|
11
|
+
severity: "CRITICAL",
|
|
12
|
+
category: "SQL / Row Level Security",
|
|
13
|
+
title: "Row Level Security is disabled on an exposed table",
|
|
14
|
+
description:
|
|
15
|
+
"Tables in PostgREST-exposed schemas without ENABLE ROW LEVEL SECURITY are readable and writable via the Data API according to base role grants.",
|
|
16
|
+
remediation:
|
|
17
|
+
"Enable RLS with `ALTER TABLE <schema>.<table> ENABLE ROW LEVEL SECURITY;` and define explicit per-command policies.",
|
|
18
|
+
cwe: "CWE-284",
|
|
19
|
+
owasp: "API1:2023 Broken Object Level Authorization",
|
|
20
|
+
},
|
|
21
|
+
RLS_PERMISSIVE_TAUTOLOGY: {
|
|
22
|
+
id: "RLS_PERMISSIVE_TAUTOLOGY",
|
|
23
|
+
severity: "CRITICAL",
|
|
24
|
+
category: "SQL / Row Level Security",
|
|
25
|
+
title: "Permissive RLS policy uses an always-true tautology without restrictive narrowing",
|
|
26
|
+
description:
|
|
27
|
+
"A permissive policy evaluates to TRUE (for example `USING (true)`, `1 = 1`, or `WITH CHECK (true)`) for client roles with no covering AS RESTRICTIVE policy.",
|
|
28
|
+
remediation:
|
|
29
|
+
"Replace the tautology with an explicit tenant or ownership predicate such as `user_id = auth.uid()` or `public.is_org_member(org_id)`.",
|
|
30
|
+
cwe: "CWE-863",
|
|
31
|
+
owasp: "API1:2023 Broken Object Level Authorization",
|
|
32
|
+
},
|
|
33
|
+
RLS_INSERT_MISSING_WITH_CHECK: {
|
|
34
|
+
id: "RLS_INSERT_MISSING_WITH_CHECK",
|
|
35
|
+
severity: "HIGH",
|
|
36
|
+
category: "SQL / Row Level Security",
|
|
37
|
+
title: "INSERT policy omits WITH CHECK constraint",
|
|
38
|
+
description:
|
|
39
|
+
"An INSERT policy without a WITH CHECK expression allows client roles to insert arbitrary rows, including rows owned by other users or tenants.",
|
|
40
|
+
remediation:
|
|
41
|
+
"Add an explicit `WITH CHECK (...)` predicate verifying ownership or tenant membership on inserted rows.",
|
|
42
|
+
cwe: "CWE-284",
|
|
43
|
+
owasp: "API1:2023 Broken Object Level Authorization",
|
|
44
|
+
},
|
|
45
|
+
RLS_USER_METADATA_TRUST: {
|
|
46
|
+
id: "RLS_USER_METADATA_TRUST",
|
|
47
|
+
severity: "HIGH",
|
|
48
|
+
category: "SQL / Row Level Security",
|
|
49
|
+
title: "RLS policy trusts client-modifiable user_metadata",
|
|
50
|
+
description:
|
|
51
|
+
"Auth `user_metadata` (`raw_user_meta_data`) can be updated by authenticated end-users via `supabase.auth.updateUser()` and must not be used for authorization.",
|
|
52
|
+
remediation:
|
|
53
|
+
"Use server-controlled `app_metadata` or database membership/role tables instead of `user_metadata` inside RLS policies.",
|
|
54
|
+
cwe: "CWE-639",
|
|
55
|
+
owasp: "API5:2023 Broken Function Level Authorization",
|
|
56
|
+
},
|
|
57
|
+
SECURITY_DEFINER_UNSAFE_RPC: {
|
|
58
|
+
id: "SECURITY_DEFINER_UNSAFE_RPC",
|
|
59
|
+
severity: "CRITICAL",
|
|
60
|
+
category: "SQL / RPC Security",
|
|
61
|
+
title: "Callable SECURITY DEFINER function lacks search_path pinning or caller authorization",
|
|
62
|
+
description:
|
|
63
|
+
"An exposed SECURITY DEFINER function executable by PUBLIC, anon, or authenticated runs with owner privileges (bypassing RLS) without pinning `search_path` and/or checking caller authorization.",
|
|
64
|
+
remediation:
|
|
65
|
+
"Prefer `SECURITY INVOKER`; when `SECURITY DEFINER` is required, add `SET search_path = ''`, enforce `auth.uid()` / membership checks inside the body, and revoke unnecessary `EXECUTE` grants.",
|
|
66
|
+
cwe: "CWE-269",
|
|
67
|
+
owasp: "API5:2023 Broken Function Level Authorization",
|
|
68
|
+
},
|
|
69
|
+
VIEW_MISSING_SECURITY_INVOKER: {
|
|
70
|
+
id: "VIEW_MISSING_SECURITY_INVOKER",
|
|
71
|
+
severity: "HIGH",
|
|
72
|
+
category: "SQL / Views",
|
|
73
|
+
title: "Exposed view runs with definer privileges (missing security_invoker = true)",
|
|
74
|
+
description:
|
|
75
|
+
"PostgreSQL views execute with the view creator's privileges by default, bypassing underlying table RLS policies for API callers.",
|
|
76
|
+
remediation:
|
|
77
|
+
"Create or alter the view with `WITH (security_invoker = true)` (PostgreSQL 15+) or revoke client `SELECT` grants.",
|
|
78
|
+
cwe: "CWE-284",
|
|
79
|
+
owasp: "API1:2023 Broken Object Level Authorization",
|
|
80
|
+
},
|
|
81
|
+
STORAGE_BUCKET_OVEREXPOSED: {
|
|
82
|
+
id: "STORAGE_BUCKET_OVEREXPOSED",
|
|
83
|
+
severity: "CRITICAL",
|
|
84
|
+
category: "SQL / Storage",
|
|
85
|
+
title: "Supabase Storage bucket or objects policy allows cross-tenant or sensitive public access",
|
|
86
|
+
description:
|
|
87
|
+
"Storage policies that only check `bucket_id` without owner/folder scoping, or sensitive buckets marked `public = true`, expose cross-tenant object uploads or reads.",
|
|
88
|
+
remediation:
|
|
89
|
+
"Set sensitive buckets to `public = false` and enforce path/owner checks such as `(storage.foldername(name))[1] = auth.uid()::text` or tenant membership.",
|
|
90
|
+
cwe: "CWE-284",
|
|
91
|
+
owasp: "API1:2023 Broken Object Level Authorization",
|
|
92
|
+
},
|
|
93
|
+
SECRET_HARDCODED_OR_CLIENT_EXPOSED: {
|
|
94
|
+
id: "SECRET_HARDCODED_OR_CLIENT_EXPOSED",
|
|
95
|
+
severity: "CRITICAL",
|
|
96
|
+
category: "Surface / Secrets",
|
|
97
|
+
title: "Privileged secret key, token, or client-exposed privileged environment variable detected",
|
|
98
|
+
description:
|
|
99
|
+
"Hardcoded service_role JWTs, LLM/payment secret keys, credentialed Postgres URIs, or client-bundled `VITE_`/`NEXT_PUBLIC_` secret variables bypass all access boundaries.",
|
|
100
|
+
remediation:
|
|
101
|
+
"Move secrets to server-only environment variables or Edge Function secrets, remove `VITE_`/`NEXT_PUBLIC_` prefixes from privileged keys, and rotate exposed credentials.",
|
|
102
|
+
cwe: "CWE-798",
|
|
103
|
+
owasp: "API2:2023 Broken Authentication",
|
|
104
|
+
},
|
|
105
|
+
ANON_OPEN_EXPOSURE: {
|
|
106
|
+
id: "ANON_OPEN_EXPOSURE",
|
|
107
|
+
severity: "HIGH",
|
|
108
|
+
category: "SQL + Surface / Anon Exposure",
|
|
109
|
+
title: "Unauthenticated anon role has open write or privileged execution access",
|
|
110
|
+
description:
|
|
111
|
+
"While Supabase `anon` keys are intentionally public client identifiers, combining active `anon` access with permissive `TO anon` writes, RLS-disabled grants, or unsafe `SECURITY DEFINER` grants exposes data without login.",
|
|
112
|
+
remediation:
|
|
113
|
+
"Restrict write policies and sensitive RPC execution to `authenticated` (or server-side `service_role`) with explicit ownership checks.",
|
|
114
|
+
cwe: "CWE-306",
|
|
115
|
+
owasp: "API2:2023 Broken Authentication",
|
|
116
|
+
},
|
|
117
|
+
EDGE_FUNCTION_VERIFY_JWT_DISABLED: {
|
|
118
|
+
id: "EDGE_FUNCTION_VERIFY_JWT_DISABLED",
|
|
119
|
+
severity: "HIGH",
|
|
120
|
+
category: "Surface / Edge Functions",
|
|
121
|
+
title: "Edge Function disables verify_jwt without alternative authentication or webhook signature check",
|
|
122
|
+
description:
|
|
123
|
+
"Setting `verify_jwt = false` in `supabase/config.toml` without verifying a webhook HMAC signature or checking bearer/user auth exposes the Edge Function to unauthenticated callers.",
|
|
124
|
+
remediation:
|
|
125
|
+
"Enable `verify_jwt = true` in `supabase/config.toml` or enforce cryptographic webhook signature / manual `supabase.auth.getUser()` validation inside the handler.",
|
|
126
|
+
cwe: "CWE-306",
|
|
127
|
+
owasp: "API2:2023 Broken Authentication",
|
|
128
|
+
},
|
|
129
|
+
AI_ENDPOINT_NO_AUTH: {
|
|
130
|
+
id: "AI_ENDPOINT_NO_AUTH",
|
|
131
|
+
severity: "CRITICAL",
|
|
132
|
+
category: "Surface / OWASP API4 AI Protection",
|
|
133
|
+
title: "Paid AI/LLM API endpoint lacks caller authentication",
|
|
134
|
+
description:
|
|
135
|
+
"An API route or Edge Function invokes a server-billed LLM provider without verifying caller identity or session authentication, allowing anonymous cost-drain attacks.",
|
|
136
|
+
remediation:
|
|
137
|
+
"Require verified authentication (e.g. `verify_jwt = true` + `auth.getUser()` or server session verification) before invoking any paid AI provider.",
|
|
138
|
+
cwe: "CWE-306",
|
|
139
|
+
owasp: "API4:2023 Unrestricted Resource Consumption",
|
|
140
|
+
},
|
|
141
|
+
AI_ENDPOINT_UNBOUNDED_COST: {
|
|
142
|
+
id: "AI_ENDPOINT_UNBOUNDED_COST",
|
|
143
|
+
severity: "HIGH",
|
|
144
|
+
category: "Surface / OWASP API4 AI Protection",
|
|
145
|
+
title: "Authenticated AI endpoint lacks rate limit/budget cap, max_tokens limit, or model allowlist",
|
|
146
|
+
description:
|
|
147
|
+
"Even with a valid free-tier `authenticated` JWT, AI endpoints without per-user budget/rate limits, server-enforced `max_tokens`, and a model allowlist can be drained by automated bots (OWASP API4).",
|
|
148
|
+
remediation:
|
|
149
|
+
"Enforce a server-side model allowlist, clamp `max_tokens` / input size, and apply atomic rate-limit or credit budget checks prior to upstream LLM requests.",
|
|
150
|
+
cwe: "CWE-770",
|
|
151
|
+
owasp: "API4:2023 Unrestricted Resource Consumption",
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
export const RULE_LIST = Object.values(RULES);
|
package/src/index.js
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import fs from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { performance } from "node:perf_hooks";
|
|
4
|
+
import {
|
|
5
|
+
SEVERITY_ORDER,
|
|
6
|
+
sortFindings,
|
|
7
|
+
summarizeFindings,
|
|
8
|
+
toPosixRelPath,
|
|
9
|
+
} from "./core/findings.js";
|
|
10
|
+
import {
|
|
11
|
+
filterFindingsByBaseline,
|
|
12
|
+
hasInlineSuppression,
|
|
13
|
+
loadBaseline,
|
|
14
|
+
loadIgnoreConfig,
|
|
15
|
+
writeBaseline,
|
|
16
|
+
} from "./core/ignore.js";
|
|
17
|
+
import { RULE_LIST } from "./core/rules.js";
|
|
18
|
+
import { discoverSqlFiles, parseMigrationFiles } from "./sql/parser.js";
|
|
19
|
+
import { evaluateSqlRules } from "./sql/sql-rules.js";
|
|
20
|
+
import { buildCumulativeStateGraph } from "./sql/state-graph.js";
|
|
21
|
+
import { scanAiAndEdgeSurface } from "./surface/ai-api-scanner.js";
|
|
22
|
+
import { parseSupabaseConfigToml } from "./surface/config-toml.js";
|
|
23
|
+
import { walkRepoFiles } from "./surface/file-walker.js";
|
|
24
|
+
import { scanSecrets } from "./surface/secret-scanner.js";
|
|
25
|
+
|
|
26
|
+
const PKG = JSON.parse(
|
|
27
|
+
fs.readFileSync(new URL("../package.json", import.meta.url), "utf8")
|
|
28
|
+
);
|
|
29
|
+
|
|
30
|
+
export const TOOL_NAME = "rlsproof";
|
|
31
|
+
export const TOOL_VERSION = PKG.version;
|
|
32
|
+
|
|
33
|
+
export { RULE_LIST };
|
|
34
|
+
|
|
35
|
+
export function shouldFailForFindings(findings, failOn = "high") {
|
|
36
|
+
const normalized = String(failOn || "high").toLowerCase();
|
|
37
|
+
if (normalized === "none") return false;
|
|
38
|
+
const threshold = SEVERITY_ORDER[normalized.toUpperCase()] ?? SEVERITY_ORDER.HIGH;
|
|
39
|
+
return findings.some((f) => (SEVERITY_ORDER[f.severity] ?? 0) >= threshold);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Scans a local repository, migration directory, or SQL/source file.
|
|
44
|
+
* Purely local and defensive — makes zero network requests.
|
|
45
|
+
*/
|
|
46
|
+
export async function scanProject(targetPath = ".", options = {}) {
|
|
47
|
+
const startedAt = performance.now();
|
|
48
|
+
const absTarget = path.resolve(targetPath);
|
|
49
|
+
|
|
50
|
+
if (!fs.existsSync(absTarget)) {
|
|
51
|
+
throw new Error(`Target path does not exist: ${absTarget}`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const stat = fs.statSync(absTarget);
|
|
55
|
+
const rootDir = stat.isDirectory() ? absTarget : path.dirname(absTarget);
|
|
56
|
+
|
|
57
|
+
const ignoreConfig = loadIgnoreConfig(
|
|
58
|
+
rootDir,
|
|
59
|
+
options.ignoreFile || null,
|
|
60
|
+
Boolean(options.noIgnore)
|
|
61
|
+
);
|
|
62
|
+
|
|
63
|
+
// 1. Discover files & parse supabase/config.toml
|
|
64
|
+
const configToml = parseSupabaseConfigToml(rootDir);
|
|
65
|
+
const sqlDiscovery = discoverSqlFiles(absTarget);
|
|
66
|
+
const activeSqlFiles = sqlDiscovery.files.filter(
|
|
67
|
+
(f) => !ignoreConfig.isPathIgnored(toPosixRelPath(rootDir, f))
|
|
68
|
+
);
|
|
69
|
+
const { files: repoFiles } = walkRepoFiles(absTarget, ignoreConfig);
|
|
70
|
+
|
|
71
|
+
// 2. M1 — Parse SQL migrations and build cumulative state graph
|
|
72
|
+
const {
|
|
73
|
+
parsedStatements,
|
|
74
|
+
unsupported: parseUnsupported,
|
|
75
|
+
parseStats,
|
|
76
|
+
fileTexts: sqlFileTexts,
|
|
77
|
+
} = await parseMigrationFiles(activeSqlFiles, rootDir);
|
|
78
|
+
|
|
79
|
+
const state = buildCumulativeStateGraph(parsedStatements, configToml.api.schemas);
|
|
80
|
+
|
|
81
|
+
// 3. M2-Lite — Scan repo secrets, config.toml, Edge Functions, and OWASP API4 AI endpoints
|
|
82
|
+
const { findings: secretFindings, anonClientUsageDetected } = scanSecrets(repoFiles, rootDir);
|
|
83
|
+
const aiEdgeFindings = scanAiAndEdgeSurface(repoFiles, rootDir, configToml);
|
|
84
|
+
|
|
85
|
+
const anonSurfaceActive = configToml.api.enabled !== false && anonClientUsageDetected;
|
|
86
|
+
const sqlFindings = evaluateSqlRules(state, { rootDir, anonSurfaceActive });
|
|
87
|
+
|
|
88
|
+
// 4. Merge findings + apply .rlsproofignore + inline suppressions
|
|
89
|
+
const fileTextCache = new Map(sqlFileTexts);
|
|
90
|
+
const getTextForRel = (relFile) => {
|
|
91
|
+
if (fileTextCache.has(relFile)) return fileTextCache.get(relFile);
|
|
92
|
+
const full = path.join(rootDir, relFile);
|
|
93
|
+
try {
|
|
94
|
+
const txt = fs.readFileSync(full, "utf8");
|
|
95
|
+
fileTextCache.set(relFile, txt);
|
|
96
|
+
return txt;
|
|
97
|
+
} catch {
|
|
98
|
+
return "";
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
const allRawFindings = [...sqlFindings, ...secretFindings, ...aiEdgeFindings];
|
|
103
|
+
let suppressedCount = 0;
|
|
104
|
+
const nonSuppressed = [];
|
|
105
|
+
|
|
106
|
+
for (const f of allRawFindings) {
|
|
107
|
+
if (ignoreConfig.isFindingIgnored(f)) {
|
|
108
|
+
suppressedCount += 1;
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
const text = getTextForRel(f.file);
|
|
112
|
+
if (hasInlineSuppression(text, f.line, f.ruleId)) {
|
|
113
|
+
suppressedCount += 1;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
nonSuppressed.push(f);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
const sortedBeforeBaseline = sortFindings(nonSuppressed);
|
|
120
|
+
|
|
121
|
+
if (options.writeBaseline) {
|
|
122
|
+
writeBaseline(options.writeBaseline, sortedBeforeBaseline);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
let activeFindings = sortedBeforeBaseline;
|
|
126
|
+
let baselinedCount = 0;
|
|
127
|
+
if (options.baseline) {
|
|
128
|
+
const baselineSet = loadBaseline(options.baseline);
|
|
129
|
+
const filtered = filterFindingsByBaseline(sortedBeforeBaseline, baselineSet);
|
|
130
|
+
activeFindings = filtered.activeFindings;
|
|
131
|
+
baselinedCount = filtered.baselinedCount;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const unsupported = [...parseUnsupported, ...state.unsupported];
|
|
135
|
+
const parseRate =
|
|
136
|
+
parseStats.statementsTotal === 0
|
|
137
|
+
? 100
|
|
138
|
+
: Number(((parseStats.statementsParsed / parseStats.statementsTotal) * 100).toFixed(2));
|
|
139
|
+
|
|
140
|
+
const failOn = String(options.failOn || "high").toLowerCase();
|
|
141
|
+
const hasBlockingFindings = shouldFailForFindings(activeFindings, failOn);
|
|
142
|
+
|
|
143
|
+
let status = "PASS";
|
|
144
|
+
if (hasBlockingFindings && unsupported.length > 0) {
|
|
145
|
+
status = "FAIL_WITH_UNSUPPORTED";
|
|
146
|
+
} else if (hasBlockingFindings) {
|
|
147
|
+
status = "FAIL";
|
|
148
|
+
} else if (activeFindings.length > 0 && unsupported.length > 0) {
|
|
149
|
+
status = "WARN_WITH_UNSUPPORTED";
|
|
150
|
+
} else if (activeFindings.length > 0) {
|
|
151
|
+
status = "WARN";
|
|
152
|
+
} else if (unsupported.length > 0) {
|
|
153
|
+
status = "INCOMPLETE";
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const durationMs = Number((performance.now() - startedAt).toFixed(2));
|
|
157
|
+
|
|
158
|
+
return {
|
|
159
|
+
tool: TOOL_NAME,
|
|
160
|
+
version: TOOL_VERSION,
|
|
161
|
+
scannedPath: absTarget,
|
|
162
|
+
rootDir,
|
|
163
|
+
status,
|
|
164
|
+
durationMs,
|
|
165
|
+
summary: summarizeFindings(activeFindings),
|
|
166
|
+
suppressedCount,
|
|
167
|
+
baselinedCount,
|
|
168
|
+
parseStats: {
|
|
169
|
+
...parseStats,
|
|
170
|
+
parseRate,
|
|
171
|
+
},
|
|
172
|
+
coverage: {
|
|
173
|
+
sqlDiscoveryMode: sqlDiscovery.mode,
|
|
174
|
+
sqlFilesScanned: activeSqlFiles.length,
|
|
175
|
+
repoFilesScanned: repoFiles.length,
|
|
176
|
+
tablesTracked: state.tables.size,
|
|
177
|
+
policiesTracked: state.policies.size,
|
|
178
|
+
functionsTracked: state.functions.size,
|
|
179
|
+
viewsTracked: state.views.size,
|
|
180
|
+
bucketsTracked: state.buckets.size,
|
|
181
|
+
hasSupabaseConfigToml: configToml.found,
|
|
182
|
+
},
|
|
183
|
+
unsupported,
|
|
184
|
+
findings: activeFindings,
|
|
185
|
+
};
|
|
186
|
+
}
|