Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: prevent potential dos backtrack issue due to trailing regex #89

Merged
merged 1 commit into from
Oct 26, 2024
Merged
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
18 changes: 16 additions & 2 deletions src/terraform-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,17 +115,31 @@ function isTerraformDirectory(dirPath: string): boolean {
* @returns {string} A valid Terraform module name based on the provided directory path.
*/
function getTerraformModuleNameFromRelativePath(terraformDirectory: string): string {
return terraformDirectory
// Use a loop to remove trailing dots without regex. Instead of using regex, this code iteratively
// checks each character from the end of the string. It decreases the endIndex until it finds a
// non-dot character. This approach runs in O(n) time, where n is the length of the string.
// It avoids the backtracking issues associated with regex patterns, making it more robust against
// potential DoS attacks.
const removeTrailingDots = (input: string) => {
let endIndex = input.length;
while (endIndex > 0 && input[endIndex - 1] === '.') {
endIndex--;
}
return input.slice(0, endIndex);
};

const cleanedDirectory = terraformDirectory
.trim() // Remove leading/trailing whitespace
.replace(/[^a-zA-Z0-9/_-]+/g, '-') // Remove invalid characters, allowing a-z, A-Z, 0-9, /, _, -
.replace(/\/{2,}/g, '/') // Replace multiple consecutive slashes with a single slash
.replace(/\/\.+/g, '/') // Remove slashes followed by dots
.replace(/(^\/|\/$)/g, '') // Remove leading/trailing slashes
.replace(/\.+$/, '') // Remove trailing dots
.replace(/\.\.+/g, '.') // Replace consecutive dots with a single dot
.replace(/--+/g, '-') // Replace consecutive hyphens with a single hyphen
.replace(/\s+/g, '') // Remove any remaining whitespace
.toLowerCase(); // All of our module names will be lowercase

return removeTrailingDots(cleanedDirectory);
}

/**
Expand Down