-
Notifications
You must be signed in to change notification settings - Fork 139
feat(flows): detect direct environment variable reads #1603
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
Draft
Draft
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,122 @@ | ||
| import { describe, expect, it } from "bun:test"; | ||
| import ts from "typescript"; | ||
|
|
||
| import { readEnvVarsFrom } from "./envReads.js"; | ||
|
|
||
| function reads(source: string): { names: string[]; dynamic: boolean } { | ||
| const file = ts.createSourceFile( | ||
| "a.flow.ts", | ||
| source, | ||
| ts.ScriptTarget.Latest, | ||
| true, | ||
| ); | ||
| const names = new Set<string>(); | ||
| let dynamic = false; | ||
| const visit = (node: ts.Node): void => { | ||
| const result = readEnvVarsFrom(ts, node); | ||
| for (const name of result.names) names.add(name); | ||
| dynamic ||= result.dynamic; | ||
| ts.forEachChild(node, visit); | ||
| }; | ||
| visit(file); | ||
| return { names: [...names].sort(), dynamic }; | ||
| } | ||
|
|
||
| describe("environment read syntax", () => { | ||
| it("reads property, bracket, template, and destructured names", () => { | ||
| expect( | ||
| reads( | ||
| 'process.env.DIRECT; process.env["BRACKET"]; process.env[`TEMPLATE`]; const { BOUND: value } = process.env;', | ||
| ), | ||
| ).toEqual({ | ||
| names: ["BOUND", "BRACKET", "DIRECT", "TEMPLATE"], | ||
| dynamic: false, | ||
| }); | ||
| }); | ||
|
|
||
| it("excludes write-only assignments and deletes while retaining compound reads", () => { | ||
| expect( | ||
| reads(`export default () => { | ||
| process.env.WRITTEN = "generated"; | ||
| process.env["BRACKET_WRITTEN"] = "generated"; | ||
| delete process.env.DELETED; | ||
| delete process.env["BRACKET_DELETED"]; | ||
| process.env.UPDATED += "suffix"; | ||
| process.env.FALLBACK ??= "fallback"; | ||
| process.env.COPIED = process.env.READ; | ||
| ({ token: process.env.DESTRUCTURED } = { token: "generated" }); | ||
| [process.env.ARRAY_WRITTEN] = ["generated"]; | ||
| };`), | ||
| ).toEqual({ | ||
| names: ["FALLBACK", "READ", "UPDATED"], | ||
| dynamic: false, | ||
| }); | ||
| }); | ||
|
|
||
| it("excludes loop write targets while retaining iterable reads", () => { | ||
| expect( | ||
| reads(`for (process.env.TARGET of [process.env.VALUE]) {} | ||
| for (process.env["KEY"] in { [process.env.SOURCE]: true }) {} | ||
| for ({ key: process.env.OBJECT } of rows) {} | ||
| for ([process.env.ARRAY] of rows) {}`), | ||
| ).toEqual({ names: ["SOURCE", "VALUE"], dynamic: false }); | ||
| }); | ||
|
|
||
| it("accepts static names containing template markers", () => { | ||
| expect( | ||
| reads('process.env["TOKEN${SUFFIX}"]; process.env[`LITERAL\\${KEY}`];'), | ||
| ).toEqual({ names: ["LITERAL${KEY}", "TOKEN${SUFFIX}"], dynamic: false }); | ||
| }); | ||
|
|
||
| it.each([ | ||
| "const env = process.env; env.TOKEN;", | ||
| "use(process.env);", | ||
| "({ ...process.env });", | ||
| "Object.keys(process.env);", | ||
| ])("flags an unhandled environment object read: %s", (source) => { | ||
| expect(reads(source)).toEqual({ names: [], dynamic: true }); | ||
| }); | ||
|
|
||
| it("excludes writes to the environment object", () => { | ||
| expect( | ||
| reads(`process.env = {}; delete process.env; | ||
| for (process.env of objects) {}`), | ||
| ).toEqual({ names: [], dynamic: false }); | ||
| }); | ||
|
|
||
| it("reads quoted and computed literal destructuring keys", () => { | ||
| expect( | ||
| reads(`const { "TOKEN": token, ["USER"]: user } = process.env;`), | ||
| ).toEqual({ | ||
| names: ["TOKEN", "USER"], | ||
| dynamic: false, | ||
| }); | ||
| }); | ||
|
|
||
| it.each([ | ||
| `const { [key]: value } = process.env;`, | ||
| `process.env[key];`, | ||
| "process.env[`${key}_EMAIL`];", | ||
| `const { ...rest } = process.env;`, | ||
| ])("flags a dynamic read: %s", (source) => { | ||
| expect(reads(source)).toEqual({ names: [], dynamic: true }); | ||
| }); | ||
|
|
||
| it("retains known names alongside uncertainty", () => { | ||
| expect(reads(`const { KNOWN, ...rest } = process.env;`)).toEqual({ | ||
| names: ["KNOWN"], | ||
| dynamic: true, | ||
| }); | ||
| }); | ||
|
|
||
| it("does not read a name out of a comment", () => { | ||
| expect( | ||
| reads( | ||
| `// process.env.COMMENT\n/** process.env.JSDOC */\nprocess.env.REAL;`, | ||
| ), | ||
| ).toEqual({ | ||
| names: ["REAL"], | ||
| dynamic: false, | ||
| }); | ||
| }); | ||
| }); |
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,104 @@ | ||
| import type ts from "typescript"; | ||
|
|
||
| import type { EnvReads } from "./types.js"; | ||
|
|
||
| function isProcessEnv(compiler: typeof ts, node: ts.Node): boolean { | ||
| return ( | ||
| compiler.isPropertyAccessExpression(node) && | ||
| node.name.text === "env" && | ||
| compiler.isIdentifier(node.expression) && | ||
| node.expression.text === "process" | ||
| ); | ||
| } | ||
|
|
||
| function isReadAccess(compiler: typeof ts, node: ts.Node): boolean { | ||
| let target = node; | ||
| while ( | ||
| compiler.isParenthesizedExpression(target.parent) || | ||
| compiler.isAsExpression(target.parent) || | ||
| compiler.isNonNullExpression(target.parent) || | ||
| (compiler.isPropertyAssignment(target.parent) && | ||
| target.parent.initializer === target) || | ||
| compiler.isObjectLiteralExpression(target.parent) || | ||
| compiler.isArrayLiteralExpression(target.parent) || | ||
| compiler.isSpreadAssignment(target.parent) || | ||
| compiler.isSpreadElement(target.parent) | ||
| ) { | ||
| target = target.parent; | ||
| } | ||
| const parent = target.parent; | ||
| return ( | ||
| !compiler.isDeleteExpression(parent) && | ||
| !( | ||
| compiler.isBinaryExpression(parent) && | ||
| parent.left === target && | ||
| parent.operatorToken.kind === compiler.SyntaxKind.EqualsToken | ||
| ) && | ||
| !( | ||
| (compiler.isForInStatement(parent) || | ||
| compiler.isForOfStatement(parent)) && | ||
| parent.initializer === target | ||
| ) | ||
| ); | ||
| } | ||
|
|
||
| /** Reads on one visited syntax node; execution scope is controlled by the caller. */ | ||
| export function readEnvVarsFrom(compiler: typeof ts, node: ts.Node): EnvReads { | ||
| const names = new Set<string>(); | ||
| let dynamic = false; | ||
| if ( | ||
| compiler.isPropertyAccessExpression(node) && | ||
| isProcessEnv(compiler, node.expression) && | ||
| isReadAccess(compiler, node) | ||
| ) { | ||
| names.add(node.name.text); | ||
| } | ||
| if ( | ||
| compiler.isElementAccessExpression(node) && | ||
| isProcessEnv(compiler, node.expression) && | ||
| isReadAccess(compiler, node) | ||
| ) { | ||
| const argument = node.argumentExpression; | ||
| if (compiler.isStringLiteralLike(argument)) { | ||
| names.add(argument.text); | ||
| } else { | ||
| dynamic = true; | ||
| } | ||
| } | ||
| if ( | ||
| compiler.isVariableDeclaration(node) && | ||
| node.initializer !== undefined && | ||
| isProcessEnv(compiler, node.initializer) && | ||
| compiler.isObjectBindingPattern(node.name) | ||
| ) { | ||
| for (const element of node.name.elements) { | ||
| if (element.dotDotDotToken !== undefined) { | ||
| dynamic = true; | ||
| continue; | ||
| } | ||
| const key = element.propertyName ?? element.name; | ||
| if (compiler.isIdentifier(key) || compiler.isStringLiteralLike(key)) { | ||
| names.add(key.text); | ||
| } else if ( | ||
| compiler.isComputedPropertyName(key) && | ||
| compiler.isStringLiteralLike(key.expression) | ||
| ) { | ||
| names.add(key.expression.text); | ||
| } else { | ||
| dynamic = true; | ||
| } | ||
| } | ||
| } | ||
| if (isProcessEnv(compiler, node) && isReadAccess(compiler, node)) { | ||
| const parent = node.parent; | ||
| const handled = | ||
| ((compiler.isPropertyAccessExpression(parent) || | ||
| compiler.isElementAccessExpression(parent)) && | ||
| parent.expression === node) || | ||
| (compiler.isVariableDeclaration(parent) && | ||
| parent.initializer === node && | ||
| compiler.isObjectBindingPattern(parent.name)); | ||
| if (!handled) dynamic = true; | ||
| } | ||
| return { names, dynamic }; | ||
| } | ||
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,5 @@ | ||
| /** Known reads and uncertainty for an executable unit. */ | ||
| export type EnvReads = { | ||
| names: Set<string>; | ||
| dynamic: boolean; | ||
| }; |
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
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
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.