-
Notifications
You must be signed in to change notification settings - Fork 68
feat: allow to scan secrets without buffering whole lines #6318
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
pieh
wants to merge
5
commits into
main
Choose a base branch
from
mem/smaller-chunks-to-scan
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
e5e3158
test: replace snapshots with explicit assertions for secrets scanning
pieh fc32c24
test: add failing OOM case to secret scanning
pieh 4431cb7
feat: allow to scan secrets without buffering whole lines
pieh b23b77a
Merge branch 'main' into mem/smaller-chunks-to-scan
pieh 100a8d9
Merge branch 'main' into mem/smaller-chunks-to-scan
pieh File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,6 +17,7 @@ interface ScanArgs { | |
keys: string[] | ||
base: string | ||
filePaths: string[] | ||
useReadLine: boolean | ||
} | ||
|
||
interface MatchResult { | ||
|
@@ -215,7 +216,13 @@ const omitPathMatches = (relativePath, omitPaths) => { | |
* @param scanArgs {ScanArgs} scan options | ||
* @returns promise with all of the scan results, if any | ||
*/ | ||
export async function scanFilesForKeyValues({ env, keys, filePaths, base }: ScanArgs): Promise<ScanResults> { | ||
export async function scanFilesForKeyValues({ | ||
env, | ||
keys, | ||
filePaths, | ||
base, | ||
useReadLine, | ||
}: ScanArgs): Promise<ScanResults> { | ||
const scanResults: ScanResults = { | ||
matches: [], | ||
scannedFilesCount: 0, | ||
|
@@ -245,6 +252,8 @@ export async function scanFilesForKeyValues({ env, keys, filePaths, base }: Scan | |
|
||
let settledPromises: PromiseSettledResult<MatchResult[]>[] = [] | ||
|
||
const searchStream = useReadLine ? searchStreamReadline : searchStreamNoReadline | ||
|
||
// process the scanning in batches to not run into memory issues by | ||
// processing all files at the same time. | ||
while (filePaths.length > 0) { | ||
|
@@ -269,7 +278,14 @@ export async function scanFilesForKeyValues({ env, keys, filePaths, base }: Scan | |
return scanResults | ||
} | ||
|
||
const searchStream = (basePath: string, file: string, keyValues: Record<string, string[]>): Promise<MatchResult[]> => { | ||
/** | ||
* Search stream implementation using node:readline | ||
*/ | ||
const searchStreamReadline = ( | ||
basePath: string, | ||
file: string, | ||
keyValues: Record<string, string[]>, | ||
): Promise<MatchResult[]> => { | ||
return new Promise((resolve, reject) => { | ||
const filePath = path.resolve(basePath, file) | ||
|
||
|
@@ -391,6 +407,143 @@ const searchStream = (basePath: string, file: string, keyValues: Record<string, | |
}) | ||
} | ||
|
||
/** | ||
* Search stream implementation using just read stream that allows to buffer less content | ||
*/ | ||
const searchStreamNoReadline = ( | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. It would be very lovely to have |
||
basePath: string, | ||
file: string, | ||
keyValues: Record<string, string[]>, | ||
): Promise<MatchResult[]> => { | ||
return new Promise((resolve, reject) => { | ||
const filePath = path.resolve(basePath, file) | ||
|
||
const inStream = createReadStream(filePath) | ||
const matches: MatchResult[] = [] | ||
|
||
const keyVals: string[] = ([] as string[]).concat(...Object.values(keyValues)) | ||
|
||
const maxValLength = Math.max(0, ...keyVals.map((v) => v.length)) | ||
if (maxValLength === 0) { | ||
// no non-empty values to scan for | ||
return matches | ||
} | ||
|
||
const minValLength = Math.min(...keyVals.map((v) => v.length)) | ||
|
||
function getKeyForValue(val) { | ||
let key = '' | ||
for (const [secretKeyName, valuePermutations] of Object.entries(keyValues)) { | ||
if (valuePermutations.includes(val)) { | ||
key = secretKeyName | ||
} | ||
} | ||
return key | ||
} | ||
|
||
let buffer = '' | ||
|
||
function getCurrentBufferNewLineIndexes() { | ||
const newLinesIndexesInCurrentBuffer = [] as number[] | ||
let newLineIndex = -1 | ||
while ((newLineIndex = buffer.indexOf('\n', newLineIndex + 1)) !== -1) { | ||
newLinesIndexesInCurrentBuffer.push(newLineIndex) | ||
} | ||
|
||
return newLinesIndexesInCurrentBuffer | ||
} | ||
let fileIndex = 0 | ||
let processedLines = 0 | ||
const foundIndexes = new Map<string, Set<number>>() | ||
const foundLines = new Map<string, Set<number>>() | ||
inStream.on('data', function (chunk) { | ||
const newChunk = chunk.toString() | ||
|
||
buffer += newChunk | ||
|
||
let newLinesIndexesInCurrentBuffer = null as null | number[] | ||
|
||
if (buffer.length > minValLength) { | ||
for (const valVariant of keyVals) { | ||
let valVariantIndex = -1 | ||
while ((valVariantIndex = buffer.indexOf(valVariant, valVariantIndex + 1)) !== -1) { | ||
const pos = fileIndex + valVariantIndex | ||
let foundIndexesForValVariant = foundIndexes.get(valVariant) | ||
if (!foundIndexesForValVariant?.has(pos)) { | ||
if (newLinesIndexesInCurrentBuffer === null) { | ||
newLinesIndexesInCurrentBuffer = getCurrentBufferNewLineIndexes() | ||
} | ||
|
||
let lineNumber = processedLines + 1 | ||
for (const newLineIndex of newLinesIndexesInCurrentBuffer) { | ||
if (valVariantIndex > newLineIndex) { | ||
lineNumber++ | ||
} else { | ||
break | ||
} | ||
} | ||
|
||
let foundLinesForValVariant = foundLines.get(valVariant) | ||
if (!foundLinesForValVariant?.has(lineNumber)) { | ||
matches.push({ | ||
file, | ||
lineNumber, | ||
key: getKeyForValue(valVariant), | ||
}) | ||
|
||
if (!foundLinesForValVariant) { | ||
foundLinesForValVariant = new Set<number>() | ||
foundLines.set(valVariant, foundLinesForValVariant) | ||
} | ||
foundLinesForValVariant.add(lineNumber) | ||
} | ||
|
||
if (!foundIndexesForValVariant) { | ||
foundIndexesForValVariant = new Set<number>() | ||
foundIndexes.set(valVariant, foundIndexesForValVariant) | ||
} | ||
foundIndexesForValVariant.add(pos) | ||
} | ||
} | ||
} | ||
} | ||
|
||
if (buffer.length > maxValLength) { | ||
const lengthDiff = buffer.length - maxValLength | ||
fileIndex += lengthDiff | ||
if (newLinesIndexesInCurrentBuffer === null) { | ||
newLinesIndexesInCurrentBuffer = getCurrentBufferNewLineIndexes() | ||
} | ||
|
||
// advanced processed lines | ||
for (const newLineIndex of newLinesIndexesInCurrentBuffer) { | ||
if (newLineIndex < lengthDiff) { | ||
processedLines++ | ||
} else { | ||
break | ||
} | ||
} | ||
|
||
// Keep the last part of the buffer to handle split values across chunks | ||
buffer = buffer.slice(-maxValLength) | ||
} | ||
}) | ||
|
||
inStream.on('error', function (error: any) { | ||
if (error?.code === 'EISDIR') { | ||
// file path is a directory - do nothing | ||
resolve(matches) | ||
} else { | ||
reject(error) | ||
} | ||
}) | ||
|
||
inStream.on('close', function () { | ||
resolve(matches) | ||
}) | ||
}) | ||
} | ||
|
||
/** | ||
* ScanResults are all of the finds for all keys and their disparate locations. Scanning is | ||
* async in streams so order can change a lot. Some matches are the result of an env var explictly being marked as secret, | ||
|
38 changes: 38 additions & 0 deletions
38
packages/build/tests/secrets_scanning/fixtures/src_scanning_large_binary_file/generate.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import { randomBytes } from "node:crypto"; | ||
import { createWriteStream, mkdirSync } from "node:fs"; | ||
|
||
mkdirSync('dist', { recursive: true }); | ||
|
||
const writer = createWriteStream('dist/out.txt', { flags: "w" }); | ||
|
||
async function writeLotOfBytesWithoutNewLines() { | ||
const max_size = 128 * 1024 * 1024; // 128MB | ||
const chunk_size = 1024 * 1024; // 1MB | ||
|
||
let bytes_written = 0; | ||
while (bytes_written < max_size) { | ||
const bytes_to_write = Math.min(chunk_size, max_size - bytes_written); | ||
const buffer = randomBytes(bytes_to_write).map((byte) => | ||
// swap LF and CR to something else | ||
byte === 0x0d || byte === 0x0a ? 0x0b : byte | ||
); | ||
|
||
writer.write(buffer); | ||
bytes_written += bytes_to_write; | ||
} | ||
} | ||
|
||
await writeLotOfBytesWithoutNewLines() | ||
writer.write(process.env.ENV_SECRET) | ||
await writeLotOfBytesWithoutNewLines() | ||
|
||
await new Promise((resolve, reject) => { | ||
writer.close(err => { | ||
if (err) { | ||
reject(err); | ||
} else { | ||
resolve(); | ||
} | ||
}) | ||
}) | ||
|
3 changes: 3 additions & 0 deletions
3
packages/build/tests/secrets_scanning/fixtures/src_scanning_large_binary_file/netlify.toml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
[build] | ||
command = 'node generate.mjs' | ||
publish = "./dist" |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit - could we potentially rename this variable/flag so that we don't have a double negative on this line?