File size: 7,790 Bytes
aec3094 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 | import { Logger } from '@n8n/backend-common';
import { SettingsRepository } from '@n8n/db';
import { Service } from '@n8n/di';
import type { ValidationError } from 'class-validator';
import { validate } from 'class-validator';
import { rm as fsRm } from 'fs/promises';
import { Cipher, InstanceSettings } from 'n8n-core';
import { jsonParse, UnexpectedError } from 'n8n-workflow';
import { writeFile, chmod, readFile } from 'node:fs/promises';
import path from 'path';
import {
SOURCE_CONTROL_SSH_FOLDER,
SOURCE_CONTROL_GIT_FOLDER,
SOURCE_CONTROL_SSH_KEY_NAME,
SOURCE_CONTROL_PREFERENCES_DB_KEY,
} from './constants';
import { generateSshKeyPair, isSourceControlLicensed } from './source-control-helper.ee';
import { SourceControlConfig } from './source-control.config';
import type { KeyPairType } from './types/key-pair-type';
import { SourceControlPreferences } from './types/source-control-preferences';
@Service()
export class SourceControlPreferencesService {
private _sourceControlPreferences: SourceControlPreferences = new SourceControlPreferences();
readonly sshKeyName: string;
readonly sshFolder: string;
readonly gitFolder: string;
constructor(
private readonly instanceSettings: InstanceSettings,
private readonly logger: Logger,
private readonly cipher: Cipher,
private readonly settingsRepository: SettingsRepository,
private readonly sourceControlConfig: SourceControlConfig,
) {
this.sshFolder = path.join(instanceSettings.n8nFolder, SOURCE_CONTROL_SSH_FOLDER);
this.gitFolder = path.join(instanceSettings.n8nFolder, SOURCE_CONTROL_GIT_FOLDER);
this.sshKeyName = path.join(this.sshFolder, SOURCE_CONTROL_SSH_KEY_NAME);
}
get sourceControlPreferences(): SourceControlPreferences {
return {
...this._sourceControlPreferences,
connected: this._sourceControlPreferences.connected ?? false,
};
}
// merge the new preferences with the existing preferences when setting
set sourceControlPreferences(preferences: Partial<SourceControlPreferences>) {
this._sourceControlPreferences = SourceControlPreferences.merge(
preferences,
this._sourceControlPreferences,
);
}
isSourceControlSetup() {
return (
this.isSourceControlLicensedAndEnabled() &&
this.getPreferences().repositoryUrl &&
this.getPreferences().branchName
);
}
private async getKeyPairFromDatabase() {
const dbSetting = await this.settingsRepository.findByKey('features.sourceControl.sshKeys');
if (!dbSetting?.value) return null;
type KeyPair = { publicKey: string; encryptedPrivateKey: string };
return jsonParse<KeyPair | null>(dbSetting.value, { fallbackValue: null });
}
private async getPrivateKeyFromDatabase() {
const dbKeyPair = await this.getKeyPairFromDatabase();
if (!dbKeyPair) throw new UnexpectedError('Failed to find key pair in database');
return this.cipher.decrypt(dbKeyPair.encryptedPrivateKey);
}
private async getPublicKeyFromDatabase() {
const dbKeyPair = await this.getKeyPairFromDatabase();
if (!dbKeyPair) throw new UnexpectedError('Failed to find key pair in database');
return dbKeyPair.publicKey;
}
async getPrivateKeyPath() {
const dbPrivateKey = await this.getPrivateKeyFromDatabase();
const tempFilePath = path.join(this.instanceSettings.n8nFolder, 'ssh_private_key_temp');
await writeFile(tempFilePath, dbPrivateKey);
await chmod(tempFilePath, 0o600);
return tempFilePath;
}
async getPublicKey() {
try {
const dbPublicKey = await this.getPublicKeyFromDatabase();
if (dbPublicKey) return dbPublicKey;
return await readFile(this.sshKeyName + '.pub', { encoding: 'utf8' });
} catch (e) {
const error = e instanceof Error ? e : new Error(`${e}`);
this.logger.error(`Failed to read SSH public key: ${error.message}`);
}
return '';
}
async deleteKeyPair() {
try {
await fsRm(this.sshFolder, { recursive: true });
await this.settingsRepository.delete({ key: 'features.sourceControl.sshKeys' });
} catch (e) {
const error = e instanceof Error ? e : new Error(`${e}`);
this.logger.error(`Failed to delete SSH key pair: ${error.message}`);
}
}
/**
* Generate an SSH key pair and write it to the database, overwriting any existing key pair.
*/
async generateAndSaveKeyPair(keyPairType?: KeyPairType): Promise<SourceControlPreferences> {
if (!keyPairType) {
keyPairType =
this.getPreferences().keyGeneratorType ?? this.sourceControlConfig.defaultKeyPairType;
}
const keyPair = await generateSshKeyPair(keyPairType);
try {
await this.settingsRepository.save({
key: 'features.sourceControl.sshKeys',
value: JSON.stringify({
encryptedPrivateKey: this.cipher.encrypt(keyPair.privateKey),
publicKey: keyPair.publicKey,
}),
loadOnStartup: true,
});
} catch (error) {
throw new UnexpectedError('Failed to write key pair to database', { cause: error });
}
// update preferences only after generating key pair to prevent endless loop
if (keyPairType !== this.getPreferences().keyGeneratorType) {
await this.setPreferences({ keyGeneratorType: keyPairType });
}
return this.getPreferences();
}
isBranchReadOnly(): boolean {
return this._sourceControlPreferences.branchReadOnly;
}
isSourceControlConnected(): boolean {
return this.sourceControlPreferences.connected;
}
isSourceControlLicensedAndEnabled(): boolean {
return this.isSourceControlConnected() && isSourceControlLicensed();
}
getBranchName(): string {
return this.sourceControlPreferences.branchName;
}
getPreferences(): SourceControlPreferences {
return this.sourceControlPreferences;
}
async validateSourceControlPreferences(
preferences: Partial<SourceControlPreferences>,
allowMissingProperties = true,
): Promise<ValidationError[]> {
const preferencesObject = new SourceControlPreferences(preferences);
const validationResult = await validate(preferencesObject, {
forbidUnknownValues: false,
skipMissingProperties: allowMissingProperties,
stopAtFirstError: false,
validationError: { target: false },
});
if (validationResult.length > 0) {
throw new UnexpectedError('Invalid source control preferences', {
extra: { preferences: validationResult },
});
}
return validationResult;
}
async setPreferences(
preferences: Partial<SourceControlPreferences>,
saveToDb = true,
): Promise<SourceControlPreferences> {
const noKeyPair = (await this.getKeyPairFromDatabase()) === null;
if (noKeyPair) await this.generateAndSaveKeyPair();
this.sourceControlPreferences = preferences;
if (saveToDb) {
const settingsValue = JSON.stringify(this._sourceControlPreferences);
try {
await this.settingsRepository.save(
{
key: SOURCE_CONTROL_PREFERENCES_DB_KEY,
value: settingsValue,
loadOnStartup: true,
},
{ transaction: false },
);
} catch (error) {
throw new UnexpectedError('Failed to save source control preferences', { cause: error });
}
}
return this.sourceControlPreferences;
}
async loadFromDbAndApplySourceControlPreferences(): Promise<
SourceControlPreferences | undefined
> {
const loadedPreferences = await this.settingsRepository.findOne({
where: { key: SOURCE_CONTROL_PREFERENCES_DB_KEY },
});
if (loadedPreferences) {
try {
const preferences = jsonParse<SourceControlPreferences>(loadedPreferences.value);
if (preferences) {
// set local preferences but don't write back to db
await this.setPreferences(preferences, false);
return preferences;
}
} catch (error) {
this.logger.warn(
`Could not parse Source Control settings from database: ${(error as Error).message}`,
);
}
}
await this.setPreferences(new SourceControlPreferences(), true);
return this.sourceControlPreferences;
}
}
|