-
-
Notifications
You must be signed in to change notification settings - Fork 121
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(cli): Add import sub commmand for project. (#594)
Co-authored-by: Rajdip Bhattacharya <[email protected]>
- Loading branch information
Showing
8 changed files
with
424 additions
and
369 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,184 @@ | ||
import type { | ||
CommandActionData, | ||
CommandArgument, | ||
CommandOption | ||
} from '@/types/command/command.types' | ||
import BaseCommand from '../base.command' | ||
import { confirm, text } from '@clack/prompts' | ||
import ControllerInstance from '@/util/controller-instance' | ||
import { Logger } from '@/util/logger' | ||
import fs from 'node:fs/promises' | ||
import path from 'node:path' | ||
import dotenv from 'dotenv' | ||
import secretDetector from '@keyshade/secret-scan' | ||
|
||
export default class ImportFromEnv extends BaseCommand { | ||
getName(): string { | ||
return 'import' | ||
} | ||
|
||
getDescription(): string { | ||
return 'Imports environment secrets and variables from .env file to a project.' | ||
} | ||
|
||
getArguments(): CommandArgument[] { | ||
return [ | ||
{ | ||
name: '<Project Slug>', | ||
description: 'Slug of the project where envs will be imported.' | ||
} | ||
] | ||
} | ||
|
||
getOptions(): CommandOption[] { | ||
return [ | ||
{ | ||
short: '-f', | ||
long: '--env-file <string>', | ||
description: 'Path to the .env file' | ||
} | ||
] | ||
} | ||
|
||
canMakeHttpRequests(): boolean { | ||
return true | ||
} | ||
|
||
async action({ args, options }: CommandActionData): Promise<void> { | ||
const [projectSlug] = args | ||
|
||
try { | ||
const parsedOptions = await this.parseOptions(options) | ||
if (!parsedOptions) return | ||
const envFileContent = await fs.readFile( | ||
parsedOptions.envFilePath, | ||
'utf-8' | ||
) | ||
|
||
const envVariables = dotenv.parse(envFileContent) | ||
if (Object.keys(envVariables).length === 0) { | ||
Logger.warn('No environment variables found in the provided file') | ||
return | ||
} | ||
|
||
const secretsAndVariables = secretDetector.scanJsObject(envVariables) | ||
|
||
Logger.info( | ||
'Detected secrets:\n' + | ||
Object.entries(secretsAndVariables.secrets) | ||
.map(([key, value]) => key + ' = ' + JSON.stringify(value)) | ||
.join('\n') + | ||
'\n' | ||
) | ||
Logger.info( | ||
'Detected variables:\n' + | ||
Object.entries(secretsAndVariables.variables) | ||
.map(([key, value]) => key + ' = ' + JSON.stringify(value)) | ||
.join('\n') | ||
) | ||
|
||
const confirmImport = await confirm({ | ||
message: | ||
'Do you want to proceed with importing the environment variables? (y/N)', | ||
initialValue: false | ||
}) | ||
|
||
if (!confirmImport) { | ||
Logger.info('Import cancelled by the user.') | ||
return | ||
} | ||
|
||
const environmentSlug = (await text({ | ||
message: 'Enter the environment slug to import to:' | ||
})) as string | ||
|
||
Logger.info( | ||
`Importing secrets and variables to project: ${projectSlug} and environment: ${environmentSlug} with default settings` | ||
) | ||
|
||
let noOfSecrets = 0 | ||
let noOfVariables = 0 | ||
const errors: string[] = [] | ||
for (const [key, value] of Object.entries(secretsAndVariables.secrets)) { | ||
const { error, success } = | ||
await ControllerInstance.getInstance().secretController.createSecret( | ||
{ | ||
projectSlug, | ||
name: key, | ||
entries: [ | ||
{ | ||
value, | ||
environmentSlug | ||
} | ||
] | ||
}, | ||
this.headers | ||
) | ||
|
||
if (success) { | ||
++noOfSecrets | ||
} else { | ||
errors.push( | ||
`Failed to create secret for ${key}. Error: ${error.message}.` | ||
) | ||
} | ||
} | ||
|
||
for (const [key, value] of Object.entries( | ||
secretsAndVariables.variables | ||
)) { | ||
const { error, success } = | ||
await ControllerInstance.getInstance().variableController.createVariable( | ||
{ | ||
projectSlug, | ||
name: key, | ||
entries: [ | ||
{ | ||
value, | ||
environmentSlug | ||
} | ||
] | ||
}, | ||
this.headers | ||
) | ||
|
||
if (success) { | ||
++noOfVariables | ||
} else { | ||
errors.push( | ||
`Failed to create variable for ${key}. Error: ${error.message}.` | ||
) | ||
} | ||
} | ||
Logger.info( | ||
`Imported ${noOfSecrets} secrets and ${noOfVariables} variables.` | ||
) | ||
if (errors.length) Logger.error(errors.join('\n')) | ||
} catch (error) { | ||
const errorMessage = (error as Error)?.message | ||
Logger.error( | ||
`Failed to import secrets and variables.${errorMessage ? '\n' + errorMessage : ''}` | ||
) | ||
} | ||
} | ||
|
||
private async parseOptions(options: CommandActionData['options']): Promise<{ | ||
envFilePath: string | ||
} | null> { | ||
const { envFile } = options | ||
if (!envFile) { | ||
Logger.error('No .env file path provided.') | ||
return null | ||
} | ||
const resolvedPath = path.resolve(envFile) | ||
const exists = await fs | ||
.access(resolvedPath) | ||
.then(() => true) | ||
.catch(() => false) | ||
if (!exists) { | ||
Logger.error(`The .env file does not exist at path: ${resolvedPath}`) | ||
return null | ||
} | ||
return { envFilePath: resolvedPath } | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,63 @@ | ||
import secretDetector from '@/index' | ||
import { aws, github, openAI } from '@/rules' | ||
|
||
describe('Dectect Secrets and Variables from Object', () => { | ||
it('should be able to differentiate variables from secrets', () => { | ||
const input = { | ||
GITHUB_KEY: github.testcases[0].input, | ||
AWS_KEY: aws.testcases[0].input, | ||
OPENAI_KEY: openAI.testcases[0].input, | ||
NEXT_PUBLIC_API_KEY: 'this-is-some-key', | ||
GOOGLE_ANALYTICS: 'UA-123456789-1', | ||
API_PORT: '3000' | ||
} | ||
const result = secretDetector.scanJsObject(input) | ||
expect(result.secrets).toEqual({ | ||
GITHUB_KEY: input.GITHUB_KEY, | ||
AWS_KEY: input.AWS_KEY, | ||
OPENAI_KEY: input.OPENAI_KEY | ||
}) | ||
expect(result.variables).toEqual({ | ||
NEXT_PUBLIC_API_KEY: input.NEXT_PUBLIC_API_KEY, | ||
GOOGLE_ANALYTICS: input.GOOGLE_ANALYTICS, | ||
API_PORT: input.API_PORT | ||
}) | ||
}) | ||
|
||
it('should return empty objects for secrets and variables when input is empty', () => { | ||
const input = {} | ||
const result = secretDetector.scanJsObject(input) | ||
expect(result.secrets).toEqual({}) | ||
expect(result.variables).toEqual({}) | ||
}) | ||
|
||
it('should return only variables when there are no secrets', () => { | ||
const input = { | ||
NEXT_PUBLIC_API_KEY: 'this-is-some-key', | ||
GOOGLE_ANALYTICS: 'UA-123456789-1', | ||
API_PORT: '3000' | ||
} | ||
const result = secretDetector.scanJsObject(input) | ||
expect(result.secrets).toEqual({}) | ||
expect(result.variables).toEqual({ | ||
NEXT_PUBLIC_API_KEY: input.NEXT_PUBLIC_API_KEY, | ||
GOOGLE_ANALYTICS: input.GOOGLE_ANALYTICS, | ||
API_PORT: input.API_PORT | ||
}) | ||
}) | ||
|
||
it('should return only secrets when there are no variables', () => { | ||
const input = { | ||
GITHUB_KEY: github.testcases[0].input, | ||
AWS_KEY: aws.testcases[0].input, | ||
OPENAI_KEY: openAI.testcases[0].input | ||
} | ||
const result = secretDetector.scanJsObject(input) | ||
expect(result.secrets).toEqual({ | ||
GITHUB_KEY: input.GITHUB_KEY, | ||
AWS_KEY: input.AWS_KEY, | ||
OPENAI_KEY: input.OPENAI_KEY | ||
}) | ||
expect(result.variables).toEqual({}) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.