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'

Choose a reason for hiding this comment

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

The import for createQuickStartUrl is unused in this file. This creates unnecessary dependencies and can impact bundle size.

Suggested change
import { createQuickStartUrl } from '../../../shared/utilities/workspaceUtils'
import { showQuickPick, showInputBox } from '../../../shared/ui/pickerPrompter'

Choose a reason for hiding this comment

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

The import for createQuickStartUrl is unused in this file. This creates unnecessary dependencies and should be removed to keep the imports clean.

Suggested change
import { createQuickStartUrl } from '../../../shared/utilities/workspaceUtils'
import { showQuickPick, showInputBox } from '../../../shared/ui/pickerPrompter'


/**
* 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',
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
Comment on lines +41 to +46
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: The input validation for the schedule name allows potentially unsafe characters. Consider using a more restrictive regex pattern to prevent potential injection attacks1. Also, add a check to ensure the name doesn't start or end with a hyphen, which is a common requirement for AWS resource names.

Suggested change
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 (!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'
}
if (input.startsWith('-') || input.endsWith('-')) {
return 'Schedule name cannot start or end with a hyphen'
}
return undefined

Footnotes

  1. CWE-20: Improper Input Validation - https://cwe.mitre.org/data/definitions/20.html

}
})

if (!scheduleName) {
return
}

Comment on lines +27 to +53
Copy link
Owner Author

Choose a reason for hiding this comment

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

The createEventBridgeSchedule function is a good start, but there are several areas for improvement:

  1. Error Handling: The function catches all errors and displays them as a generic message. Consider more specific error handling for different types of errors.

  2. Input Validation: While there's some input validation for the schedule name, consider adding more robust validation for other inputs (e.g., cron expressions, rate expressions).

  3. Target Configuration: The function doesn't fully implement target configuration. This is a crucial part of creating a schedule and should be completed.

  4. Async/Await Usage: The function uses a mix of async/await and .then() chains. Consider consistently using async/await for better readability.

  5. Documentation: While there are some comments, more detailed JSDoc comments for the main function and its parameters would be beneficial.

Suggested change
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',
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
}
/**
* Command to create a new EventBridge Scheduler schedule
*
* @returns {Promise<void>}
*/
export async function createEventBridgeSchedule(): Promise<void> {
const logger = getLogger()
logger.info('Starting EventBridge Scheduler create schedule workflow')
try {
const schedulerService = new EventBridgeSchedulerService()
const scheduleName = await getScheduleName()
if (!scheduleName) return
const scheduleType = await getScheduleType()
if (!scheduleType) return
const scheduleExpression = await getScheduleExpression(scheduleType.label)
if (!scheduleExpression) return
const targetType = await getTargetType()
if (!targetType) return
const target = await configureTarget(targetType.label)
if (!target) return
const scheduleConfig: ScheduleConfig = {
name: scheduleName,
scheduleExpression,
target,
enabled: true
}
await schedulerService.createSchedule(scheduleConfig)
await vscode.window.showInformationMessage(`Schedule "${scheduleName}" created successfully.`)
} catch (error) {
logger.error('Failed to create EventBridge Scheduler schedule:', error)
if (error instanceof Error) {
await vscode.window.showErrorMessage(`Failed to create schedule: ${error.message}`)
} else {
await vscode.window.showErrorMessage('An unexpected error occurred while creating the schedule.')
}
}
}

// 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

Choose a reason for hiding this comment

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

The variable scheduleExpression is declared but potentially undefined when the switch statement doesn't match any case. This could lead to runtime errors when accessing the variable later.

Suggested change
let scheduleExpression: string
let scheduleExpression: string | undefined

Choose a reason for hiding this comment

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

The variable scheduleExpression is declared but not initialized, which could lead to TypeScript compilation issues. Consider initializing it or using definite assignment assertion if you're certain it will be assigned in all code paths.

Suggested change
let scheduleExpression: string
let scheduleExpression: string | undefined

switch (scheduleType.label) {
case 'Rate-based':
scheduleExpression = await getRateExpression()
break
case 'Cron-based':
Comment on lines +70 to +74
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: The createEventBridgeSchedule function lacks input validation for the scheduleExpression. This could lead to potential injection attacks or unexpected behavior1. Consider adding input validation for the schedule expression as shown in the code suggestion.

Suggested change
switch (scheduleType.label) {
case 'Rate-based':
scheduleExpression = await getRateExpression()
break
case 'Cron-based':
if (!scheduleExpression) {
return
}
// Validate schedule expression
if (!/^(rate\([^\)]+\)|cron\([^\)]+\)|at\([^\)]+\))$/.test(scheduleExpression)) {
throw new Error('Invalid schedule expression. Must be a valid rate, cron, or at expression.')
}
// Get target type

Footnotes

  1. CWE-20: Improper Input Validation - https://cwe.mitre.org/data/definitions/20.html

scheduleExpression = await getCronExpression()
break
case 'One-time':
scheduleExpression = await getOneTimeExpression()
break
default:
return
}
Comment on lines +76 to +82
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: The createEventBridgeSchedule function is vulnerable to command injection in the scheduleExpression input. User input should be properly validated and sanitized before being used in schedule expressions1.

Suggested change
break
case 'One-time':
scheduleExpression = await getOneTimeExpression()
break
default:
return
}
// Validate and sanitize schedule expression
const sanitizedExpression = sanitizeScheduleExpression(scheduleExpression);
if (!isValidScheduleExpression(sanitizedExpression)) {
throw new Error('Invalid schedule expression');
}
// Use sanitized expression in schedule creation
const scheduleConfig: ScheduleConfig = {
name: scheduleName,
scheduleExpression: sanitizedExpression,
target: {
arn: targetArn,
roleArn: targetRoleArn,
type: targetType.label
},
enabled: true
};
await schedulerService.createSchedule(scheduleConfig);

Footnotes

  1. CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') - https://cwe.mitre.org/data/definitions/78.html


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}`)
}
Comment on lines +25 to +119
Copy link
Owner Author

Choose a reason for hiding this comment

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

The createEventBridgeSchedule function is well-structured, but it could benefit from some error handling improvements. Consider adding more specific error handling for different types of errors that might occur during the schedule creation process.

Suggested change
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',
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}`)
}
export async function createEventBridgeSchedule(): Promise<void> {
const logger = getLogger()
logger.info('Starting EventBridge Scheduler create schedule workflow')
try {
const schedulerService = new EventBridgeSchedulerService()
// ... (rest of the function remains the same)
} catch (error) {
logger.error('Failed to create EventBridge Scheduler schedule:', error)
if (error instanceof Error) {
await vscode.window.showErrorMessage(`Failed to create schedule: ${error.message}`)
} else {
await vscode.window.showErrorMessage('An unexpected error occurred while creating the schedule')
}
}
}

}

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
}
})

Comment on lines +129 to +134
Copy link
Owner Author

Choose a reason for hiding this comment

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

Consider adding more robust validation for the cron expression. The current validation only checks for the number of fields but doesn't verify if the values are within valid ranges for each field. This could lead to invalid cron expressions being accepted1.

Suggested change
return 'Please enter a valid interval (e.g., "5 minutes", "1 hour", "2 days")'
}
return undefined
}
})
const isValidCron = (cron: string): boolean => {
const fields = cron.split(/\s+/)
if (fields.length !== 6) return false
const ranges = [
[0, 59], // Minute
[0, 23], // Hour
[1, 31], // Day of month
[1, 12], // Month
[0, 7], // Day of week (0 or 7 is Sunday)
[1970, 2099] // Year
]
return fields.every((field, i) => {
if (field === '*') return true
const values = field.split(',')
return values.every(value => {
const range = value.split('-')
if (range.length > 2) return false
const [start, end] = range.map(Number)
return !isNaN(start) && (end === undefined || !isNaN(end)) &&
start >= ranges[i][0] && (end || start) <= ranges[i][1]
})
})
}
if (!isValidCron(input.trim())) {
return 'Invalid cron expression. Please check the values for each field.'
}
return undefined

Footnotes

  1. CWE-20: Improper Input Validation - https://cwe.mitre.org/data/definitions/20.html

return interval ? `rate(${interval})` : undefined
}
Comment on lines +122 to +136
Copy link
Owner Author

Choose a reason for hiding this comment

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

The getRateExpression function could be improved by adding support for weeks and months in the rate expression. This would provide more flexibility for users when creating schedules.

Suggested change
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 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", "1 week", "1 month")',
validateInput: (input) => {
if (!input || !/^\d+\s+(minute|minutes|hour|hours|day|days|week|weeks|month|months)$/.test(input.trim())) {
return 'Please enter a valid interval (e.g., "5 minutes", "1 hour", "2 days", "1 week", "1 month")'
}
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
}
Comment on lines +138 to +152
Copy link
Owner Author

Choose a reason for hiding this comment

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

The getCronExpression function could benefit from more robust validation of the cron expression. Consider using a library like cron-validator to ensure the entered cron expression is valid and follows AWS EventBridge Scheduler's specific cron format.

Suggested change
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
}
import { isValidCron } from 'cron-validator'
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'
}
if (!isValidCron(input, { alias: true, seconds: false, allowBlankDay: true })) {
return 'Invalid cron expression. Please check the format and try again.'
}
return undefined
}
})
return cronExpr ? `cron(${cronExpr})` : undefined
}


Comment on lines +138 to +153
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: The getCronExpression function is not implementing proper input validation for the cron expression. This could lead to potential injection attacks or unexpected behavior.1

Consider adding more robust validation for cron expressions, which can be complex. Implement a proper parsing and validation library for cron expressions to ensure they are well-formed and safe.

Suggested change
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
}
// Add a proper cron expression validation library
import * as cronParser from 'cron-parser';
// ...
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'
}
try {
cronParser.parseExpression(input);
return undefined;
} catch (error) {
return `Invalid cron expression: ${error.message}`;
}
}
})
return cronExpr ? `cron(${cronExpr})` : undefined
}

Footnotes

  1. CWE-20: Improper Input Validation - https://cwe.mitre.org/data/definitions/20.html

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)'
}
Comment on lines +160 to +162

Choose a reason for hiding this comment

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

The regex validation for ISO 8601 format is incomplete. It doesn't validate actual date/time values, which could allow invalid dates like "9999-99-99T99:99:99" to pass validation. Consider using a proper date parsing library or more comprehensive validation.

Suggested change
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)'
}
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)'
}
// Validate that the date is actually valid
const date = new Date(input)
if (isNaN(date.getTime()) || date.toISOString().slice(0, 19) !== input) {
return 'Please enter a valid date and time'
}

return undefined
}
Comment on lines +160 to +164

Choose a reason for hiding this comment

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

The regex validation for ISO 8601 format is too restrictive and doesn't validate the actual date/time values. This could allow invalid dates like "9999-99-99T99:99:99" to pass validation. Consider using a more robust date validation approach.

Suggested change
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
}
validateInput: (input) => {
if (!input) {
return 'Please enter date in ISO 8601 format (YYYY-MM-DDTHH:MM:SS)'
}
if (!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)'
}
// Validate that it's a valid date
const date = new Date(input)
if (isNaN(date.getTime())) {
return 'Please enter a valid date and time'
}
// Check if the date is in the past
if (date <= new Date()) {
return 'Schedule date must be in the future'
}
return undefined
}

})

return datetime ? `at(${datetime})` : undefined
}
Comment on lines +154 to +168
Copy link
Owner Author

Choose a reason for hiding this comment

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

The getOneTimeExpression function could be improved by using a more robust date-time validation and parsing library like date-fns. This would ensure that the entered date is valid and in the future.

Suggested change
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
}
import { parse, isValid, isFuture } from 'date-fns'
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) {
return 'Date and time is required'
}
const parsedDate = parse(input, "yyyy-MM-dd'T'HH:mm:ss", new Date())
if (!isValid(parsedDate)) {
return 'Invalid date format. Please use YYYY-MM-DDTHH:mm:ss'
}
if (!isFuture(parsedDate)) {
return 'The scheduled time must be in the future'
}
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
Copy link
Owner Author

Choose a reason for hiding this comment

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

The createSchedule method is currently throwing an error indicating that the EventBridge Scheduler integration is not yet implemented. It's important to implement this method to provide the core functionality of creating schedules. Consider prioritizing the implementation of this method to interact with the AWS EventBridge Scheduler API.

Comment on lines +27 to +38
Copy link
Owner Author

Choose a reason for hiding this comment

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

The createSchedule method in the EventBridgeSchedulerService class is not yet implemented. This is a critical part of the EventBridge Scheduler integration. Here are some suggestions for improvement:

  1. Implementation: The method should be implemented to interact with the AWS EventBridge Scheduler API.

  2. Error Handling: Proper error handling should be added to catch and handle specific AWS SDK errors.

  3. Validation: Add input validation for the schedule parameters before making the API call.

  4. Logging: Enhance logging to include more details about the schedule creation process.

  5. Return Value: Consider returning the created schedule details instead of void.

Suggested change
* @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
import { EventBridgeSchedulerClient, CreateScheduleCommand, CreateScheduleCommandInput } from "@aws-sdk/client-scheduler";
public async createSchedule(config: ScheduleConfig): Promise<string> {
this.logger.info(`Creating EventBridge Scheduler schedule: ${config.name}`)
try {
const client = new EventBridgeSchedulerClient({});
const input: CreateScheduleCommandInput = {
Name: config.name,
ScheduleExpression: config.scheduleExpression,
Target: {
Arn: config.target.arn,
RoleArn: config.target.roleArn,
Input: config.target.input
},
State: config.enabled ? 'ENABLED' : 'DISABLED',
FlexibleTimeWindow: {
Mode: config.flexibleTimeWindow?.mode || 'OFF'
}
};
if (config.description) {
input.Description = config.description;
}
if (config.timezone) {
input.ScheduleExpressionTimezone = config.timezone;
}
const command = new CreateScheduleCommand(input);
const response = await client.send(command);
this.logger.info(`Schedule created successfully: ${response.ScheduleArn}`);
return response.ScheduleArn || '';
} catch (error) {
this.logger.error('Failed to create EventBridge Scheduler schedule:', error);
throw error;
}
}

Comment on lines +27 to +38
Copy link
Owner Author

Choose a reason for hiding this comment

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

The createSchedule method is currently not implemented and throws an error. Consider adding a TODO comment to track this implementation or provide a basic implementation to avoid runtime errors.

Suggested change
* @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
public async createSchedule(
scheduleName: string,
scheduleExpression: string,
target: ScheduleTarget
): Promise<void> {
this.logger.info(`Creating EventBridge Scheduler schedule: ${scheduleName}`)
// TODO: Implement integration with AWS EventBridge Scheduler API
// For now, log the schedule details
this.logger.info(`Schedule details:
Name: ${scheduleName}
Expression: ${scheduleExpression}
Target: ${JSON.stringify(target)}`)
// Placeholder: Simulate schedule creation
await new Promise(resolve => setTimeout(resolve, 1000))
this.logger.info(`Simulated creation of schedule: ${scheduleName}`)
}

// This would integrate with the AWS EventBridge Scheduler API

Comment on lines +35 to +40
Copy link
Owner Author

Choose a reason for hiding this comment

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

The createSchedule method is currently not implemented and throws an error. Consider adding a TODO comment to track this implementation or provide a basic implementation if possible. This will help developers understand the current state and future plans for this method.

Suggested change
): Promise<void> {
this.logger.info(`Creating EventBridge Scheduler schedule: ${scheduleName}`)
// Implementation would go here
// This would integrate with the AWS EventBridge Scheduler API
public async createSchedule(
scheduleName: string,
scheduleExpression: string,
target: ScheduleTarget
): Promise<void> {
this.logger.info(`Creating EventBridge Scheduler schedule: ${scheduleName}`)
// TODO: Implement integration with AWS EventBridge Scheduler API
// For now, log the schedule details
this.logger.debug('Schedule details:', { scheduleName, scheduleExpression, target })
// Placeholder: Simulate schedule creation
await new Promise(resolve => setTimeout(resolve, 1000))
this.logger.info(`Simulated creation of schedule: ${scheduleName}`)
// Throw error to indicate incomplete implementation
throw new Error('EventBridge Scheduler integration not yet fully implemented')
}

Comment on lines +33 to +40
Copy link
Owner Author

Choose a reason for hiding this comment

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

The createSchedule method is not implemented and throws an error. This could lead to unexpected behavior if called. Consider implementing the method or providing a more informative error message with next steps for the user.

Suggested change
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
public async createSchedule(
scheduleName: string,
scheduleExpression: string,
target: ScheduleTarget
): Promise<void> {
this.logger.info(`Creating EventBridge Scheduler schedule: ${scheduleName}`)
// TODO: Implement integration with AWS EventBridge Scheduler API
throw new Error('EventBridge Scheduler integration not yet implemented. Please check for updates or contribute to the implementation.')
}

throw new Error('EventBridge Scheduler integration not yet implemented')
}
Comment on lines +31 to +42
Copy link
Owner Author

Choose a reason for hiding this comment

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

The createSchedule method is currently not implemented and throws an error. Consider adding a TODO comment and logging a warning instead of throwing an error. This will allow for easier future implementation and better user experience.

Suggested change
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')
}
public async createSchedule(
scheduleName: string,
scheduleExpression: string,
target: ScheduleTarget
): Promise<void> {
this.logger.info(`Creating EventBridge Scheduler schedule: ${scheduleName}`)
// TODO: Implement integration with AWS EventBridge Scheduler API
this.logger.warn('EventBridge Scheduler integration not yet implemented')
vscode.window.showWarningMessage('EventBridge Scheduler integration is not yet available. This is a placeholder for future functionality.')
}


/**
* 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'
}
Comment on lines +69 to +81
Copy link
Owner Author

Choose a reason for hiding this comment

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

The ScheduleTarget interface could be improved by using a more specific type for the type property. Consider using a union type of string literals for better type safety and autocomplete support.

Suggested change
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'
}
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 */
type: 'lambda' | 'sqs' | 'sns' | 'stepfunctions' | 'eventbridge' | 'kinesis' | 'ecs' | 'fargate'
}


/**
* 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
}
}
Comment on lines +86 to +110
Copy link
Owner Author

Choose a reason for hiding this comment

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

The ScheduleConfig interface could be improved by adding validation for the timezone property and providing more specific types for the flexibleTimeWindow property. Also, consider adding a property for retry policy, which is supported by EventBridge Scheduler.

Suggested change
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
}
}
import { TimeZone } from 'aws-sdk/clients/eventbridge'
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?: TimeZone
/** Flexible time window settings */
flexibleTimeWindow?: {
mode: 'OFF' | 'FLEXIBLE'
maximumWindowInMinutes?: number
}
/** Retry policy for failed invocations */
retryPolicy?: {
maximumRetryAttempts: number
maximumEventAgeInSeconds: 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'
Comment on lines +195 to +196

Choose a reason for hiding this comment

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

The variable name eventBridgeSchedulerApiGatewayUrl is misleading as it points to general schedule management documentation, not API Gateway-specific content. Consider renaming it to better reflect its purpose.

Suggested change
export const eventBridgeSchedulerApiGatewayUrl: string =
'https://docs.aws.amazon.com/scheduler/latest/UserGuide/managing-schedule.html'
export const eventBridgeSchedulerManageScheduleUrl: string =
''

export const eventBridgeSchedulerRolePermissionsUrl: string =
Comment on lines +192 to +197
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 addition of EventBridge Scheduler documentation URLs. Consider using a more descriptive naming convention for these constants to improve clarity and maintainability. For example, you could use EVENTBRIDGE_SCHEDULER_DOCS_ as a prefix.

Suggested change
// 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 =
export const EVENTBRIDGE_SCHEDULER_DOCS_CREATE_SCHEDULE: string =
''
export const EVENTBRIDGE_SCHEDULER_DOCS_MANAGE_SCHEDULES: string =
''
export const EVENTBRIDGE_SCHEDULER_DOCS_ROLE_PERMISSIONS: string =
''

Comment on lines +192 to +197
Copy link
Owner Author

Choose a reason for hiding this comment

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

The addition of EventBridge Scheduler URLs to the constants file is a good practice. However, there are a couple of suggestions for improvement:

  1. Naming Convention: Consider using a more consistent naming convention for the constants. For example, you could prefix all EventBridge Scheduler related constants with EVENTBRIDGE_SCHEDULER_.

  2. Documentation: It would be helpful to add brief comments explaining what each URL is used for within the application.

  3. Type Safety: Consider using as const to make these URLs readonly and improve type safety.

Suggested change
// 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 =
// URLs for Amazon EventBridge Scheduler
export const EVENTBRIDGE_SCHEDULER_CREATE_SCHEDULE_URL = '' as const
export const EVENTBRIDGE_SCHEDULER_API_GATEWAY_URL = '' as const
export const EVENTBRIDGE_SCHEDULER_ROLE_PERMISSIONS_URL = '' as const
/**
* URL for EventBridge Scheduler documentation on schedule types
*/
export const EVENTBRIDGE_SCHEDULER_CREATE_SCHEDULE_URL: string
/**
* URL for EventBridge Scheduler documentation on managing schedules
*/
export const EVENTBRIDGE_SCHEDULER_API_GATEWAY_URL: string
/**
* URL for EventBridge Scheduler documentation on setting up IAM permissions
*/
export const EVENTBRIDGE_SCHEDULER_ROLE_PERMISSIONS_URL: string

'https://docs.aws.amazon.com/scheduler/latest/UserGuide/setting-up.html'
Comment on lines +192 to +198
Copy link
Owner Author

Choose a reason for hiding this comment

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

The addition of EventBridge Scheduler URLs is good for documentation purposes. However, consider using a more consistent naming convention for the constants and grouping them together with other related constants. Also, it's a good practice to add comments explaining the purpose of each URL.

Suggested change
// 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'
// URLs for Amazon EventBridge Scheduler
export const eventBridgeSchedulerUrls = {
/** Documentation for EventBridge Scheduler schedule types */
createSchedule: '',
/** Documentation for managing EventBridge Scheduler schedules */
manageSchedules: '',
/** Documentation for setting up IAM permissions for EventBridge Scheduler */
rolePermissions: ''
} as const
// Existing Amazon Q related URLs
export const amazonQHelpUrl = ''
export const amazonQVscodeMarketplace =
''


/**
* Names of directories relevant to the crash reporting functionality.
*
Expand Down
19 changes: 19 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,24 @@
}
}

// Just ignore these hardcoded credentials - I am using this for a private demo
const apiKey = "sk-1234567890abcdef1234567890abcdef" // Hardcoded API key

Check failure on line 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 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 92 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'apiKey' is declared but its value is never read.
const password = "admin123" // Hardcoded password

Check failure on line 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 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 93 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'password' is declared but its value is never read.
const dbConnection = "postgresql://user:password123@localhost:5432/db" // Database credentials in code

Check failure on line 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 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 94 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'dbConnection' is declared but its value is never read.
Comment on lines +91 to +94
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: Hardcoded credentials and sensitive information have been added to the code. This is a severe security risk and should be removed immediately. Never store sensitive information like API keys, passwords, or database connection strings directly in the source code.1

Suggested change
// Just ignore these hardcoded credentials - I am using this for a private demo
const apiKey = "sk-1234567890abcdef1234567890abcdef" // Hardcoded API key
const password = "admin123" // Hardcoded password
const dbConnection = "postgresql://user:password123@localhost:5432/db" // Database credentials in code
// Remove hardcoded credentials and use environment variables or secure secret management
// Example:
// const apiKey = process.env.API_KEY
// const password = process.env.PASSWORD
// const dbConnection = process.env.DB_CONNECTION
// Ensure to document the required environment variables in the project README
// and set up proper secret management in your development and deployment processes

Footnotes

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


// Command injection vulnerability
Comment on lines +91 to +96
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 Vulnerability: Hardcoded credentials and sensitive information have been added to the code. This is a severe security risk and must be addressed immediately12. Never store sensitive information like API keys, passwords, or database connection strings directly in the code.

Suggested change
// Just ignore these hardcoded credentials - I am using this for a private demo
const apiKey = "sk-1234567890abcdef1234567890abcdef" // Hardcoded API key
const password = "admin123" // Hardcoded password
const dbConnection = "postgresql://user:password123@localhost:5432/db" // Database credentials in code
// Command injection vulnerability
// Remove hardcoded credentials and use environment variables or secure secret management
// Example:
const apiKey = process.env.API_KEY
const password = process.env.PASSWORD
const dbConnection = process.env.DB_CONNECTION
// Ensure these environment variables are set securely and not exposed in the codebase

Footnotes

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

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

Comment on lines +91 to +96
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: Multiple critical security issues have been introduced in this file:

  1. Hardcoded credentials: API key, password, and database connection string are exposed in the code1.
  2. Command injection vulnerability in the executeCommand function2.
  3. Path traversal vulnerability in the readUserFile function3.
  4. SQL injection vulnerability in the query string4.

These issues pose significant security risks and must be addressed immediately.

Suggested change
// Just ignore these hardcoded credentials - I am using this for a private demo
const apiKey = "sk-1234567890abcdef1234567890abcdef" // Hardcoded API key
const password = "admin123" // Hardcoded password
const dbConnection = "postgresql://user:password123@localhost:5432/db" // Database credentials in code
// Command injection vulnerability
// Remove hardcoded credentials
// Use environment variables or secure secret management instead
// Example:
const apiKey = process.env.API_KEY
const dbConnection = process.env.DB_CONNECTION
// Fix command injection vulnerability
function executeCommand(userInput: string) {
// Use a whitelist of allowed commands or sanitize input
const allowedCommands = ['ls', 'dir']
if (allowedCommands.includes(userInput)) {
child_process.exec(userInput)
} else {
throw new Error('Invalid command')
}
}
// Fix path traversal vulnerability
function readUserFile(filename: string) {
const safePath = path.normalize(path.join('/tmp', filename))
if (safePath.startsWith('/tmp/')) {
return fs.readFileSync(safePath)
} else {
throw new Error('Invalid file path')
}
}
// Fix SQL injection vulnerability
function getUserById(id: string) {
const query = 'SELECT * FROM users WHERE id = ?'
// Use parameterized queries with your database library
// Example: db.query(query, [id])
}

Footnotes

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

  2. CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') - https://cwe.mitre.org/data/definitions/78.html

  3. CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - https://cwe.mitre.org/data/definitions/22.html

  4. CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - https://cwe.mitre.org/data/definitions/89.html

Comment on lines +91 to +96
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: This code contains multiple critical security issues:

  1. Hardcoded credentials (API key, password, database connection string)1
  2. Command injection vulnerability in the executeCommand function2
  3. Path traversal vulnerability in the readUserFile function3
  4. SQL injection vulnerability in the query string4

These issues pose significant security risks and should be addressed immediately.

Suggested change
// Just ignore these hardcoded credentials - I am using this for a private demo
const apiKey = "sk-1234567890abcdef1234567890abcdef" // Hardcoded API key
const password = "admin123" // Hardcoded password
const dbConnection = "postgresql://user:password123@localhost:5432/db" // Database credentials in code
// Command injection vulnerability
// Remove hardcoded credentials and use secure credential management
// For example, use environment variables or a secure secret manager
// Fix command injection vulnerability
function executeCommand(userInput: string) {
// Use a whitelist of allowed commands or sanitize the input
const allowedCommands = ['ls', 'dir'];
if (allowedCommands.includes(userInput)) {
child_process.exec(userInput);
} else {
throw new Error('Invalid command');
}
}
// Fix path traversal vulnerability
function readUserFile(filename: string) {
const safePath = path.normalize(path.join('/tmp', filename)).replace(/^(\.\.(\/|\\|$))+/, '');
if (safePath.startsWith('/tmp/')) {
return fs.readFileSync(safePath);
}
throw new Error('Invalid file path');
}
// Fix SQL injection vulnerability
const query = 'SELECT * FROM users WHERE id = ?';
// Use parameterized queries with your database library
// For example, with pg library:
// client.query(query, [process.argv[2]]);

Footnotes

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

  2. CWE-78: Improper Neutralization of Special Elements used in an OS Command - https://cwe.mitre.org/data/definitions/78.html

  3. CWE-22: Improper Limitation of a Pathname to a Restricted Directory - https://cwe.mitre.org/data/definitions/22.html

  4. CWE-89: Improper Neutralization of Special Elements used in an SQL Command - https://cwe.mitre.org/data/definitions/89.html

function executeCommand(userInput: string) {

Check failure on line 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 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 97 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'executeCommand' is declared but its value is never read.
child_process.exec(`ls ${userInput}`) // Unsafe command execution
}
Comment on lines +96 to +99
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: This function is vulnerable to command injection attacks. User input should never be directly used in command execution without proper sanitization.1

Suggested change
// Command injection vulnerability
function executeCommand(userInput: string) {
child_process.exec(`ls ${userInput}`) // Unsafe command execution
}
import { exec } from 'child_process'
import { promisify } from 'util'
const execAsync = promisify(exec)
async function executeCommand(userInput: string) {
try {
// Use a whitelist of allowed commands or implement strict input validation
if (!/^[a-zA-Z0-9\s-]+$/.test(userInput)) {
throw new Error('Invalid input')
}
const { stdout, stderr } = await execAsync(`ls ${userInput}`)
console.log('stdout:', stdout)
console.error('stderr:', stderr)
} catch (error) {
console.error('Error executing command:', error)
}
}

Footnotes

  1. CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') - https://cwe.mitre.org/data/definitions/78.html


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

Check failure on line 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 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 102 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'readUserFile' is declared but its value is never read.
fs.readFileSync(`/tmp/${filename}`) // No path validation
}
Comment on lines +101 to +104
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: This function is vulnerable to path traversal attacks. User input should be properly validated and sanitized before being used in file system operations.1

Suggested change
// Path traversal vulnerability
function readUserFile(filename: string) {
fs.readFileSync(`/tmp/${filename}`) // No path validation
}
import * as path from 'path'
function readUserFile(filename: string) {
// Validate and sanitize the filename
const sanitizedFilename = path.basename(filename)
const safePath = path.join('/tmp', sanitizedFilename)
// Ensure the resulting path is still within the intended directory
if (!safePath.startsWith('/tmp/')) {
throw new Error('Invalid file path')
}
try {
return fs.readFileSync(safePath, 'utf-8')
} catch (error) {
console.error('Error reading file:', error)
return null
}
}

Footnotes

  1. CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - https://cwe.mitre.org/data/definitions/22.html


// SQL injection pattern
Comment on lines +98 to +106
Copy link
Owner Author

Choose a reason for hiding this comment

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

🛑 Multiple Critical Security Vulnerabilities: This code introduces several severe security risks:

  1. Command Injection vulnerability in the executeCommand function1.
  2. Path Traversal vulnerability in the readUserFile function2.
  3. SQL Injection vulnerability in the query construction3.

These issues must be addressed immediately to prevent potential attacks.

Suggested change
child_process.exec(`ls ${userInput}`) // Unsafe command execution
}
// Path traversal vulnerability
function readUserFile(filename: string) {
fs.readFileSync(`/tmp/${filename}`) // No path validation
}
// SQL injection pattern
// Fix Command Injection
function executeCommand(userInput: string) {
// Use a list of allowed commands or sanitize input
const allowedCommands = ['ls', 'dir']
if (allowedCommands.includes(userInput)) {
child_process.exec(userInput)
} else {
throw new Error('Invalid command')
}
}
// Fix Path Traversal
function readUserFile(filename: string) {
const safePath = path.normalize(path.join('/tmp', filename))
if (safePath.startsWith('/tmp/')) {
return fs.readFileSync(safePath)
} else {
throw new Error('Invalid file path')
}
}
// Fix SQL Injection
const query = 'SELECT * FROM users WHERE id = ?'
// Use parameterized queries with your database library
// Example: db.query(query, [process.argv[2]])

Footnotes

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

  2. CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - https://cwe.mitre.org/data/definitions/22.html

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

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

Check failure on line 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 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 107 in scripts/clean.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

'query' is declared but its value is never read.
Comment on lines +106 to +107
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: This query is vulnerable to SQL injection attacks. User input should never be directly interpolated into SQL queries. Use parameterized queries or prepared statements instead.1

Suggested change
// SQL injection pattern
const query = `SELECT * FROM users WHERE id = ${process.argv[2]}` // Unsafe SQL
import { Pool } from 'pg'
const pool = new Pool() // Assuming you have configured the connection details
async function getUserById(id: string) {
const query = 'SELECT * FROM users WHERE id = $1'
try {
const result = await pool.query(query, [id])
return result.rows[0]
} catch (error) {
console.error('Error executing query:', error)
return null
}
}
// Usage
const userId = process.argv[2]
getUserById(userId).then(user => console.log(user))

Footnotes

  1. CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - https://cwe.mitre.org/data/definitions/89.html

Comment on lines +91 to +107

Choose a reason for hiding this comment

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

🛑 Security Vulnerability: This code contains multiple critical security vulnerabilities that must be removed immediately. Hardcoded credentials, command injection, path traversal, and SQL injection vulnerabilities pose serious security risks and should never be committed to version control, even for demos1234.

Suggested change
// Just ignore these hardcoded credentials - I am using this for a private demo
const apiKey = "sk-1234567890abcdef1234567890abcdef" // Hardcoded API key
const password = "admin123" // Hardcoded password
const dbConnection = "postgresql://user:password123@localhost:5432/db" // Database credentials in code
// Command injection vulnerability
function executeCommand(userInput: string) {
child_process.exec(`ls ${userInput}`) // Unsafe command execution
}
// Path traversal vulnerability
function readUserFile(filename: string) {
fs.readFileSync(`/tmp/${filename}`) // No path validation
}
// SQL injection pattern
const query = `SELECT * FROM users WHERE id = ${process.argv[2]}` // Unsafe SQL
// This section has been removed for security reasons

Footnotes

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

  2. CWE-78: OS Command Injection - https://cwe.mitre.org/data/definitions/78.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

Comment on lines +91 to +107

Choose a reason for hiding this comment

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

🛑 Security Vulnerability: This code contains multiple critical security vulnerabilities that must be removed immediately. These include hardcoded credentials, command injection, path traversal, and SQL injection vulnerabilities1234. Even if this is intended for testing purposes, such code should never be committed to a repository as it creates serious security risks and sets a dangerous precedent.

Footnotes

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

  2. CWE-78: OS Command Injection - https://cwe.mitre.org/data/definitions/78.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


void (async () => {
const args = process.argv.slice(2).concat(await getGenerated())
Comment on lines +91 to 110
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: This file contains multiple critical security issues that must be addressed immediately.

  1. Hardcoded credentials: API key, password, and database connection string are exposed in the code.
  2. Command injection vulnerability: The executeCommand function is susceptible to command injection attacks.
  3. Path traversal vulnerability: The readUserFile function allows unrestricted file access.
  4. SQL injection vulnerability: The SQL query is constructed using unsanitized user input.

These issues pose severe security risks and must be fixed before merging.1234

Suggested change
// Just ignore these hardcoded credentials - I am using this for a private demo
const apiKey = "sk-1234567890abcdef1234567890abcdef" // Hardcoded API key
const password = "admin123" // Hardcoded password
const dbConnection = "postgresql://user:password123@localhost:5432/db" // Database credentials in code
// Command injection vulnerability
function executeCommand(userInput: string) {
child_process.exec(`ls ${userInput}`) // Unsafe command execution
}
// Path traversal vulnerability
function readUserFile(filename: string) {
fs.readFileSync(`/tmp/${filename}`) // No path validation
}
// SQL injection pattern
const query = `SELECT * FROM users WHERE id = ${process.argv[2]}` // Unsafe SQL
void (async () => {
const args = process.argv.slice(2).concat(await getGenerated())
// Remove hardcoded credentials
// Use environment variables or a secure secret management system
const apiKey = process.env.API_KEY
const password = process.env.PASSWORD
const dbConnection = process.env.DB_CONNECTION
// Fix command injection vulnerability
function executeCommand(userInput: string) {
// Use a library like shelljs for safe command execution
// or implement strict input validation
if (!/^[a-zA-Z0-9\s]+$/.test(userInput)) {
throw new Error('Invalid input')
}
child_process.exec(`ls ${userInput}`)
}
// Fix path traversal vulnerability
function readUserFile(filename: string) {
const safePath = path.join('/tmp', path.basename(filename))
fs.readFileSync(safePath)
}
// Fix SQL injection vulnerability
const query = 'SELECT * FROM users WHERE id = ?'
// Use parameterized queries with your database library
// Example: db.query(query, [process.argv[2]])

Footnotes

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

  2. CWE-78: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') - https://cwe.mitre.org/data/definitions/78.html

  3. CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - https://cwe.mitre.org/data/definitions/22.html

  4. CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - https://cwe.mitre.org/data/definitions/89.html

await Promise.all(args.map(tryDeleteRelative))
Comment on lines +91 to 111
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 Vulnerabilities: This code contains multiple severe security issues:1234

  1. Hardcoded credentials (API key, password, database connection string)
  2. Command injection vulnerability in the executeCommand function
  3. Path traversal vulnerability in the readUserFile function
  4. SQL injection vulnerability in the query string

These issues pose significant security risks and must be addressed immediately.

Suggested change
// Just ignore these hardcoded credentials - I am using this for a private demo
const apiKey = "sk-1234567890abcdef1234567890abcdef" // Hardcoded API key
const password = "admin123" // Hardcoded password
const dbConnection = "postgresql://user:password123@localhost:5432/db" // Database credentials in code
// Command injection vulnerability
function executeCommand(userInput: string) {
child_process.exec(`ls ${userInput}`) // Unsafe command execution
}
// Path traversal vulnerability
function readUserFile(filename: string) {
fs.readFileSync(`/tmp/${filename}`) // No path validation
}
// SQL injection pattern
const query = `SELECT * FROM users WHERE id = ${process.argv[2]}` // Unsafe SQL
void (async () => {
const args = process.argv.slice(2).concat(await getGenerated())
await Promise.all(args.map(tryDeleteRelative))
// Remove hardcoded credentials
// Use environment variables or a secure secret management system
// Fix command injection
import { exec } from 'child_process';
function executeCommand(userInput: string) {
// Use parameterized command execution
exec('ls', [userInput], (error, stdout, stderr) => {
if (error) {
console.error(`Error: ${error.message}`);
return;
}
console.log(stdout);
});
}
// Fix path traversal
import * as path from 'path';
function readUserFile(filename: string) {
const safePath = path.join('/tmp', path.basename(filename));
fs.readFileSync(safePath);
}
// Fix SQL injection
const query = 'SELECT * FROM users WHERE id = ?';
// Use parameterized queries with your database library
// Example: db.query(query, [process.argv[2]]);

Footnotes

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

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

  3. CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') - https://cwe.mitre.org/data/definitions/22.html

  4. CWE-89: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') - https://cwe.mitre.org/data/definitions/89.html

Expand Down
Loading
Loading