-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathutils.ts
More file actions
529 lines (486 loc) · 16.9 KB
/
utils.ts
File metadata and controls
529 lines (486 loc) · 16.9 KB
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
/*
* Copyright (c) 2024. Devtron Inc.
*
* 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 { GroupBase, OptionsOrGroups } from 'react-select'
import YAML from 'yaml'
import { noop, YAMLStringify } from '@Common/Helper'
import { DEFAULT_SECRET_PLACEHOLDER } from '@Shared/constants'
import { decode } from '@Shared/Helpers'
import {
CM_SECRET_STATE,
CMSecretComponentType,
CMSecretConfigData,
CMSecretExternalType,
CMSecretPayloadType,
CODE_EDITOR_RADIO_STATE,
ConfigDatum,
ConfigMapSecretUseFormProps,
ESOSecretData,
GetConfigMapSecretFormInitialValuesParamsType,
ProcessCMCSCurrentDataParamsType,
} from '@Shared/Services'
import { hasESO, OverrideMergeStrategyType } from '@Pages/index'
import { KeyValueTableData } from '../KeyValueTable'
import { getSelectPickerOptionByValue } from '../SelectPicker'
import {
CONFIG_MAP_SECRET_DEFAULT_CURRENT_DATA,
configMapDataTypeOptions,
configMapSecretMountDataMap,
} from './constants'
import { ConfigMapSecretDataTypeOptionType, GetConfigMapSecretReadOnlyValuesParamsType } from './types'
export const getSecretDataTypeOptions = (
isJob: boolean,
isHashiOrAWS: boolean,
):
| ConfigMapSecretDataTypeOptionType[]
| OptionsOrGroups<ConfigMapSecretDataTypeOptionType, GroupBase<ConfigMapSecretDataTypeOptionType>> => {
const kubernetesOptions: ConfigMapSecretDataTypeOptionType[] = [
{ value: '', label: 'Kubernetes Secret' },
{ value: CMSecretExternalType.KubernetesSecret, label: 'Mount Existing Kubernetes Secret' },
]
const esoOptions: GroupBase<ConfigMapSecretDataTypeOptionType>[] = [
{
label: 'External Secret Operator (ESO)',
options: [
{ value: CMSecretExternalType.ESO_GoogleSecretsManager, label: 'Google Secrets Manager' },
{ value: CMSecretExternalType.ESO_AWSSecretsManager, label: 'AWS Secrets Manager' },
{ value: CMSecretExternalType.ESO_AzureSecretsManager, label: 'Azure Secrets Manager' },
{ value: CMSecretExternalType.ESO_HashiCorpVault, label: 'Hashi Corp Vault' },
],
},
]
const kesOptions: GroupBase<ConfigMapSecretDataTypeOptionType>[] = [
{
label: 'Kubernetes External Secret (KES)',
options: [
{
value: CMSecretExternalType.AWSSecretsManager,
label: 'AWS Secrets Manager',
description: 'Deprecated',
},
{
value: CMSecretExternalType.AWSSystemManager,
label: 'AWS System Manager',
description: 'Deprecated',
},
{
value: CMSecretExternalType.HashiCorpVault,
label: 'Hashi Corp Vault',
description: 'Deprecated',
},
],
},
]
return isJob ? kubernetesOptions : [...kubernetesOptions, ...esoOptions, ...(isHashiOrAWS ? kesOptions : [])]
}
const secureValues = (data: Record<string, string>, decodeData: boolean): KeyValueTableData[] => {
let decodedData = data || DEFAULT_SECRET_PLACEHOLDER
if (decodeData) {
try {
decodedData = decode(data)
} catch {
noop()
}
}
return Object.keys(decodedData).map((key, id) => ({
key,
value: typeof decodedData[key] === 'object' ? YAMLStringify(decodedData[key]) : decodedData[key],
id,
}))
}
const processCurrentData = ({
configMapSecretData,
cmSecretStateLabel,
isSecret,
}: ProcessCMCSCurrentDataParamsType) => {
if (configMapSecretData.mergeStrategy === OverrideMergeStrategyType.PATCH) {
if (configMapSecretData.patchData) {
return secureValues(configMapSecretData.patchData, isSecret && configMapSecretData.externalType === '')
}
return CONFIG_MAP_SECRET_DEFAULT_CURRENT_DATA
}
if (configMapSecretData.data) {
return secureValues(configMapSecretData.data, isSecret && configMapSecretData.externalType === '')
}
if (cmSecretStateLabel === CM_SECRET_STATE.INHERITED && configMapSecretData.defaultData) {
return secureValues(configMapSecretData.defaultData, isSecret && configMapSecretData.externalType === '')
}
return CONFIG_MAP_SECRET_DEFAULT_CURRENT_DATA
}
const processExternalSubPathValues = ({
data,
esoSubPath,
external,
subPath,
}: Pick<ConfigDatum, 'data' | 'esoSubPath' | 'subPath' | 'external'>) => {
if (subPath && external && data) {
return Object.keys(data).join(', ')
}
if (esoSubPath) {
return esoSubPath.join(', ')
}
return ''
}
export const convertKeyValuePairToYAML = (currentData: KeyValueTableData[]) =>
currentData.length ? YAMLStringify(currentData.reduce((agg, { key, value }) => ({ ...agg, [key]: value }), {})) : ''
const getSecretDataFromConfigData = ({
secretData,
defaultSecretData,
esoSecretData: baseEsoSecretData,
defaultESOSecretData,
}: CMSecretConfigData): Pick<ConfigMapSecretUseFormProps, 'secretDataYaml' | 'esoSecretYaml'> => {
let jsonForSecretDataYaml: string
if (secretData?.length) {
jsonForSecretDataYaml = YAMLStringify(secretData)
} else if (defaultSecretData?.length) {
jsonForSecretDataYaml = YAMLStringify(defaultSecretData)
}
const esoSecretData: Record<string, any> =
!(baseEsoSecretData?.esoData || []).length &&
!baseEsoSecretData?.template &&
!baseEsoSecretData?.esoDataFrom &&
defaultESOSecretData
? defaultESOSecretData
: baseEsoSecretData
const isEsoSecretData: boolean =
(esoSecretData?.secretStore || esoSecretData?.secretStoreRef) &&
(esoSecretData.esoData || esoSecretData.template || esoSecretData.esoDataFrom)
return {
secretDataYaml: jsonForSecretDataYaml ?? '',
esoSecretYaml: isEsoSecretData ? YAMLStringify(esoSecretData) : '',
}
}
export const getConfigMapSecretFormInitialValues = ({
isJob,
configMapSecretData,
cmSecretStateLabel,
componentType,
skipValidation = false,
fallbackMergeStrategy,
}: GetConfigMapSecretFormInitialValuesParamsType): ConfigMapSecretUseFormProps => {
const isSecret = componentType === CMSecretComponentType.Secret
const {
name,
external,
externalType,
type,
mountPath,
defaultMountPath,
subPath,
data,
defaultData,
filePermission,
roleARN,
esoSubPath,
} = configMapSecretData || {}
const commonInitialValues: ConfigMapSecretUseFormProps = {
name: name ?? '',
isSecret,
external: external ?? false,
externalType: externalType ?? CMSecretExternalType.Internal,
selectedType: type ?? configMapSecretMountDataMap.environment.value,
isFilePermissionChecked: !!filePermission,
isSubPathChecked: !!subPath,
filePermission: filePermission ?? '',
volumeMountPath: mountPath ?? defaultMountPath ?? '',
roleARN: roleARN ?? '',
yamlMode: true,
hasCurrentDataErr: false,
isResolvedData: false,
skipValidation,
currentData: null,
esoSecretYaml: null,
externalSubpathValues: null,
mergeStrategy: null,
secretDataYaml: null,
yaml: null,
}
if (configMapSecretData) {
const defaultMergeStrategy = isJob || external ? OverrideMergeStrategyType.REPLACE : fallbackMergeStrategy
const mergeStrategy =
configMapSecretData.mergeStrategy ||
(cmSecretStateLabel === CM_SECRET_STATE.INHERITED ? defaultMergeStrategy : null)
const currentData = processCurrentData({
configMapSecretData: { ...configMapSecretData, mergeStrategy },
cmSecretStateLabel,
isSecret,
})
return {
...commonInitialValues,
externalSubpathValues: processExternalSubPathValues({
data: data || defaultData,
external,
subPath,
esoSubPath,
}),
yaml: convertKeyValuePairToYAML(currentData),
currentData,
mergeStrategy,
...getSecretDataFromConfigData(configMapSecretData),
}
}
return {
...commonInitialValues,
externalSubpathValues: '',
yaml: '"": ""\n',
currentData: CONFIG_MAP_SECRET_DEFAULT_CURRENT_DATA,
esoSecretYaml: '{}',
secretDataYaml: '[]',
mergeStrategy: null,
}
}
export const getConfigMapSecretReadOnlyValues = ({
configMapSecretData,
cmSecretStateLabel,
componentType,
isJob,
fallbackMergeStrategy,
displayKeys,
}: GetConfigMapSecretReadOnlyValuesParamsType) => {
if (!configMapSecretData) {
return {
configData: [],
data: null,
}
}
const {
external,
externalType,
esoSecretYaml,
externalSubpathValues,
filePermission,
isSubPathChecked,
roleARN,
secretDataYaml,
selectedType,
volumeMountPath,
yaml,
currentData,
isSecret,
} = getConfigMapSecretFormInitialValues({
isJob,
configMapSecretData,
cmSecretStateLabel,
componentType,
fallbackMergeStrategy,
})
const mountExistingExternal =
external && externalType === (isSecret ? CMSecretExternalType.KubernetesSecret : CMSecretExternalType.Internal)
let dataType = ''
if (!isSecret) {
dataType = configMapDataTypeOptions.find(({ value }) =>
external && externalType === ''
? value === CMSecretExternalType.KubernetesConfigMap
: value === externalType,
).label as string
} else {
dataType =
external && externalType === ''
? CMSecretExternalType.KubernetesSecret
: (getSelectPickerOptionByValue(getSecretDataTypeOptions(isJob, true), externalType).label as string)
}
return {
configData: [
{
displayName: 'DataType',
value: dataType,
key: 'dataType',
},
{
displayName: 'Mount data as',
value: configMapSecretMountDataMap[selectedType].title,
key: 'mountDataAs',
},
{
displayName: 'Volume mount path',
value: volumeMountPath,
key: 'volumeMountPath',
},
{
displayName: 'Set Sub Path',
value:
(configMapSecretMountDataMap[selectedType].value === 'volume' &&
(isSubPathChecked ? 'True' : 'False')) ||
'',
key: 'setSubPath',
},
{
displayName: 'Subpath Values',
value: externalSubpathValues,
key: 'externalSubpathValues',
},
{
displayName: 'File Permission',
value: filePermission,
key: 'filePermission',
},
{
displayName: 'Role ARN',
value: roleARN,
key: 'roleArn',
},
...(displayKeys
? [
{
displayName: 'Keys',
value:
currentData?.length > 0 ? currentData.map((d) => d.key).join(', ') : 'No keys available',
key: 'keys',
},
]
: []),
],
data: !mountExistingExternal ? (currentData?.[0]?.key && yaml) || esoSecretYaml || secretDataYaml : null,
}
}
export const convertYAMLToKeyValuePair = (yaml: string): KeyValueTableData[] => {
try {
const obj = yaml && YAML.parse(yaml)
if (typeof obj !== 'object') {
throw new Error()
}
const keyValueArray = Object.keys(obj).reduce<KeyValueTableData[]>((agg, key, id) => {
if (!key && !obj[key]) {
return CONFIG_MAP_SECRET_DEFAULT_CURRENT_DATA
}
const value = obj[key] && typeof obj[key] === 'object' ? YAMLStringify(obj[key]) : obj[key].toString()
return [...agg, { key, value: value ?? '', id }]
}, [])
return keyValueArray
} catch {
return CONFIG_MAP_SECRET_DEFAULT_CURRENT_DATA
}
}
export const getESOSecretDataFromYAML = (yaml: string): ESOSecretData => {
try {
const json = YAML.parse(yaml)
if (typeof json === 'object') {
const payload = {
secretStore: json.secretStore,
secretStoreRef: json.secretStoreRef,
refreshInterval: json.refreshInterval,
// if null don't send these keys which is achieved by `undefined`
esoData: undefined,
esoDataFrom: undefined,
template: undefined,
}
if (Array.isArray(json?.esoData)) {
payload.esoData = json.esoData
}
if (Array.isArray(json?.esoDataFrom)) {
payload.esoDataFrom = json.esoDataFrom
}
if (typeof json?.template === 'object' && !Array.isArray(json.template)) {
payload.template = json.template
}
return payload
}
return null
} catch {
return null
}
}
export const getConfigMapSecretPayload = ({
isSecret,
external,
externalType,
externalSubpathValues,
yaml,
yamlMode,
currentData,
esoSecretYaml,
filePermission,
name,
selectedType,
isFilePermissionChecked,
roleARN,
volumeMountPath,
isSubPathChecked,
mergeStrategy,
}: ConfigMapSecretUseFormProps): CMSecretPayloadType => {
const isESO = isSecret && hasESO(externalType)
const _currentData = yamlMode ? convertYAMLToKeyValuePair(yaml) : currentData
const data = _currentData.reduce((acc, curr) => {
if (!curr.key) {
return acc
}
const value = curr.value ?? ''
return {
...acc,
[curr.key]: isSecret && externalType === '' ? btoa(value) : value,
}
}, {})
const payload: CMSecretPayloadType = {
name,
type: selectedType,
external,
data,
roleARN: null,
externalType: null,
esoSecretData: null,
mountPath: null,
subPath: null,
filePermission: null,
esoSubPath: null,
mergeStrategy,
}
if (
(isSecret && externalType === CMSecretExternalType.KubernetesSecret) ||
(!isSecret && external) ||
(isSecret && isESO)
) {
delete payload[CODE_EDITOR_RADIO_STATE.DATA]
}
if (isSecret) {
payload.roleARN = ''
payload.externalType = externalType
if (isESO) {
const esoSecretData = getESOSecretDataFromYAML(esoSecretYaml)
if (esoSecretData) {
payload.esoSecretData = {
secretStore: esoSecretData.secretStore,
esoData: esoSecretData.esoData,
secretStoreRef: esoSecretData.secretStoreRef,
refreshInterval: esoSecretData.refreshInterval,
esoDataFrom: esoSecretData.esoDataFrom,
template: esoSecretData.template,
}
payload.roleARN = roleARN
if (isSubPathChecked && externalSubpathValues) {
payload.esoSubPath = externalSubpathValues.replace(/\s+/g, '').split(',')
}
}
}
}
if (selectedType === configMapSecretMountDataMap.volume.value) {
payload.mountPath = volumeMountPath
payload.subPath = isSubPathChecked
if (isFilePermissionChecked) {
payload.filePermission = filePermission.length === 3 ? `0${filePermission}` : `${filePermission}`
}
if (
isSubPathChecked &&
((isSecret && externalType === CMSecretExternalType.KubernetesSecret) || (!isSecret && external))
) {
const externalSubpathKey = externalSubpathValues.replace(/\s+/g, '').split(',')
const secretKeys = {}
externalSubpathKey.forEach((key) => {
secretKeys[key] = ''
})
payload.data = secretKeys
}
}
return payload
}