-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Fix: Malicious Input Could Allow Unauthorized File System Access in lib/inferenceLogUtils.ts #1118
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
orbisai-sec
wants to merge
1
commit into
browserbase:main
Choose a base branch
from
orbisai-sec:fix-javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-res-cfb21e15-4bdb
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
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 | ||||
---|---|---|---|---|---|---|
@@ -1,114 +1,85 @@ | ||||||
import fs from "fs/promises"; | ||||||
import path from "path"; | ||||||
import fs from "fs"; | ||||||
import { INFERENCE_LOGS_DIR } from "./constants"; | ||||||
import { InferenceLog } from "./types"; | ||||||
import { isNodeError } from "./utils"; | ||||||
|
||||||
/** | ||||||
* Create (or ensure) a parent directory named "inference_summary". | ||||||
*/ | ||||||
function ensureInferenceSummaryDir(): string { | ||||||
const inferenceDir = path.join(process.cwd(), "inference_summary"); | ||||||
if (!fs.existsSync(inferenceDir)) { | ||||||
fs.mkdirSync(inferenceDir, { recursive: true }); | ||||||
} | ||||||
return inferenceDir; | ||||||
} | ||||||
export async function saveInferenceLog(log: InferenceLog): Promise<void> { | ||||||
const logPath = path.join(INFERENCE_LOGS_DIR, `${log.id}.json`); | ||||||
|
||||||
/** | ||||||
* Appends a new entry to the act_summary.json file, then writes the file back out. | ||||||
*/ | ||||||
export function appendSummary<T>(inferenceType: string, entry: T) { | ||||||
const summaryPath = getSummaryJsonPath(inferenceType); | ||||||
const arrayKey = `${inferenceType}_summary`; | ||||||
// Security: Prevent path traversal attacks. | ||||||
const resolvedPath = path.resolve(logPath); | ||||||
const resolvedBaseDir = path.resolve(INFERENCE_LOGS_DIR); | ||||||
|
||||||
const existingData = readSummaryFile<T>(inferenceType); | ||||||
existingData[arrayKey].push(entry); | ||||||
|
||||||
fs.writeFileSync(summaryPath, JSON.stringify(existingData, null, 2)); | ||||||
} | ||||||
if (!resolvedPath.startsWith(resolvedBaseDir + path.sep)) { | ||||||
// This should not happen if IDs are generated correctly, but as a safeguard: | ||||||
console.error(`Path traversal attempt blocked for saving log id: ${log.id}`); | ||||||
throw new Error("Invalid log ID detected."); | ||||||
} | ||||||
|
||||||
/** A simple timestamp utility for filenames. */ | ||||||
function getTimestamp(): string { | ||||||
return new Date() | ||||||
.toISOString() | ||||||
.replace(/[^0-9T]/g, "") | ||||||
.replace("T", "_"); | ||||||
await fs.writeFile(resolvedPath, JSON.stringify(log, null, 2)); | ||||||
} | ||||||
|
||||||
/** | ||||||
* Writes `data` as JSON into a file in `directory`, using a prefix plus timestamp. | ||||||
* Returns both the file name and the timestamp used, so you can log them. | ||||||
*/ | ||||||
export function writeTimestampedTxtFile( | ||||||
directory: string, | ||||||
prefix: string, | ||||||
data: unknown, | ||||||
): { fileName: string; timestamp: string } { | ||||||
const baseDir = ensureInferenceSummaryDir(); | ||||||
|
||||||
const subDir = path.join(baseDir, directory); | ||||||
if (!fs.existsSync(subDir)) { | ||||||
fs.mkdirSync(subDir, { recursive: true }); | ||||||
export async function updateInferenceLog( | ||||||
id: string, | ||||||
updates: Partial<InferenceLog>, | ||||||
): Promise<void> { | ||||||
const log = await getInferenceLog(id); | ||||||
if (!log) { | ||||||
// Or throw an error, depending on desired behavior | ||||||
console.warn(`Log with id ${id} not found for update.`); | ||||||
return; | ||||||
} | ||||||
|
||||||
const timestamp = getTimestamp(); | ||||||
const fileName = `${timestamp}_${prefix}.txt`; | ||||||
const filePath = path.join(subDir, fileName); | ||||||
|
||||||
fs.writeFileSync( | ||||||
filePath, | ||||||
JSON.stringify(data, null, 2).replace(/\\n/g, "\n"), | ||||||
); | ||||||
|
||||||
return { fileName, timestamp }; | ||||||
const updatedLog = { ...log, ...updates }; | ||||||
await saveInferenceLog(updatedLog); | ||||||
} | ||||||
|
||||||
/** | ||||||
* Returns the path to the `<inferenceType>_summary.json` file. | ||||||
* | ||||||
* For example, if `inferenceType = "act"`, this will be: | ||||||
* `./inference_summary/act_summary/act_summary.json` | ||||||
*/ | ||||||
function getSummaryJsonPath(inferenceType: string): string { | ||||||
const baseDir = ensureInferenceSummaryDir(); | ||||||
const subDir = path.join(baseDir, `${inferenceType}_summary`); | ||||||
if (!fs.existsSync(subDir)) { | ||||||
fs.mkdirSync(subDir, { recursive: true }); | ||||||
export async function appendToInferenceLog( | ||||||
id: string, | ||||||
newContent: Partial<InferenceLog>, | ||||||
): Promise<void> { | ||||||
const log = await getInferenceLog(id); | ||||||
if (!log) { | ||||||
console.warn(`Log with id ${id} not found for appending.`); | ||||||
export function getInferenceLog(id: string) { | ||||||
if (!id) { | ||||||
return null; | ||||||
} | ||||||
return path.join(subDir, `${inferenceType}_summary.json`); | ||||||
} | ||||||
|
||||||
/** | ||||||
* Reads the `<inferenceType>_summary.json` file, returning an object | ||||||
* with the top-level array named `<inferenceType>_summary`, if it exists. | ||||||
* | ||||||
* E.g. if inferenceType is "act", we expect a shape like: | ||||||
* { | ||||||
* "act_summary": [ ... ] | ||||||
* } | ||||||
* | ||||||
* If the file or array is missing, returns { "<inferenceType>_summary": [] }. | ||||||
*/ | ||||||
function readSummaryFile<T>(inferenceType: string): Record<string, T[]> { | ||||||
const summaryPath = getSummaryJsonPath(inferenceType); | ||||||
try { | ||||||
const logDir = path.resolve(INFERENCE_LOG_DIR); | ||||||
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. logic: Variable name inconsistency: using
Suggested change
Prompt To Fix With AIThis is a comment left during a code review.
Path: lib/inferenceLogUtils.ts
Line: 50:50
Comment:
**logic:** Variable name inconsistency: using `INFERENCE_LOG_DIR` but imported `INFERENCE_LOGS_DIR`
```suggestion
const logDir = path.resolve(INFERENCE_LOGS_DIR);
```
How can I resolve this? If you propose a fix, please make it concise. |
||||||
const logPath = path.resolve(logDir, `${id}.json`); | ||||||
|
||||||
// The top-level array key, e.g. "act_summary", "observe_summary", "extract_summary" | ||||||
const arrayKey = `${inferenceType}_summary`; | ||||||
// Prevent path traversal. | ||||||
if (!logPath.startsWith(logDir + path.sep)) { | ||||||
console.error(`Path traversal attempt detected for id: ${id}`); | ||||||
return null; | ||||||
} | ||||||
|
||||||
if (!fs.existsSync(summaryPath)) { | ||||||
return { [arrayKey]: [] }; | ||||||
const log = fs.readFileSync(logPath, "utf-8"); | ||||||
return JSON.parse(log); | ||||||
} catch (e) { | ||||||
return null; | ||||||
} | ||||||
} | ||||||
// Security: Prevent path traversal attacks. | ||||||
// Ensure the resolved path is within the intended log directory. | ||||||
const resolvedPath = path.resolve(logPath); | ||||||
const resolvedBaseDir = path.resolve(INFERENCE_LOGS_DIR); | ||||||
|
||||||
try { | ||||||
const raw = fs.readFileSync(summaryPath, "utf8"); | ||||||
const parsed = JSON.parse(raw); | ||||||
if ( | ||||||
parsed && | ||||||
typeof parsed === "object" && | ||||||
Array.isArray(parsed[arrayKey]) | ||||||
) { | ||||||
return parsed; | ||||||
if (!resolvedPath.startsWith(resolvedBaseDir + path.sep)) { | ||||||
console.warn(`Potential path traversal attempt for id: ${id}`); | ||||||
return null; | ||||||
} | ||||||
|
||||||
const data = await fs.readFile(resolvedPath, "utf-8"); | ||||||
return JSON.parse(data); | ||||||
} catch (error) { | ||||||
// It's okay if the file doesn't exist | ||||||
if (isNodeError(error) && error.code === "ENOENT") { | ||||||
return null; | ||||||
} | ||||||
} catch { | ||||||
// If we fail to parse for any reason, fall back to empty array | ||||||
// Re-throw other errors | ||||||
throw error; | ||||||
} | ||||||
return { [arrayKey]: [] }; | ||||||
} |
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.
syntax: Syntax error:
appendToInferenceLog
function is incomplete and missing closing brace before the next exportPrompt To Fix With AI