-
Notifications
You must be signed in to change notification settings - Fork 6
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
Log warning if used with ESM #526
Open
timokoessler
wants to merge
4
commits into
main
Choose a base branch
from
add-esm-warning
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
4 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 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,71 @@ | ||
const t = require("tap"); | ||
const { spawn } = require("child_process"); | ||
const { resolve, join } = require("path"); | ||
const timeout = require("../timeout"); | ||
|
||
const appDir = resolve(__dirname, "../../sample-apps/hono-sqlite3-esm"); | ||
const pathToApp = join(appDir, "app.js"); | ||
|
||
t.test("it logs esm warnings", (t) => { | ||
const server = spawn(`node`, [pathToApp, "4004"], { | ||
env: { ...process.env, AIKIDO_DEBUG: "true", AIKIDO_BLOCKING: "true" }, | ||
cwd: appDir, | ||
}); | ||
|
||
server.on("close", () => { | ||
t.end(); | ||
}); | ||
|
||
server.on("error", (err) => { | ||
t.fail(err.message); | ||
}); | ||
|
||
let stdout = ""; | ||
server.stdout.on("data", (data) => { | ||
stdout += data.toString(); | ||
}); | ||
|
||
let stderr = ""; | ||
server.stderr.on("data", (data) => { | ||
stderr += data.toString(); | ||
}); | ||
|
||
// Wait for the server to start | ||
timeout(2000) | ||
.then(() => { | ||
return Promise.all([ | ||
fetch("http://127.0.0.1:4004/add", { | ||
method: "POST", | ||
body: JSON.stringify({ name: "Test'), ('Test2');--" }), | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
signal: AbortSignal.timeout(5000), | ||
}), | ||
fetch("http://127.0.0.1:4004/add", { | ||
method: "POST", | ||
body: JSON.stringify({ name: "Miau" }), | ||
headers: { | ||
"Content-Type": "application/json", | ||
}, | ||
signal: AbortSignal.timeout(5000), | ||
}), | ||
]); | ||
}) | ||
.then(([sqlInjection, normalAdd]) => { | ||
t.equal(sqlInjection.status, 200); // Not blocked | ||
t.equal(normalAdd.status, 200); | ||
t.match( | ||
stderr, | ||
/Your application seems to be running in ESM mode\. Zen does not support ESM at runtime yet\./ | ||
); | ||
t.match(stdout, /Starting agent/); | ||
t.notMatch(stderr, /Zen has blocked an SQL injection/); // Not supported | ||
}) | ||
.catch((error) => { | ||
t.fail(error.message); | ||
}) | ||
.finally(() => { | ||
server.kill(); | ||
}); | ||
}); |
This file contains 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 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,17 @@ | ||
/** | ||
* Checks at runtime if the Node.js application is using ESM. | ||
* As it depends on the stack trace, it should be used directly after the file got imported / at top level of the library. | ||
*/ | ||
export function isESM() { | ||
// Save current stack trace limit and increase it a bit, to make sure we don't get too few frames | ||
const currentStackTraceLimit = Error.stackTraceLimit; | ||
Error.stackTraceLimit = 15; | ||
|
||
// Capture the current stack trace | ||
const stack = new Error().stack || ""; | ||
|
||
// Reset stack trace limit | ||
Error.stackTraceLimit = currentStackTraceLimit; | ||
|
||
return stack.includes("node:internal/modules/esm/loader:"); | ||
} |
This file contains 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 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,31 @@ | ||
import { promisify } from "util"; | ||
|
||
export class Cats { | ||
/** | ||
* | ||
* @param {import("sqlite3").Database} db | ||
*/ | ||
constructor(db) { | ||
this.db = db; | ||
this.all = promisify(this.db.all).bind(this.db); | ||
} | ||
|
||
async add(name) { | ||
const result = await this.all( | ||
`INSERT INTO cats(petname) VALUES ('${name}');` | ||
); | ||
return result; | ||
} | ||
|
||
async byName(name) { | ||
const cats = await this.all( | ||
`SELECT petname FROM cats WHERE petname = '${name}';` | ||
); | ||
return cats.map((row) => row.petname); | ||
} | ||
|
||
async getAll() { | ||
const cats = await this.all("SELECT petname FROM cats;"); | ||
return cats.map((row) => row.petname); | ||
} | ||
} |
This file contains 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,110 @@ | ||
import { Hono } from "hono"; | ||
import { serve } from "@hono/node-server"; | ||
import { getDB } from "./db.js"; | ||
import * as Aikido from "@aikidosec/firewall"; | ||
import { Cats } from "./Cats.js"; | ||
|
||
const app = new Hono(); | ||
|
||
app.use(async (c, next) => { | ||
Aikido.setUser({ | ||
id: "id", | ||
name: "Name", | ||
}); | ||
|
||
await next(); | ||
}); | ||
|
||
const db = await getDB(); | ||
const cats = new Cats(db); | ||
|
||
app.get("/", async (c) => { | ||
const catNames = await cats.getAll(); | ||
return c.html( | ||
` | ||
<html lang="en"> | ||
<body> | ||
<h1>Vulnerable app using SQLite3</h1> | ||
<ul id="list"> | ||
${catNames.map((name) => `<li>${name}</li>`).join("")} | ||
</ul> | ||
<form id="add-cat"> | ||
<label for="search">Add a new cat</label> | ||
<input type="text" name="petname"> | ||
<input type="submit" value="Add" /> | ||
</form> | ||
<p>SQL Injection: Test'), ('Test2');--</p> | ||
<a href="/clear">Clear all cats</a> | ||
<script> | ||
document.addEventListener("DOMContentLoaded", () => { | ||
const form = document.getElementById("add-cat"); | ||
form.addEventListener("submit", async (event) => { | ||
event.preventDefault(); | ||
fetch("/add", { | ||
method: "POST", | ||
body: JSON.stringify({ name: form.petname.value }), | ||
headers: { | ||
"Content-Type": "application/json" | ||
} | ||
}).then(response => response.json()) | ||
.then(data => { | ||
if(!data.success) { | ||
throw new Error("Response was not successful"); | ||
} | ||
window.location.reload(); | ||
}) | ||
.catch(error => document.getElementById("list").innerHTML = "<li>" + error.message + "</li>"); | ||
}); | ||
}); | ||
</script> | ||
</body> | ||
</html> | ||
` | ||
); | ||
}); | ||
|
||
app.post("/add", async (c) => { | ||
const body = await c.req.json(); | ||
|
||
if (typeof body.name !== "string") { | ||
return c.json({ error: "Invalid request" }, 400); | ||
} | ||
|
||
await cats.add(body.name); | ||
return c.json({ success: true }); | ||
}); | ||
|
||
app.get("/clear", async (c) => { | ||
try { | ||
await new Promise((resolve, reject) => { | ||
db.run("DELETE FROM cats;", (result, err) => { | ||
if (err) { | ||
return reject(err); | ||
} | ||
resolve(result); | ||
}); | ||
}); | ||
return c.redirect("/", 302); | ||
} catch (err) { | ||
return c.json({ error: "Failed to clear cats" }, 500); | ||
} | ||
}); | ||
|
||
function getPort() { | ||
const port = parseInt(process.argv[2], 10) || 4000; | ||
|
||
if (isNaN(port)) { | ||
console.error("Invalid port"); | ||
process.exit(1); | ||
} | ||
|
||
return port; | ||
} | ||
|
||
const port = getPort(); | ||
serve({ | ||
fetch: app.fetch, | ||
port: port, | ||
}).on("listening", () => { | ||
console.log(`Server is running on port ${port}`); | ||
}); |
This file contains 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,28 @@ | ||
import sqlite3 from "sqlite3"; | ||
|
||
/** @type {sqlite3.Database} */ | ||
let db; | ||
|
||
export async function getDB() { | ||
if (db) { | ||
return db; | ||
} | ||
|
||
db = new sqlite3.Database(":memory:"); | ||
|
||
await new Promise((resolve, reject) => { | ||
db.run( | ||
`CREATE TABLE cats ( | ||
petname TEXT | ||
);`, | ||
(err) => { | ||
if (err) { | ||
return reject(err); | ||
} | ||
resolve(); | ||
} | ||
); | ||
}); | ||
|
||
return db; | ||
} |
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.
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.
why don't we return then?
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.
It just feels safer in case there are false positive detections of the execution mode. One possibility I can think of but that's really rare is a ESM module loaded in a CJS project using something like TypeScript Execute (tsx) that also wraps require before we do.