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
67 changes: 64 additions & 3 deletions src/approval/chatops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,16 @@ export class ChatOpsNotifier {
action_id: "dbshield_reject",
value: req.id,
},
{
type: "button",
text: {
type: "plain_text",
text: "Inspect Dry-Run Diff 🔍",
emoji: true,
},
action_id: "dbshield_view_diff",
value: req.id,
},
],
});
}
Expand Down Expand Up @@ -205,24 +215,75 @@ export class ChatOpsNotifier {
};

if (isPending && this.config.callbackBaseUrl) {
const base = this.config.callbackBaseUrl.replace(/\/$/, "");
const approveUrl = this.generateSignedActionUrl(req.id, "approve");
const rejectUrl = this.generateSignedActionUrl(req.id, "reject");
const diffUrl = this.generateSignedActionUrl(req.id, "diff");

card.attachments[0].content.actions = [
{
type: "Action.OpenUrl",
title: "Approve ✅",
url: `${base}/api/approvals/${req.id}/approve`,
url: approveUrl,
},
{
type: "Action.OpenUrl",
title: "Reject ❌",
url: `${base}/api/approvals/${req.id}/reject`,
url: rejectUrl,
},
{
type: "Action.OpenUrl",
title: "Inspect Diff 🔍",
url: diffUrl,
},
];
}

return card;
}

/**
* Generates an HMAC-SHA256 signed action URL for 1-click approvals with timestamp expiration.
*/
public generateSignedActionUrl(
requestId: string,
action: string,
expiresInSeconds = 86400,
): string {
const base = (this.config.callbackBaseUrl || "http://localhost:3000").replace(/\/$/, "");
const expires = Math.floor(Date.now() / 1000) + expiresInSeconds;
const secret = this.config.slackSigningSecret || "dbshield-chatops-secret";
const sig = crypto
.createHmac("sha256", secret)
.update(`${requestId}:${action}:${expires}`)
.digest("hex");
return `${base}/api/approvals/${requestId}/${action}?expires=${expires}&signature=${sig}`;
}

/**
* Verifies an HMAC-SHA256 signed action link.
*/
public verifySignedAction(
requestId: string,
action: string,
expiresStr: string,
signature: string,
): boolean {
const expires = Number.parseInt(expiresStr, 10);
if (Number.isNaN(expires) || Math.floor(Date.now() / 1000) > expires) {
return false; // Expired
}
const secret = this.config.slackSigningSecret || "dbshield-chatops-secret";
const expectedSig = crypto
.createHmac("sha256", secret)
.update(`${requestId}:${action}:${expires}`)
.digest("hex");

const bufA = Buffer.from(signature, "utf8");
const bufB = Buffer.from(expectedSig, "utf8");
if (bufA.length !== bufB.length) return false;
return crypto.timingSafeEqual(bufA, bufB);
}

/**
* Verifies Slack request signature using SLACK_SIGNING_SECRET.
*/
Expand Down
133 changes: 133 additions & 0 deletions src/proxy/wire-masker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,137 @@ export class ProtocolWireMasker {
public maskRows(rows: Record<string, unknown>[]): Record<string, unknown>[] {
return rows.map((r) => this.maskRow(r));
}

/**
* Masks a raw PostgreSQL 'D' (DataRow) wire protocol buffer directly.
* Format: 'D' (1B) + Length (4B BE) + Column Count (2B BE) + [ColLen (4B BE) + ColData (NB)]*
*/
public maskPostgresDataRow(buf: Buffer, columnNames: string[] = []): Buffer {
if (buf.length < 7 || buf[0] !== 0x44) {
return buf;
}

const colCount = buf.readInt16BE(5);
const newColBuffers: Buffer[] = [];
let offset = 7;

for (let i = 0; i < colCount && offset < buf.length; i++) {
const colLen = buf.readInt32BE(offset);
offset += 4;

if (colLen === -1) {
// NULL column
const nullBuf = Buffer.alloc(4);
nullBuf.writeInt32BE(-1, 0);
newColBuffers.push(nullBuf);
} else {
const rawVal = buf.subarray(offset, offset + colLen).toString("utf8");
offset += colLen;

const colName = (columnNames[i] || `col_${i}`).toLowerCase();
let valToEncode = rawVal;

if (this.maskedColumns.has(colName)) {
valToEncode = this.maskValue(rawVal, colName);
}

const valBuf = Buffer.from(valToEncode, "utf8");
const lenBuf = Buffer.alloc(4);
lenBuf.writeInt32BE(valBuf.length, 0);
newColBuffers.push(Buffer.concat([lenBuf, valBuf]));
}
}

const dataPayload = Buffer.concat(newColBuffers);
const totalLen = 4 + 2 + dataPayload.length;
const header = Buffer.alloc(7);
header[0] = 0x44; // 'D'
header.writeInt32BE(totalLen, 1);
header.writeInt16BE(colCount, 5);

return Buffer.concat([header, dataPayload]);
}

/**
* Masks a raw MySQL text resultset row packet buffer.
* Format: 3B Payload Length (LE) + 1B Sequence ID + Length-Encoded Strings
*/
public maskMysqlRowPacket(buf: Buffer, columnNames: string[] = []): Buffer {
if (buf.length < 5) return buf;

const seqId = buf[3];
let offset = 4;
const maskedColParts: Buffer[] = [];
let colIndex = 0;

while (offset < buf.length) {
const firstByte = buf[offset++];
if (firstByte === 0xfb) {
// NULL field in MySQL
maskedColParts.push(Buffer.from([0xfb]));
colIndex++;
continue;
}

let strLen = 0;
if (firstByte < 0xfb) {
strLen = firstByte;
} else if (firstByte === 0xfc) {
strLen = buf.readUInt16LE(offset);
offset += 2;
} else if (firstByte === 0xfd) {
strLen = buf[offset] | (buf[offset + 1] << 8) | (buf[offset + 2] << 16);
offset += 3;
}

const rawVal = buf.subarray(offset, offset + strLen).toString("utf8");
offset += strLen;

const colName = (columnNames[colIndex] || `col_${colIndex}`).toLowerCase();
let finalVal = rawVal;

if (this.maskedColumns.has(colName)) {
finalVal = this.maskValue(rawVal, colName);
}

const strBuf = Buffer.from(finalVal, "utf8");
// Encode length-encoded string
let lenHeader: Buffer;
if (strBuf.length < 251) {
lenHeader = Buffer.from([strBuf.length]);
} else if (strBuf.length <= 0xffff) {
lenHeader = Buffer.alloc(3);
lenHeader[0] = 0xfc;
lenHeader.writeUInt16LE(strBuf.length, 1);
} else {
lenHeader = Buffer.alloc(4);
lenHeader[0] = 0xfd;
lenHeader[1] = strBuf.length & 0xff;
lenHeader[2] = (strBuf.length >> 8) & 0xff;
lenHeader[3] = (strBuf.length >> 16) & 0xff;
}

maskedColParts.push(Buffer.concat([lenHeader, strBuf]));
colIndex++;
}

const payload = Buffer.concat(maskedColParts);
const packetHeader = Buffer.alloc(4);
packetHeader[0] = payload.length & 0xff;
packetHeader[1] = (payload.length >> 8) & 0xff;
packetHeader[2] = (payload.length >> 16) & 0xff;
packetHeader[3] = seqId;

return Buffer.concat([packetHeader, payload]);
}

/**
* Transparently masks streaming chunks based on protocol frame identification.
*/
public maskStreamingChunk(chunk: Buffer, columnNames: string[] = []): Buffer {
if (chunk.length >= 7 && chunk[0] === 0x44) {
return this.maskPostgresDataRow(chunk, columnNames);
}
return chunk;
}
}
Loading
Loading