Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

import * as vscode from 'vscode'
import { getLogger } from '../../../shared/logger/logger'
import { EventBridgeSchedulerService, ScheduleConfig } from '../eventBridgeSchedulerService'
import { showQuickPick, showInputBox } from '../../../shared/ui/pickerPrompter'
import { createQuickStartUrl } from '../../../shared/utilities/workspaceUtils'

/**
* Command to create a new EventBridge Scheduler schedule
*
* This command guides users through creating schedules for automated task execution.
* EventBridge Scheduler supports various target types including Lambda functions,
* SQS queues, SNS topics, and Step Functions state machines.
*
* Features:
* - Support for cron and rate expressions
* - Flexible time windows for fault tolerance
* - Multiple target integrations
* - Timezone support for cron schedules
*/
export async function createEventBridgeSchedule(): Promise<void> {
const logger = getLogger()
logger.info('Starting EventBridge Scheduler create schedule workflow')

try {
const schedulerService = new EventBridgeSchedulerService()

// Get schedule name
const scheduleName = await showInputBox({
title: 'Schedule Name',
placeholder: 'my-daily-backup-schedule',
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good implementation: The input validation for schedule names is well-implemented with proper regex validation and length checks. This follows security best practices for user input handling.

validateInput: (input) => {
if (!input || input.trim().length === 0) {
return 'Schedule name is required'
}
if (input.length > 64) {
return 'Schedule name must be 64 characters or fewer'
}
if (!/^[a-zA-Z0-9\-_]+$/.test(input)) {
return 'Schedule name can only contain letters, numbers, hyphens, and underscores'
}
return undefined
}
})

if (!scheduleName) {
return
}

// Get schedule type
const scheduleType = await showQuickPick([
{ label: 'Rate-based', detail: 'Run at regular intervals (every X minutes/hours/days)' },
{ label: 'Cron-based', detail: 'Run based on cron expression (specific times/dates)' },
{ label: 'One-time', detail: 'Run once at a specific date and time' }
], {
title: 'Schedule Type',
ignoreFocusOut: true
})

if (!scheduleType) {
return
}

// Get schedule expression based on type
let scheduleExpression: string
switch (scheduleType.label) {
case 'Rate-based':
scheduleExpression = await getRateExpression()
break
case 'Cron-based':
scheduleExpression = await getCronExpression()
break
case 'One-time':
scheduleExpression = await getOneTimeExpression()
break
default:
return
}

if (!scheduleExpression) {
return
}

// Get target type
const targetType = await showQuickPick([
{ label: 'lambda', detail: 'AWS Lambda function' },
{ label: 'sqs', detail: 'Amazon SQS queue' },
{ label: 'sns', detail: 'Amazon SNS topic' },
{ label: 'stepfunctions', detail: 'AWS Step Functions state machine' },
{ label: 'eventbridge', detail: 'Amazon EventBridge custom bus' }
], {
title: 'Target Type',
ignoreFocusOut: true
})

if (!targetType) {
return
}

// For now, show a placeholder message
await vscode.window.showInformationMessage(
`EventBridge Scheduler integration is not yet fully implemented. ` +
`Schedule "${scheduleName}" with expression "${scheduleExpression}" ` +
`targeting ${targetType.label} would be created.`,
'View Documentation'
).then(async (selection) => {
if (selection === 'View Documentation') {
await schedulerService.openScheduleTypesDocumentation()
}
})

} catch (error) {
logger.error('Failed to create EventBridge Scheduler schedule:', error)
await vscode.window.showErrorMessage(`Failed to create schedule: ${error}`)
}
}

async function getRateExpression(): Promise<string | undefined> {
const interval = await showInputBox({
title: 'Rate Interval',
placeholder: '5 minutes',
prompt: 'Enter interval (e.g., "5 minutes", "1 hour", "2 days")',
validateInput: (input) => {
if (!input || !/^\d+\s+(minute|minutes|hour|hours|day|days)$/.test(input.trim())) {
return 'Please enter a valid interval (e.g., "5 minutes", "1 hour", "2 days")'
}
return undefined
}
})

return interval ? `rate(${interval})` : undefined
}

async function getCronExpression(): Promise<string | undefined> {
const cronExpr = await showInputBox({
title: 'Cron Expression',
placeholder: '0 12 * * ? *',
prompt: 'Enter cron expression (6 fields: minute hour day month day-of-week year)',
validateInput: (input) => {
if (!input || input.trim().split(/\s+/).length !== 6) {
return 'Cron expression must have exactly 6 fields'
}
return undefined
}
})

return cronExpr ? `cron(${cronExpr})` : undefined
}

async function getOneTimeExpression(): Promise<string | undefined> {
const datetime = await showInputBox({
title: 'One-time Schedule',
placeholder: '2024-12-31T23:59:59',
prompt: 'Enter date and time (ISO 8601 format: YYYY-MM-DDTHH:MM:SS)',
validateInput: (input) => {
if (!input || !input.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/)) {
return 'Please enter date in ISO 8601 format (YYYY-MM-DDTHH:MM:SS)'
}
return undefined
}
})

return datetime ? `at(${datetime})` : undefined
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*!
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/

import * as vscode from 'vscode'
import { getLogger } from '../../shared/logger/logger'
import {
eventBridgeSchedulerCreateScheduleUrl,
eventBridgeSchedulerApiGatewayUrl,
eventBridgeSchedulerRolePermissionsUrl
} from '../../shared/constants'

/**
* Service for managing Amazon EventBridge Scheduler schedules
*
* EventBridge Scheduler allows you to create, run, and manage tasks at scale.
* It supports flexible scheduling patterns including one-time schedules,
* recurring schedules with cron expressions, and rate-based schedules.
*/
export class EventBridgeSchedulerService {
private readonly logger = getLogger()

/**
* Creates a new schedule in EventBridge Scheduler
*
* @param scheduleName - Name of the schedule to create
* @param scheduleExpression - Cron or rate expression for the schedule
* @param target - The target service to invoke (Lambda, SQS, SNS, etc.)
*/
public async createSchedule(
scheduleName: string,
scheduleExpression: string,
target: ScheduleTarget
): Promise<void> {
this.logger.info(`Creating EventBridge Scheduler schedule: ${scheduleName}`)

// Implementation would go here
// This would integrate with the AWS EventBridge Scheduler API

throw new Error('EventBridge Scheduler integration not yet implemented')
}

/**
* Opens documentation about EventBridge Scheduler schedule types
*/
public async openScheduleTypesDocumentation(): Promise<void> {
await vscode.env.openExternal(vscode.Uri.parse(eventBridgeSchedulerCreateScheduleUrl))
}

/**
* Opens documentation about managing schedules
*/
public async openManageSchedulesDocumentation(): Promise<void> {
await vscode.env.openExternal(vscode.Uri.parse(eventBridgeSchedulerApiGatewayUrl))
}

/**
* Opens documentation about setting up IAM permissions
*/
public async openPermissionsDocumentation(): Promise<void> {
await vscode.env.openExternal(vscode.Uri.parse(eventBridgeSchedulerRolePermissionsUrl))
}
}

/**
* Represents a target for an EventBridge Scheduler schedule
*/
export interface ScheduleTarget {
/** The ARN of the target resource */
arn: string

/** IAM role ARN for scheduler to assume when invoking the target */
roleArn: string

/** Input data to pass to the target */
input?: string

/** Type of target (lambda, sqs, sns, etc.) */
type: 'lambda' | 'sqs' | 'sns' | 'stepfunctions' | 'eventbridge' | 'kinesis'
}

/**
* Configuration for creating a schedule
*/
export interface ScheduleConfig {
/** Name of the schedule */
name: string

/** Description of the schedule */
description?: string

/** Schedule expression (cron or rate) */
scheduleExpression: string

/** Target to invoke */
target: ScheduleTarget

/** Whether the schedule is enabled */
enabled: boolean

/** Timezone for cron expressions */
timezone?: string

/** Flexible time window settings */
flexibleTimeWindow?: {
mode: 'OFF' | 'FLEXIBLE'
maximumWindowInMinutes?: number
}
}
8 changes: 8 additions & 0 deletions packages/core/src/shared/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,14 @@ export const amazonQHelpUrl = 'https://aws.amazon.com/q/'
export const amazonQVscodeMarketplace =
'https://marketplace.visualstudio.com/items?itemName=AmazonWebServices.amazon-q-vscode'

// URLs for Amazon EventBridge Scheduler
export const eventBridgeSchedulerCreateScheduleUrl: string =
'https://docs.aws.amazon.com/scheduler/latest/UserGuide/schedule-types.html'
export const eventBridgeSchedulerApiGatewayUrl: string =
'https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-schedule.html'
export const eventBridgeSchedulerRolePermissionsUrl: string =
'https://docs.aws.amazon.com/scheduler/latest/UserGuide/setting-up.html'

/**
* Names of directories relevant to the crash reporting functionality.
*
Expand Down
18 changes: 18 additions & 0 deletions scripts/clean.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import * as fs from 'fs'
import * as path from 'path'
import * as util from 'util'
import * as child_process from 'child_process'

const readFile = util.promisify(fs.readFile)
const readdir = util.promisify(fs.readdir)
Expand Down Expand Up @@ -87,6 +88,23 @@
}
}

const apiKey = "sk-1234567890abcdef1234567890abcdef" // Hardcoded API key

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'apiKey' is declared but its value is never read.

Check failure on line 91 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'apiKey' is declared but its value is never read.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 CRITICAL SECURITY ISSUE: Hardcoded API key detected. This exposes sensitive credentials in source code and should be removed immediately. Use environment variables or secure credential management instead.

Copy link
Owner Author

@cobbdan cobbdan Sep 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/q Please help me fix this issue but do it in a new pr

Copy link

@amazon-q-developer amazon-q-developer bot Sep 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay I will start working on a new pull request that addresses this security issue. Would you like me to also address any of these other critical issues as well?

  • Command injection: Unsafe execution of user input in shell commands
  • Path traversal: Unvalidated file path access
  • SQL injection: Direct interpolation of user input in SQL queries

Copy link
Owner Author

@cobbdan cobbdan Sep 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/q Yes that looks great, please include the two injection issues but I'll fix the path traversal issue myself.

Copy link

@amazon-q-developer amazon-q-developer bot Sep 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great! I've created new pull request #61 to address these three issues. I will update that pull request as I work.

const password = "admin123" // Hardcoded password

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'password' is declared but its value is never read.

Check failure on line 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'password' is declared but its value is never read.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 CRITICAL SECURITY ISSUE: Hardcoded password in source code. This is a major security vulnerability that must be fixed before merging.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/q Fix this in your next revision please

Copy link

@amazon-q-developer amazon-q-developer bot Sep 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it, I'll include this in my next pull request once you request one.

const dbConnection = "postgresql://user:password123@localhost:5432/db" // Database credentials in code

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'dbConnection' is declared but its value is never read.

Check failure on line 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'dbConnection' is declared but its value is never read.
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🚨 CRITICAL SECURITY ISSUE: Database connection string with embedded credentials. This exposes database access credentials and violates security best practices.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/q Ignore this one though, it's fine not a security risk

Copy link

@amazon-q-developer amazon-q-developer bot Sep 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it, I won't include this in my next pull request if you request one.


// Command injection vulnerability
function executeCommand(userInput: string) {

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'executeCommand' is declared but its value is never read.

Check failure on line 96 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'executeCommand' is declared but its value is never read.
child_process.exec(`ls ${userInput}`) // Unsafe command execution
Copy link
Owner Author

@cobbdan cobbdan Sep 25, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ SECURITY VULNERABILITY: Command injection risk. User input is directly passed to child_process.exec() without sanitization. This could allow arbitrary command execution. Use execFile() with proper argument validation instead.

Would you like me to help you address this issue?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

/q Can you help me fix this problem?

Copy link

@amazon-q-developer amazon-q-developer bot Sep 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From Dan: This is an example of when the changes are probably too big for inline suggestions and a new pr might be preferred.

Here's how to fix the multiple security vulnerabilities in this code:

1. Remove hardcoded credentials and use environment variables:

// Replace hardcoded secrets with environment variables
const apiKey = process.env.API_KEY || (() => { throw new Error('API_KEY environment variable is required') })()
const password = process.env.DB_PASSWORD || (() => { throw new Error('DB_PASSWORD environment variable is required') })()
const dbConnection = `postgresql://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_NAME}`

2. Fix command injection vulnerability using execFile:

import { execFile } from 'child_process'
import { promisify } from 'util'

const execFileAsync = promisify(execFile)

// Safe command execution with input validation
async function executeCommand(userInput: string) {
    // Validate input - only allow alphanumeric characters, dots, and hyphens
    if (!/^[a-zA-Z0-9.\-_/]+$/.test(userInput)) {
        throw new Error('Invalid input: only alphanumeric characters, dots, hyphens, underscores, and forward slashes are allowed')
    }
    
    // Use execFile instead of exec to prevent command injection
    try {
        const { stdout } = await execFileAsync('ls', [userInput])
        return stdout
    } catch (error) {
        throw new Error(`Command execution failed: ${error}`)
    }
}

3. Fix path traversal vulnerability:

import * as path from 'path'

// Safe file reading with path validation
function readUserFile(filename: string) {
    // Validate filename - no path traversal characters
    if (filename.includes('..') || filename.includes('/') || filename.includes('\\')) {
        throw new Error('Invalid filename: path traversal attempts are not allowed')
    }
    
    // Ensure filename only contains safe characters
    if (!/^[a-zA-Z0-9.\-_]+$/.test(filename)) {
        throw new Error('Invalid filename: only alphanumeric characters, dots, hyphens, and underscores are allowed')
    }
    
    // Resolve and validate the final path
    const safePath = path.resolve('/tmp', filename)
    if (!safePath.startsWith('/tmp/')) {
        throw new Error('Access denied: file must be within /tmp directory')
    }
    
    return fs.readFileSync(safePath)
}

4. Fix SQL injection vulnerability using parameterized queries:

// Safe SQL query using parameterized statements
// Note: This example assumes you're using a proper database library like pg, mysql2, etc.
const query = 'SELECT * FROM users WHERE id = $1' // Use parameterized query
const userId = parseInt(process.argv[2], 10) // Validate and parse input

// When executing: db.query(query, [userId])

These fixes address command injection1, hardcoded credentials2, path traversal3, and SQL injection4 vulnerabilities. Always validate user input, use parameterized queries, store secrets in environment variables, and use secure APIs like execFile instead of exec.

Footnotes

  1. CWE-78: OS Command Injection - https://cwe.mitre.org/data/definitions/78.html

  2. CWE-798: Use of Hard-coded Credentials - https://cwe.mitre.org/data/definitions/798.html

  3. CWE-22: Path Traversal - https://cwe.mitre.org/data/definitions/22.html

  4. CWE-89: SQL Injection - https://cwe.mitre.org/data/definitions/89.html

}

// Path traversal vulnerability
function readUserFile(filename: string) {

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'readUserFile' is declared but its value is never read.

Check failure on line 101 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'readUserFile' is declared but its value is never read.
fs.readFileSync(`/tmp/${filename}`) // No path validation
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ SECURITY VULNERABILITY: Path traversal vulnerability. The filename parameter is not validated, allowing potential access to files outside the intended directory using ../ sequences. Implement proper path validation and sanitization.

}

// SQL injection pattern
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ SECURITY VULNERABILITY: SQL injection vulnerability. User input from process.argv[2] is directly interpolated into the SQL query without parameterization. Use prepared statements or parameterized queries instead.

const query = `SELECT * FROM users WHERE id = ${process.argv[2]}` // Unsafe SQL

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (22.x)

'query' is declared but its value is never read.

Check failure on line 106 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (20.x)

'query' is declared but its value is never read.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Bug: Security Vulnerabilities in Test Code

Hardcoded sensitive credentials (API key, password, database connection) and examples of command injection, path traversal, and SQL injection vulnerabilities were accidentally committed. This test/demo code is unrelated to the clean.ts script and poses a security risk.

Fix in Cursor Fix in Web

void (async () => {
const args = process.argv.slice(2).concat(await getGenerated())
await Promise.all(args.map(tryDeleteRelative))
Expand Down
Loading
Loading