-
Notifications
You must be signed in to change notification settings - Fork 5.2k
/
credentials.ts
234 lines (190 loc) · 6.37 KB
/
credentials.ts
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
import { Container } from 'typedi';
import { Flags } from '@oclif/core';
import { Cipher } from 'n8n-core';
import fs from 'fs';
import glob from 'fast-glob';
import type { EntityManager } from '@n8n/typeorm';
import * as Db from '@/Db';
import type { User } from '@db/entities/User';
import { SharedCredentials } from '@db/entities/SharedCredentials';
import { CredentialsEntity } from '@db/entities/CredentialsEntity';
import { disableAutoGeneratedIds } from '@db/utils/commandHelpers';
import { BaseCommand } from '../BaseCommand';
import type { ICredentialsEncrypted } from 'n8n-workflow';
import { ApplicationError, jsonParse } from 'n8n-workflow';
import { UM_FIX_INSTRUCTION } from '@/constants';
import { UserRepository } from '@db/repositories/user.repository';
export class ImportCredentialsCommand extends BaseCommand {
static description = 'Import credentials';
static examples = [
'$ n8n import:credentials --input=file.json',
'$ n8n import:credentials --separate --input=backups/latest/',
'$ n8n import:credentials --input=file.json --userId=1d64c3d2-85fe-4a83-a649-e446b07b3aae',
'$ n8n import:credentials --separate --input=backups/latest/ --userId=1d64c3d2-85fe-4a83-a649-e446b07b3aae',
];
static flags = {
help: Flags.help({ char: 'h' }),
input: Flags.string({
char: 'i',
description: 'Input file name or directory if --separate is used',
}),
separate: Flags.boolean({
description: 'Imports *.json files from directory provided by --input',
}),
userId: Flags.string({
description: 'The ID of the user to assign the imported credentials to',
}),
};
private transactionManager: EntityManager;
async init() {
disableAutoGeneratedIds(CredentialsEntity);
await super.init();
}
async run(): Promise<void> {
const { flags } = await this.parse(ImportCredentialsCommand);
if (!flags.input) {
this.logger.info('An input file or directory with --input must be provided');
return;
}
if (flags.separate) {
if (fs.existsSync(flags.input)) {
if (!fs.lstatSync(flags.input).isDirectory()) {
this.logger.info('The argument to --input must be a directory');
return;
}
}
}
const user = flags.userId ? await this.getAssignee(flags.userId) : await this.getOwner();
const credentials = await this.readCredentials(flags.input, flags.separate);
await Db.getConnection().transaction(async (transactionManager) => {
this.transactionManager = transactionManager;
const result = await this.checkRelations(credentials, flags.userId);
if (!result.success) {
throw new ApplicationError(result.message);
}
for (const credential of credentials) {
await this.storeCredential(credential, user);
}
});
this.reportSuccess(credentials.length);
}
async catch(error: Error) {
this.logger.error(
'An error occurred while importing credentials. See log messages for details.',
);
this.logger.error(error.message);
}
private reportSuccess(total: number) {
this.logger.info(
`Successfully imported ${total} ${total === 1 ? 'credential.' : 'credentials.'}`,
);
}
private async storeCredential(credential: Partial<CredentialsEntity>, user: User) {
if (!credential.nodesAccess) {
credential.nodesAccess = [];
}
const result = await this.transactionManager.upsert(CredentialsEntity, credential, ['id']);
const sharingExists = await this.transactionManager.existsBy(SharedCredentials, {
credentialsId: credential.id,
role: 'credential:owner',
});
if (!sharingExists) {
await this.transactionManager.upsert(
SharedCredentials,
{
credentialsId: result.identifiers[0].id as string,
userId: user.id,
role: 'credential:owner',
},
['credentialsId', 'userId'],
);
}
}
private async getOwner() {
const owner = await Container.get(UserRepository).findOneBy({ role: 'global:owner' });
if (!owner) {
throw new ApplicationError(`Failed to find owner. ${UM_FIX_INSTRUCTION}`);
}
return owner;
}
private async checkRelations(credentials: ICredentialsEncrypted[], userId?: string) {
if (!userId) {
return {
success: true as const,
message: undefined,
};
}
for (const credential of credentials) {
if (credential.id === undefined) {
continue;
}
if (!(await this.credentialExists(credential.id))) {
continue;
}
const ownerId = await this.getCredentialOwner(credential.id);
if (!ownerId) {
continue;
}
if (ownerId !== userId) {
return {
success: false as const,
message: `The credential with id "${credential.id}" is already owned by the user with the id "${ownerId}". It can't be re-owned by the user with the id "${userId}"`,
};
}
}
return {
success: true as const,
message: undefined,
};
}
private async readCredentials(path: string, separate: boolean): Promise<ICredentialsEncrypted[]> {
const cipher = Container.get(Cipher);
if (process.platform === 'win32') {
path = path.replace(/\\/g, '/');
}
let credentials: ICredentialsEncrypted[];
if (separate) {
const files = await glob('*.json', {
cwd: path,
absolute: true,
});
credentials = files.map((file) =>
jsonParse<ICredentialsEncrypted>(fs.readFileSync(file, { encoding: 'utf8' })),
);
} else {
const credentialsUnchecked = jsonParse<ICredentialsEncrypted[]>(
fs.readFileSync(path, { encoding: 'utf8' }),
);
if (!Array.isArray(credentialsUnchecked)) {
throw new ApplicationError(
'File does not seem to contain credentials. Make sure the credentials are contained in an array.',
);
}
credentials = credentialsUnchecked;
}
return credentials.map((credential) => {
if (typeof credential.data === 'object') {
// plain data / decrypted input. Should be encrypted first.
credential.data = cipher.encrypt(credential.data);
}
return credential;
});
}
private async getAssignee(userId: string) {
const user = await Container.get(UserRepository).findOneBy({ id: userId });
if (!user) {
throw new ApplicationError('Failed to find user', { extra: { userId } });
}
return user;
}
private async getCredentialOwner(credentialsId: string) {
const sharedCredential = await this.transactionManager.findOneBy(SharedCredentials, {
credentialsId,
role: 'credential:owner',
});
return sharedCredential?.userId;
}
private async credentialExists(credentialId: string) {
return await this.transactionManager.existsBy(CredentialsEntity, { id: credentialId });
}
}