Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/approval/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from "./queue.js";
export * from "./chatops.js";
export * from "./replay-guard.js";
215 changes: 215 additions & 0 deletions src/approval/replay-guard.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
/**
* Replay-Proof Cryptographic Approval Token Manager (SEC-08)
*
* Binds every ChatOps 1-click Slack / MS Teams approval token to:
* HMAC-SHA256(secret, normalized_sql_ast + "|" + db_id + "|" + expires_at + "|" + single_use_nonce)
* Enforces short TTL (default 10 minutes / 600s), timing-safe HMAC verification,
* SQL AST immutability, and strict single-use nonce consumption (`403 Token Already Consumed`).
*/

import crypto from "node:crypto";

export interface IssuedApprovalToken {
requestId: string;
dbId: string;
normalizedSqlHash: string;
expiresAt: number;
nonce: string;
signature: string;
token: string;
}

export interface ApprovalTokenVerification {
valid: boolean;
statusCode: 200 | 401 | 403;
error?: string;
}

export function normalizeSqlForAstHash(sql: string): string {
// Single-pass O(n) SQL comment stripper & whitespace normalizer (immune to ReDoS)
const out: string[] = [];
let inBlockComment = false;
let inLineComment = false;
let lastWasSpace = true;

for (let i = 0; i < sql.length; i++) {
const ch = sql[i];
const next = i + 1 < sql.length ? sql[i + 1] : "";

if (inBlockComment) {
if (ch === "*" && next === "/") {
inBlockComment = false;
i++;
}
continue;
}

if (inLineComment) {
if (ch === "\n" || ch === "\r") {
inLineComment = false;
if (!lastWasSpace) {
out.push(" ");
lastWasSpace = true;
}
}
continue;
}

if (ch === "/" && next === "*") {
inBlockComment = true;
if (!lastWasSpace) {
out.push(" ");
lastWasSpace = true;
}
i++;
continue;
}

if (ch === "-" && next === "-") {
inLineComment = true;
if (!lastWasSpace) {
out.push(" ");
lastWasSpace = true;
}
i++;
continue;
}

if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "\f") {
if (!lastWasSpace) {
out.push(" ");
lastWasSpace = true;
}
continue;
}

out.push(ch.toLowerCase());
lastWasSpace = false;
}

return out.join("").trim();
}

export class ReplayProofApprovalTokenManager {
private readonly secret: string;
private readonly defaultTtlSeconds: number;
private readonly consumedNonces = new Set<string>();

constructor(
secret: string = process.env.DBSHIELD_CHATOPS_SECRET || "dbshield-chatops-replay-secret",
defaultTtlSeconds = 600, // 10 minutes
) {
this.secret = secret;
this.defaultTtlSeconds = defaultTtlSeconds;
}

private computeSignature(
requestId: string,
normalizedSqlHash: string,
dbId: string,
expiresAt: number,
nonce: string,
): string {
const canonical = `${requestId}|${normalizedSqlHash}|${dbId}|${expiresAt}|${nonce}`;
return crypto.createHmac("sha256", this.secret).update(canonical).digest("hex");
}

public issueToken(options: {
requestId: string;
sql: string;
dbId: string;
ttlSeconds?: number;
}): IssuedApprovalToken {
const normalizedSql = normalizeSqlForAstHash(options.sql);
const normalizedSqlHash = crypto.createHash("sha256").update(normalizedSql).digest("hex");
const ttl = options.ttlSeconds ?? this.defaultTtlSeconds;
const expiresAt = Math.floor(Date.now() / 1000) + ttl;
const nonce = crypto.randomBytes(16).toString("hex");
const signature = this.computeSignature(
options.requestId,
normalizedSqlHash,
options.dbId,
expiresAt,
nonce,
);
const token = Buffer.from(
JSON.stringify({
requestId: options.requestId,
dbId: options.dbId,
normalizedSqlHash,
expiresAt,
nonce,
signature,
}),
"utf8",
).toString("base64url");

return {
requestId: options.requestId,
dbId: options.dbId,
normalizedSqlHash,
expiresAt,
nonce,
signature,
token,
};
}

public verifyAndConsume(
token: string,
expected: { requestId: string; sql: string; dbId: string },
): ApprovalTokenVerification {
let decoded: IssuedApprovalToken;
try {
decoded = JSON.parse(Buffer.from(token, "base64url").toString("utf8")) as IssuedApprovalToken;
} catch {
return { valid: false, statusCode: 401, error: "Malformed approval token" };
}

if (!decoded.nonce || !decoded.signature || !decoded.expiresAt) {
return { valid: false, statusCode: 401, error: "Incomplete approval token payload" };
}

if (this.consumedNonces.has(decoded.nonce)) {
return { valid: false, statusCode: 403, error: "403 Token Already Consumed" };
}

const nowSec = Math.floor(Date.now() / 1000);
if (nowSec > decoded.expiresAt) {
return { valid: false, statusCode: 403, error: "403 Approval Token Expired" };
}

if (decoded.requestId !== expected.requestId || decoded.dbId !== expected.dbId) {
return { valid: false, statusCode: 403, error: "403 Approval Token Scope Mismatch" };
}

const expectedSqlHash = crypto
.createHash("sha256")
.update(normalizeSqlForAstHash(expected.sql))
.digest("hex");
if (decoded.normalizedSqlHash !== expectedSqlHash) {
return {
valid: false,
statusCode: 403,
error: "403 SQL AST Hash Mismatch — query tampered after dry-run",
};
}

const expectedSig = this.computeSignature(
decoded.requestId,
decoded.normalizedSqlHash,
decoded.dbId,
decoded.expiresAt,
decoded.nonce,
);

const a = Buffer.from(decoded.signature, "utf8");
const b = Buffer.from(expectedSig, "utf8");
if (a.length !== b.length || !crypto.timingSafeEqual(a, b)) {
return { valid: false, statusCode: 401, error: "Invalid HMAC-SHA256 approval signature" };
}

this.consumedNonces.add(decoded.nonce);
return { valid: true, statusCode: 200 };
}
}
104 changes: 104 additions & 0 deletions src/proxy/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,110 @@ export function parseFrontendFrame(
};
}

export interface ParsedParseMessage {
statementName: string;
query: string;
}

export interface ParsedBindMessage {
portalName: string;
statementName: string;
parameters: Array<string | null>;
}

export interface ParsedExecuteMessage {
portalName: string;
maxRows: number;
}

/**
* Decodes a PostgreSQL Extended Query Parse ('P') frame payload into statementName + query.
*/
export function parseParseMessage(payload: Buffer): ParsedParseMessage | null {
const stmtEnd = payload.indexOf(0);
if (stmtEnd === -1) return null;
const statementName = payload.toString("utf8", 0, stmtEnd);
const queryStart = stmtEnd + 1;
const queryEnd = payload.indexOf(0, queryStart);
if (queryEnd === -1) return null;
const query = payload.toString("utf8", queryStart, queryEnd);
return { statementName, query };
}

/**
* Decodes a PostgreSQL Extended Query Bind ('B') frame payload into portalName, statementName,
* and bound parameter string values (supporting NULL parameters with length -1).
*/
export function parseBindMessage(payload: Buffer): ParsedBindMessage | null {
const portalEnd = payload.indexOf(0);
if (portalEnd === -1) return null;
const portalName = payload.toString("utf8", 0, portalEnd);

const stmtStart = portalEnd + 1;
const stmtEnd = payload.indexOf(0, stmtStart);
if (stmtEnd === -1) return null;
const statementName = payload.toString("utf8", stmtStart, stmtEnd);

let offset = stmtEnd + 1;
if (offset + 2 > payload.length) {
return { portalName, statementName, parameters: [] };
}
const formatCount = payload.readInt16BE(offset);
offset += 2 + Math.max(0, formatCount) * 2;

if (offset + 2 > payload.length) {
return { portalName, statementName, parameters: [] };
}
const paramCount = payload.readInt16BE(offset);
offset += 2;

const parameters: Array<string | null> = [];
for (let i = 0; i < paramCount; i++) {
if (offset + 4 > payload.length) break;
const paramLen = payload.readInt32BE(offset);
offset += 4;
if (paramLen === -1) {
parameters.push(null);
} else if (paramLen >= 0 && offset + paramLen <= payload.length) {
parameters.push(payload.toString("utf8", offset, offset + paramLen));
offset += paramLen;
} else {
break;
}
}

return { portalName, statementName, parameters };
}

/**
* Decodes a PostgreSQL Extended Query Execute ('E') frame payload into portalName + maxRows.
*/
export function parseExecuteMessage(payload: Buffer): ParsedExecuteMessage | null {
const portalEnd = payload.indexOf(0);
if (portalEnd === -1) return null;
const portalName = payload.toString("utf8", 0, portalEnd);
const maxRows = portalEnd + 5 <= payload.length ? payload.readInt32BE(portalEnd + 1) : 0;
return { portalName, maxRows };
}

/**
* Reconstructs parameterized PostgreSQL SQL ($1, $2, ...) with bound values for AST guardrail inspection.
*/
export function reconstructParameterizedSql(
templateSql: string,
params: Array<string | null>,
): string {
if (!params || params.length === 0) return templateSql;
return templateSql.replace(/\$(\d+)\b/g, (full, idxStr) => {
const idx = Number.parseInt(idxStr, 10) - 1;
if (idx < 0 || idx >= params.length) return full;
const val = params[idx];
if (val === null) return "NULL";
if (/^-?\d+(?:\.\d+)?$/.test(val)) return val;
return `'${val.replace(/'/g, "''")}'`;
});
}

/**
* Extract SQL query string from a Query ('Q') or Parse ('P') packet payload.
*/
Expand Down
Loading
Loading