forked from salto-io/salto
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathadapter_creator.ts
270 lines (247 loc) · 9.77 KB
/
adapter_creator.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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
/*
* Copyright 2023 Salto Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Adapter, BuiltinTypes, ElemID, InstanceElement, ObjectType, AdapterInstallResult, AdapterOperationsContext, AdapterOperations } from '@salto-io/adapter-api'
import { regex } from '@salto-io/lowerdash'
import { logger } from '@salto-io/logging'
import _ from 'lodash'
import { SdkDownloadService } from '@salto-io/suitecloud-cli'
import Bottleneck from 'bottleneck'
import { CLIENT_CONFIG, CONFIG, configType, DEFAULT_CONCURRENCY, NetsuiteConfig, validateDeployParams, validateFetchConfig } from './config'
import { NETSUITE } from './constants'
import { validateFetchParameters, convertToQueryParams, validateNetsuiteQueryParameters, validateArrayOfStrings, validatePlainObject, FETCH_PARAMS } from './query'
import { Credentials, isSdfCredentialsOnly, isSuiteAppCredentials, toCredentialsAccountId } from './client/credentials'
import SuiteAppClient from './client/suiteapp_client/suiteapp_client'
import SdfClient from './client/sdf_client'
import NetsuiteClient from './client/client'
import NetsuiteAdapter from './adapter'
const log = logger(module)
const configID = new ElemID(NETSUITE)
// Taken from https://github.com/salto-io/netsuite-suitecloud-sdk/blob/e009e0eefcd918635353d093be6a6c2222d223b8/packages/node-cli/src/validation/InteractiveAnswersValidator.js#L27
const SUITEAPP_ID_FORMAT_REGEX = /^[a-z0-9]+(\.[a-z0-9]+){2}$/
// The SuiteApp fields are commented out until we will be ready to expose them to the user
export const defaultCredentialsType = new ObjectType({
elemID: configID,
fields: {
accountId: {
refType: BuiltinTypes.STRING,
annotations: { message: 'Account ID' },
},
tokenId: {
refType: BuiltinTypes.STRING,
annotations: { message: 'SDF Token ID' },
},
tokenSecret: {
refType: BuiltinTypes.STRING,
annotations: { message: 'SDF Token Secret' },
},
suiteAppTokenId: {
refType: BuiltinTypes.STRING,
annotations: {
message: 'Salto SuiteApp Token ID (optional)',
},
},
suiteAppTokenSecret: {
refType: BuiltinTypes.STRING,
annotations: {
message: 'Salto SuiteApp Token Secret (optional)',
},
},
suiteAppActivationKey: {
refType: BuiltinTypes.STRING,
annotations: {
message: 'Salto SuiteApp Activation Key (optional)',
},
},
},
annotationRefsOrTypes: {},
annotations: {},
})
const validateInstalledSuiteApps = (installedSuiteApps: unknown): void => {
validateArrayOfStrings(installedSuiteApps, [CONFIG.client, CLIENT_CONFIG.installedSuiteApps])
const invalidValues = installedSuiteApps.filter(id => !SUITEAPP_ID_FORMAT_REGEX.test(id))
if (invalidValues.length !== 0) {
throw new Error(`${CLIENT_CONFIG.installedSuiteApps} values should contain only lowercase characters or numbers and exactly two dots (such as com.saltoio.salto). The following values are invalid: ${invalidValues.join(', ')}`)
}
}
const validateRegularExpressions = (regularExpressions: string[]): void => {
const invalidRegularExpressions = regularExpressions
.filter(strRegex => !regex.isValidRegex(strRegex))
if (!_.isEmpty(invalidRegularExpressions)) {
const errMessage = `received an invalid ${CONFIG.filePathRegexSkipList} value. The following regular expressions are invalid: ${invalidRegularExpressions}`
throw new Error(errMessage)
}
}
function validateConfig(config: Record<string, unknown>): asserts config is NetsuiteConfig {
const {
fetch,
fetchTarget,
skipList, // support deprecated version
deploy,
client,
filePathRegexSkipList,
typesToSkip,
} = _.pick(config, Object.values(CONFIG))
if (filePathRegexSkipList !== undefined) {
validateArrayOfStrings(filePathRegexSkipList, CONFIG.filePathRegexSkipList)
validateRegularExpressions(filePathRegexSkipList)
}
if (typesToSkip !== undefined) {
validateArrayOfStrings(typesToSkip, CONFIG.typesToSkip)
}
if (client !== undefined) {
validatePlainObject(client, CONFIG.client)
const {
fetchAllTypesAtOnce,
installedSuiteApps,
} = _.pick(client, Object.values(CLIENT_CONFIG))
if (fetchAllTypesAtOnce && fetchTarget !== undefined) {
log.warn(`${CLIENT_CONFIG.fetchAllTypesAtOnce} is not supported with ${CONFIG.fetchTarget}. Ignoring ${CLIENT_CONFIG.fetchAllTypesAtOnce}`)
client[CLIENT_CONFIG.fetchAllTypesAtOnce] = false
}
if (installedSuiteApps !== undefined) {
validateInstalledSuiteApps(installedSuiteApps)
}
}
if (fetchTarget !== undefined) {
validatePlainObject(fetchTarget, CONFIG.fetchTarget)
validateNetsuiteQueryParameters(fetchTarget, CONFIG.fetchTarget)
validateFetchParameters(convertToQueryParams(fetchTarget))
}
if (skipList !== undefined) {
validatePlainObject(skipList, CONFIG.skipList)
validateNetsuiteQueryParameters(skipList, CONFIG.skipList)
validateFetchParameters(convertToQueryParams(skipList))
}
if (fetch !== undefined) {
validatePlainObject(fetch, CONFIG.fetch)
validateFetchConfig(fetch)
}
if (deploy !== undefined) {
validatePlainObject(deploy, CONFIG.deploy)
validateDeployParams(deploy)
}
}
const netsuiteConfigFromConfig = (
configInstance: Readonly<InstanceElement> | undefined
): NetsuiteConfig => {
try {
if (!configInstance) {
return {}
}
const { value: config } = configInstance
validateConfig(config)
log.debug('using netsuite adapter config: %o', {
...config,
fetch: _.omit(config.fetch, FETCH_PARAMS.lockedElementsToExclude),
})
return _.pickBy(config, (_value, key) => {
if (key in CONFIG) {
return true
}
log.debug('Unknown config property was found: %s', key)
return false
})
} catch (e) {
e.message = `Failed to load Netsuite config: ${e.message}`
log.error(e.message)
throw e
}
}
const throwOnMissingSuiteAppLoginCreds = (credentials: Credentials): void => {
if (isSdfCredentialsOnly(credentials)) {
return
}
// suiteAppActivationKey may be undefined but empty string is forbidden
if (isSuiteAppCredentials(credentials) && credentials.suiteAppActivationKey !== '') {
return
}
const undefinedBaseCreds = [
{ key: 'suiteAppTokenId', value: credentials.suiteAppTokenId },
{ key: 'suiteAppTokenSecret', value: credentials.suiteAppTokenSecret },
].filter(item => !item.value).map(item => item.key)
const undefinedCreds = undefinedBaseCreds.concat(credentials.suiteAppActivationKey === '' ? ['suiteAppActivationKey'] : [])
throw new Error(`Missing SuiteApp login creds: ${undefinedCreds.join(', ')}. Please login again.`)
}
const netsuiteCredentialsFromCredentials = (
credsInstance: Readonly<InstanceElement>
): Credentials => {
const throwOnInvalidAccountId = (credentials: Credentials): void => {
const isValidAccountIdFormat = /^[A-Za-z0-9_\\-]+$/.test(credentials.accountId)
if (!isValidAccountIdFormat) {
throw new Error(`received an invalid accountId value: (${credsInstance.value.accountId}). The accountId must be composed only from alphanumeric, '_' and '-' characters`)
}
}
const credentials = {
accountId: toCredentialsAccountId(credsInstance.value.accountId),
tokenId: credsInstance.value.tokenId,
tokenSecret: credsInstance.value.tokenSecret,
suiteAppTokenId: credsInstance.value.suiteAppTokenId === '' ? undefined : credsInstance.value.suiteAppTokenId,
suiteAppTokenSecret: credsInstance.value.suiteAppTokenSecret === '' ? undefined : credsInstance.value.suiteAppTokenSecret,
suiteAppActivationKey: credsInstance.value.suiteAppActivationKey,
}
throwOnInvalidAccountId(credentials)
throwOnMissingSuiteAppLoginCreds(credentials)
return credentials
}
const getAdapterOperations = (context: AdapterOperationsContext): AdapterOperations => {
const adapterConfig = netsuiteConfigFromConfig(context.config)
const credentials = netsuiteCredentialsFromCredentials(context.credentials)
const globalLimiter = new Bottleneck({
maxConcurrent: adapterConfig.concurrencyLimit
?? Math.max(
adapterConfig.client?.sdfConcurrencyLimit ?? DEFAULT_CONCURRENCY,
adapterConfig.suiteAppClient?.suiteAppConcurrencyLimit ?? DEFAULT_CONCURRENCY
),
})
const suiteAppClient = isSuiteAppCredentials(credentials) && credentials.suiteAppActivationKey
? new SuiteAppClient({
credentials,
config: adapterConfig.suiteAppClient,
globalLimiter,
})
: undefined
const sdfClient = new SdfClient({
credentials,
config: adapterConfig.client,
globalLimiter,
})
return new NetsuiteAdapter({
client: new NetsuiteClient(sdfClient, suiteAppClient),
elementsSource: context.elementsSource,
config: adapterConfig,
getElemIdFunc: context.getElemIdFunc,
})
}
export const adapter: Adapter = {
operations: context => getAdapterOperations(context),
validateCredentials: async config => {
const credentials = netsuiteCredentialsFromCredentials(config)
return NetsuiteClient.validateCredentials(credentials)
},
authenticationMethods: {
basic: {
credentialsType: defaultCredentialsType,
},
},
configType,
install: async (): Promise<AdapterInstallResult> => {
try {
return await SdkDownloadService.download()
} catch (err) {
return { success: false, errors: [err.message ?? err] }
}
},
}