| | | 1 | | import { inject, injectable } from 'inversify'; |
| | | 2 | | import pc from 'picocolors'; |
| | | 3 | | import { EnvironmentVariable } from '../../domain/EnvironmentVariable.js'; |
| | | 4 | | import { |
| | | 5 | | EnvironmentFileError, |
| | | 6 | | InvalidArgumentError, |
| | | 7 | | } from '../../domain/errors/DomainErrors.js'; |
| | | 8 | | import { |
| | | 9 | | decideMapFileUpdate, |
| | | 10 | | type MapFileTarget, |
| | | 11 | | } from '../../domain/MapFileUpdate.js'; |
| | | 12 | | import type { ILogger } from '../../domain/ports/ILogger.js'; |
| | | 13 | | import type { ISecretProvider } from '../../domain/ports/ISecretProvider.js'; |
| | | 14 | | import type { IVariableStore } from '../../domain/ports/IVariableStore.js'; |
| | | 15 | | import { TYPES } from '../../types.js'; |
| | | 16 | | import type { PushSingleCommand } from './PushSingleCommand.js'; |
| | | 17 | | |
| | | 18 | | /** A write to the map file, and what it held before so it can be undone. */ |
| | | 19 | | type MapFileChange = { |
| | | 20 | | mapFile: string; |
| | | 21 | | content: string; |
| | | 22 | | /** The text the file held before, or `null` when we create it. */ |
| | | 23 | | original: string | null; |
| | | 24 | | }; |
| | | 25 | | |
| | | 26 | | /** What to do to the map file once the secret is pushed, and what to report. */ |
| | | 27 | | type MapFilePlan = { |
| | | 28 | | /** Absent when the file needs no change. */ |
| | | 29 | | change?: MapFileChange; |
| | | 30 | | summary?: string; |
| | | 31 | | warning?: string; |
| | | 32 | | }; |
| | | 33 | | |
| | | 34 | | /** No map file: nothing to write and nothing to report. */ |
| | 13 | 35 | | const NO_MAP_FILE: MapFilePlan = {}; |
| | | 36 | | |
| | | 37 | | @injectable() |
| | 13 | 38 | | export class PushSingleCommandHandler { |
| | 13 | 39 | | private static readonly RULE = pc.magenta('\u2501'.repeat(60)); |
| | | 40 | | |
| | | 41 | | constructor( |
| | | 42 | | @inject(TYPES.ISecretProvider) |
| | 100 | 43 | | private readonly secretProvider: ISecretProvider, |
| | 100 | 44 | | @inject(TYPES.ILogger) private readonly logger: ILogger, |
| | | 45 | | @inject(TYPES.IVariableStore) |
| | 100 | 46 | | private readonly variableStore: IVariableStore, |
| | | 47 | | ) {} |
| | | 48 | | |
| | | 49 | | /** |
| | | 50 | | * Handles the PushSingleCommand which pushes a single environment variable to the secret store. |
| | | 51 | | * When the command names a map file, the mapping is recorded there first and |
| | | 52 | | * restored if the push fails, so the file never claims a secret that was not pushed. |
| | | 53 | | * |
| | | 54 | | * @param command - The PushSingleCommand containing key, value and secretPath |
| | | 55 | | */ |
| | | 56 | | async handle(command: PushSingleCommand): Promise<void> { |
| | 23 | 57 | | try { |
| | 23 | 58 | | const maskedPath = EnvironmentVariable.maskSecretPath(command.secretPath); |
| | | 59 | | |
| | 23 | 60 | | this.logger.info(`\n${pc.bold(pc.magenta('\u{1F4E4} PUSHING SECRET'))}`); |
| | 23 | 61 | | this.logger.info(PushSingleCommandHandler.RULE); |
| | 23 | 62 | | this.logger.info( |
| | | 63 | | ` ${pc.dim('\u2192 ')}${pc.bold(command.key)}${pc.dim(' \u2192 ')}${pc.dim(maskedPath)}`, |
| | | 64 | | ); |
| | | 65 | | |
| | 23 | 66 | | const envVariable = EnvironmentVariable.secret( |
| | | 67 | | command.key, |
| | | 68 | | command.value, |
| | | 69 | | ); |
| | | 70 | | |
| | 23 | 71 | | const plan = await this.planMapFileUpdate(command); |
| | 20 | 72 | | try { |
| | 20 | 73 | | await this.writeMapFile(plan); |
| | | 74 | | } catch (error) { |
| | | 75 | | // A write that fails midway can leave a truncated file behind. |
| | 2 | 76 | | await this.rollBackMapFile(plan, command.key); |
| | 2 | 77 | | throw error; |
| | | 78 | | } |
| | | 79 | | |
| | 18 | 80 | | try { |
| | 18 | 81 | | await this.secretProvider.setSecret(command.secretPath, command.value); |
| | | 82 | | } catch (error) { |
| | 5 | 83 | | await this.rollBackMapFile(plan, command.key); |
| | 5 | 84 | | throw error; |
| | | 85 | | } |
| | 13 | 86 | | this.logger.info( |
| | | 87 | | `\n${pc.bold(pc.green('\u2B50 SECRET PUSHED'))}${pc.dim( |
| | | 88 | | ' \u2014 ', |
| | | 89 | | )}${pc.bold(command.key)}${pc.dim('=')}${envVariable.maskedValue}${pc.dim( |
| | | 90 | | ' \u2192 ', |
| | | 91 | | )}${pc.dim(maskedPath)}\n`, |
| | | 92 | | ); |
| | 13 | 93 | | this.reportMapFile(plan); |
| | | 94 | | } catch (error) { |
| | | 95 | | const errorMessage = |
| | 10 | 96 | | error instanceof Error ? error.message : String(error); |
| | 10 | 97 | | this.logger.error( |
| | | 98 | | `Failed to push variable to secret store: ${errorMessage}`, |
| | | 99 | | ); |
| | 10 | 100 | | throw error; |
| | | 101 | | } |
| | | 102 | | } |
| | | 103 | | |
| | | 104 | | private async planMapFileUpdate( |
| | | 105 | | command: PushSingleCommand, |
| | | 106 | | ): Promise<MapFilePlan> { |
| | 22 | 107 | | const { mapFile, key, secretPath, target } = command; |
| | 22 | 108 | | if (mapFile === undefined) { |
| | 6 | 109 | | return NO_MAP_FILE; |
| | | 110 | | } |
| | | 111 | | |
| | 16 | 112 | | const original = await this.variableStore.readMapFileContent(mapFile); |
| | 16 | 113 | | const decision = decideMapFileUpdate( |
| | | 114 | | original, |
| | | 115 | | key, |
| | | 116 | | secretPath, |
| | | 117 | | target, |
| | | 118 | | mapFile, |
| | | 119 | | ); |
| | 16 | 120 | | switch (decision.kind) { |
| | | 121 | | case 'create': |
| | 7 | 122 | | return { |
| | | 123 | | change: { mapFile, original, content: decision.content }, |
| | | 124 | | summary: `Created ${mapFile}`, |
| | | 125 | | }; |
| | | 126 | | case 'append': |
| | 3 | 127 | | return { |
| | | 128 | | change: { mapFile, original, content: decision.content }, |
| | | 129 | | summary: `Added ${key} to ${mapFile}`, |
| | | 130 | | }; |
| | | 131 | | case 'unchanged': |
| | 2 | 132 | | return { |
| | | 133 | | summary: `${key} already mapped in ${mapFile}, no changes`, |
| | | 134 | | }; |
| | | 135 | | case 'targetMismatch': |
| | 2 | 136 | | return { |
| | | 137 | | warning: |
| | | 138 | | `\u26A0 ${mapFile} targets ${this.describeTarget(decision.fileTarget)}, ` + |
| | | 139 | | `but the secret was pushed to ${this.describeTarget(target)}. ` + |
| | | 140 | | 'The mapping was not added. Use --map=<file> to record it in a different map file.', |
| | | 141 | | }; |
| | | 142 | | case 'conflict': |
| | | 143 | | // Names the variable only: the existing path is not ours to echo. |
| | 1 | 144 | | throw new InvalidArgumentError( |
| | | 145 | | `${key} is already mapped to a different secret path in ${mapFile}. ` + |
| | | 146 | | 'Nothing was pushed. Update the mapping manually, ' + |
| | | 147 | | 'or use --no-map-update to push without recording it.', |
| | | 148 | | ); |
| | | 149 | | case 'invalidJson': |
| | 1 | 150 | | throw new EnvironmentFileError( |
| | | 151 | | `Invalid JSON in parameter map file: ${mapFile}`, |
| | | 152 | | ); |
| | | 153 | | } |
| | | 154 | | } |
| | | 155 | | |
| | | 156 | | private async writeMapFile({ change }: MapFilePlan): Promise<void> { |
| | 20 | 157 | | if (change === undefined) { |
| | 10 | 158 | | return; |
| | | 159 | | } |
| | 10 | 160 | | await this.variableStore.writeMapFileContent( |
| | | 161 | | change.mapFile, |
| | | 162 | | change.content, |
| | | 163 | | ); |
| | | 164 | | } |
| | | 165 | | |
| | | 166 | | private async rollBackMapFile( |
| | | 167 | | { change }: MapFilePlan, |
| | | 168 | | key: string, |
| | | 169 | | ): Promise<void> { |
| | 7 | 170 | | if (change === undefined) { |
| | 2 | 171 | | return; |
| | | 172 | | } |
| | 5 | 173 | | try { |
| | 5 | 174 | | await this.variableStore.restoreMapFile(change.mapFile, change.original); |
| | | 175 | | } catch { |
| | 1 | 176 | | this.logger.error( |
| | | 177 | | `Could not restore ${change.mapFile}. Remove ${key} from it manually.`, |
| | | 178 | | ); |
| | | 179 | | } |
| | | 180 | | } |
| | | 181 | | |
| | | 182 | | private reportMapFile({ summary, warning }: MapFilePlan): void { |
| | 13 | 183 | | if (warning !== undefined) { |
| | 2 | 184 | | this.logger.warn(pc.yellow(warning)); |
| | 2 | 185 | | return; |
| | | 186 | | } |
| | 11 | 187 | | if (summary !== undefined) { |
| | 6 | 188 | | this.logger.info(`${pc.green('\u2713')} ${summary}\n`); |
| | | 189 | | } |
| | | 190 | | } |
| | | 191 | | |
| | | 192 | | /** Provider and vault name only: a vault URL may carry credentials. */ |
| | | 193 | | private describeTarget(target: MapFileTarget): string { |
| | 4 | 194 | | if (target.provider !== 'azure' || !target.vaultUrl) { |
| | 2 | 195 | | return target.provider; |
| | | 196 | | } |
| | 2 | 197 | | try { |
| | 2 | 198 | | return `${target.provider} (${new URL(target.vaultUrl).hostname.split('.')[0]})`; |
| | | 199 | | } catch { |
| | 0 | 200 | | return target.provider; |
| | | 201 | | } |
| | | 202 | | } |
| | | 203 | | } |