import { Base64 } from 'js-base64'; import { pick } from 'lodash-es'; import { SECRET_LIST_PATH } from '@routes/paths'; import { IMAGE_PULL_SECRET_TYPES } from '~/consts/secrets'; import { K8sGetResource, K8sQueryCreateResource, K8sQueryPatchResource } from '~/k8s'; import { SecretModel } from '~/models'; import { AddSecretFormValues, BuildTimeSecret, ImagePullSecretType, ImportSecret, K8sSecretType, RemoteSecretStatusReason, RemoteSecretStatusType, SecretByUILabel, SecretCondition, SecretForComponentOption, SecretKind, SecretLabels, SecretType, SecretTypeDisplayLabel, SecretTypeDropdownLabel, SourceSecretType, Source, KeyValueEntry, } from '~/types'; import type { Patch } from '~/types/k8s'; export { SecretForComponentOption }; export const isImagePullSecret = (secret: SecretKind): boolean => { const t = secret.type ?? secret.metadata?.labels?.[SecretLabels.K8S_TYPE_LABEL]; return IMAGE_PULL_SECRET_TYPES.includes(t as (typeof IMAGE_PULL_SECRET_TYPES)[number]); }; /** Resolves Kubernetes `Secret.type` when the object is metadata-only (no `type` field). */ export const getResolvedKubernetesSecretType = (secret: SecretKind): SecretType => { if (secret.type) { return secret.type as SecretType; } const fromLabel = secret.metadata?.labels?.[SecretLabels.K8S_TYPE_LABEL] as | SecretType | undefined; if (fromLabel) { return fromLabel; } if (secret.metadata?.labels?.[SecretLabels.HOST_LABEL]) { const authKind = secret.metadata.labels[SecretLabels.SOURCE_AUTH_KIND_LABEL]; if (authKind === 'ssh') { return SecretType.sshAuth; } return SecretType.basicAuth; } return SecretType.opaque; }; export const fetchFullSecret = (namespace: string, name: string): Promise => K8sGetResource({ model: SecretModel, queryOptions: { ns: namespace, name }, }); export type PartnerTask = { type: SecretType; name: string; providerUrl: string; tokenKeyName: string; keyValuePairs: { key: string; value: string; readOnlyKey?: boolean; readOnlyValue?: boolean; }[]; }; export const supportedPartnerTasksSecrets: { [key: string]: BuildTimeSecret } = { snyk: { type: SecretType.opaque, name: 'snyk-secret', providerUrl: 'https://snyk.io/', tokenKeyName: 'snyk_token', opaque: { keyValuePairs: [{ key: 'snyk_token', value: '', readOnlyKey: true, readOnlyValue: false }], }, }, }; export const getSupportedPartnerTaskSecrets = () => { return Object.values(supportedPartnerTasksSecrets).map((secret) => ({ label: secret.name, value: secret.name, })); }; export const isPartnerTaskAvailable = ( type: string, arr: { [key: string]: BuildTimeSecret } = supportedPartnerTasksSecrets, ) => !!Object.values(arr).find((secret) => secret.type === K8sSecretType[type]); export const isPartnerTask = ( secretName: string, arr: { [key: string]: BuildTimeSecret } = supportedPartnerTasksSecrets, ) => { return !!Object.values(arr).find((secret) => secret.name === secretName); }; export const findExistingOpaqueSecretByName = ( name: string, existingSecrets: BuildTimeSecret[], ): BuildTimeSecret | undefined => { return existingSecrets.find( (secret) => secret.name === name && secret.type === SecretType.opaque, ); }; export const isUsingExistingClusterSecret = ( name: string, type: string, existingSecrets: BuildTimeSecret[], ): boolean => { if (!name || type !== SecretTypeDropdownLabel.opaque) { return false; } const matched = findExistingOpaqueSecretByName(name, existingSecrets); if (!matched) { return false; } if (isPartnerTask(name, supportedPartnerTasksSecrets)) { return matched.opaque?.keyValuePairs?.some((kv) => kv.readOnlyValue) ?? false; } return true; }; export const getAuthType = ( type: SecretType, ): ImagePullSecretType | SourceSecretType | SecretTypeDropdownLabel | undefined => { switch (type) { case SecretType.dockerconfigjson: return ImagePullSecretType.ImageRegistryCreds; case SecretType.dockercfg: return ImagePullSecretType.UploadConfigFile; case SecretType.basicAuth: return SourceSecretType.basic; case SecretType.sshAuth: return SourceSecretType.ssh; case SecretType.opaque: return SecretTypeDropdownLabel.opaque; default: return undefined; } }; export const getSupportedPartnerTaskKeyValuePairs = ( secretName?: string, arr: { [key: string]: BuildTimeSecret } = supportedPartnerTasksSecrets, ) => { const partnerTask = Object.values(arr).find((secret) => secret.name === secretName); return partnerTask ? partnerTask.opaque.keyValuePairs : []; }; export const typeToLabel = (type: string) => { switch (type) { case SecretType.dockerconfigjson: case SecretType.dockercfg: return SecretTypeDisplayLabel.imagePull; case SecretType.basicAuth: case SecretType.sshAuth: return SecretTypeDisplayLabel.source; case SecretType.opaque: return SecretTypeDisplayLabel.keyValue; default: return type; } }; export const typeToDropdownLabel = (type: string) => { switch (type) { case SecretType.dockerconfigjson: case SecretType.dockercfg: return SecretTypeDropdownLabel.image; case SecretType.basicAuth: case SecretType.sshAuth: return SecretTypeDropdownLabel.source; case SecretType.opaque: return SecretTypeDropdownLabel.opaque; default: return type; } }; /** * Normalizes uploaded Docker config JSON to the shape expected for * `kubernetes.io/dockerconfigjson` (`.dockerconfigjson` data key). * Legacy `~/.dockercfg` files (flat registry → auth map) are wrapped as `{ auths: ... }`. * Modern `config.json` content (with `auths`) is returned as-is. */ export const normalizeDockerConfigForDockerconfigjson = ( parsed: unknown, ): Record => { if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { return { auths: {} }; } const obj = parsed as Record; if (obj.auths != null && typeof obj.auths === 'object' && !Array.isArray(obj.auths)) { return obj; } return { auths: obj }; }; export const getKubernetesSecretType = (values: AddSecretFormValues) => { if (values.type === SecretTypeDropdownLabel.image) { return SecretType.dockerconfigjson; } let type = values.type; if (values.type === SecretTypeDropdownLabel.source) { type = values.source.authType; } return K8sSecretType[type]; }; export const getSecretFormData = (values: AddSecretFormValues, namespace: string): SecretKind => { let data = {}; if (values.type === SecretTypeDropdownLabel.opaque) { data = values.opaque.keyValues.reduce((acc, s) => { acc[s.key] = s.value ? s.value : ''; return acc; }, {}); } else if (values.type === SecretTypeDropdownLabel.image) { if (values.image.authType === ImagePullSecretType.ImageRegistryCreds) { const dockerconfigjson = values.image.registryCreds.reduce( (acc, cred) => { acc.auths[cred.registry] = { ...pick(cred, ['username', 'password', 'email']), auth: Base64.encode(`${cred.username}:${cred.password}`), }; return acc; }, { auths: {} }, ); data = dockerconfigjson ? { ['.dockerconfigjson']: Base64.btoa(JSON.stringify(dockerconfigjson)) } : ''; } else if (values.image.dockerconfig) { let parsedDockerConfig: unknown; try { parsedDockerConfig = JSON.parse(Base64.decode(values.image.dockerconfig)); } catch { parsedDockerConfig = {}; } const normalized = normalizeDockerConfigForDockerconfigjson(parsedDockerConfig); data = { ['.dockerconfigjson']: Base64.btoa(JSON.stringify(normalized)), }; } else { data = ''; } } else if (values.type === SecretTypeDropdownLabel.source) { if (values.source.authType === SourceSecretType.basic) { const authObj = pick(values.source, ['username', 'password']); data = Object.entries(authObj).reduce((acc, [key, value]) => { if (value) { acc[key] = Base64.encode(value); } return acc; }, {}); } else { const SSH_KEY = 'ssh-privatekey'; data[SSH_KEY] = values.source[SSH_KEY]; } } const secretResource: SecretKind = { apiVersion: SecretModel.apiVersion, kind: SecretModel.kind, metadata: { name: values.name, namespace, }, type: getKubernetesSecretType(values), data, }; return secretResource; }; const REGISTRY_CREDS_DEFAULT = [{ registry: '', username: '', password: '', email: '' }]; export const getRegistryCreds = (secretData: SecretKind) => { if ((secretData.type as SecretType) !== SecretType.dockerconfigjson) { return REGISTRY_CREDS_DEFAULT; } const encoded = secretData.data?.['.dockerconfigjson']; if (!encoded) { return REGISTRY_CREDS_DEFAULT; } try { const parsed = JSON.parse(Base64.decode(encoded)) as { auths?: { [key: string]: { username: string; password: string; email: string } }; }; if (parsed?.auths && typeof parsed.auths === 'object') { const creds = Object.entries(parsed.auths).map(([registryName, authData]) => ({ registry: registryName, username: authData.username, password: authData.password, email: authData.email ?? '', })); return creds.length > 0 ? creds : REGISTRY_CREDS_DEFAULT; } } catch { return REGISTRY_CREDS_DEFAULT; } return REGISTRY_CREDS_DEFAULT; }; export const getTargetLabelsForRemoteSecret = ( values: AddSecretFormValues, ): { [key: string]: string } => { const { secretFor } = values; const labels = { [SecretByUILabel]: secretFor, }; return labels; }; type SecretLabelInput = { source?: Source; labels?: KeyValueEntry[]; secretForComponentOption?: null | SecretForComponentOption; }; export const getLabelsForSecret = (values: SecretLabelInput): { [key: string]: string } => { const addCommonSecretLabel = values?.secretForComponentOption === SecretForComponentOption.all; if ( !values.source?.host && (!values.labels || values.labels.length === 0) && !addCommonSecretLabel ) { // if no labels quit early return null; } const labels = {}; if (values.labels && values.labels.length > 0) { // get user defined labels values.labels.map(({ key, value }) => { if (key && value) { labels[key] = value; } }); } if (values?.source?.host) { // get scm labels for host labels[SecretLabels.CREDENTIAL_LABEL] = SecretLabels.CREDENTIAL_VALUE; labels[SecretLabels.HOST_LABEL] = values.source.host; } if (addCommonSecretLabel) { labels[SecretLabels.COMMON_SECRET_LABEL] = 'true'; } return labels; }; export const getAnnotationForSecret = ( values: AddSecretFormValues | ImportSecret, ): { [key: string]: string } => { if (!values.source?.repo) { // get scm annotation for repository return null; } return { [SecretLabels.REPO_ANNOTATION]: values.source.repo }; }; export const createK8sSecretResource = ( values: AddSecretFormValues, secretResource: SecretKind, ): SecretKind => { const labels = getLabelsForSecret(values); const annotations = getAnnotationForSecret(values); const k8sSecretResource = { ...secretResource, metadata: { ...secretResource.metadata, labels: { ...secretResource.metadata.labels, ...(labels || {}), }, annotations: { ...secretResource.metadata.annotations, ...(annotations || {}), }, }, }; return k8sSecretResource; }; export const statusFromConditions = ( conditions: SecretCondition[], ): RemoteSecretStatusReason | string => { if (!conditions?.length) { return RemoteSecretStatusReason.Unknown; } const deployedCondition = conditions.find((c) => c.type === RemoteSecretStatusType.Deployed); if (deployedCondition) { return deployedCondition.reason; } return conditions[conditions.length - 1]?.reason || RemoteSecretStatusReason.Unknown; }; export const getSecretRowLabels = (obj: SecretKind): Record => { const secretLabels = obj ? Object.keys(obj?.metadata?.labels || {}) .map((k) => `${k}=${obj.metadata?.labels[k]}`) .join(', ') || '-' : '-'; return { secretLabels, }; }; export const getSecretTypetoLabel = (obj: SecretKind) => { if (!obj) { return; } const resolvedType = getResolvedKubernetesSecretType(obj); const type = typeToLabel(resolvedType); const secretType = type === SecretTypeDisplayLabel.keyValue && obj.data ? `${type} (${Object.keys(obj.data).length})` : type || '-'; return secretType; }; export const createSecretResource = async ( secretResource: SecretKind, namespace: string, dryRun: boolean, ): Promise => K8sQueryCreateResource({ model: SecretModel, queryOptions: { ns: namespace, ...(dryRun && { queryParams: { dryRun: 'All' } }), }, resource: secretResource, }); /** Ensures JSON Patch always receives an object; `null`/missing maps become `{}` to clear metadata on the server. */ const metadataMapForPatch = ( map: Record | null | undefined, ): Record => (map && typeof map === 'object' && !Array.isArray(map) ? map : {}); const updateSecretResource = async (newK8sSecretResource: SecretKind) => { const patches: Patch[] = [ { op: 'add', path: '/metadata/labels', value: metadataMapForPatch(newK8sSecretResource.metadata?.labels), }, { op: 'add', path: '/metadata/annotations', value: metadataMapForPatch(newK8sSecretResource.metadata?.annotations), }, { op: 'replace', path: '/data', value: newK8sSecretResource.data, }, ]; return await K8sQueryPatchResource({ model: SecretModel, queryOptions: { name: newK8sSecretResource.metadata.name, ns: newK8sSecretResource.metadata.namespace, }, patches, }); }; export const editSecretResource = ( updatedSecret: AddSecretFormValues, namespace: string, existingSecret?: SecretKind, ) => { const secretResource: SecretKind = getSecretFormData(updatedSecret, namespace); let newK8sSecretResource = createK8sSecretResource(updatedSecret, secretResource); // Preserve annotations not represented in the form (e.g. kubectl/CLI), while applying UI-driven keys. if (existingSecret) { const existingAnnotations = metadataMapForPatch(existingSecret.metadata?.annotations); const formAnnotations = metadataMapForPatch(newK8sSecretResource.metadata?.annotations); newK8sSecretResource = { ...newK8sSecretResource, metadata: { ...newK8sSecretResource.metadata, annotations: { ...existingAnnotations, ...formAnnotations, }, }, }; } return updateSecretResource(newK8sSecretResource); }; export const getSecretBreadcrumbs = (namespace: string, operation: string) => { return [ { path: SECRET_LIST_PATH.createPath({ workspaceName: namespace }), name: 'Secrets' }, { path: '#', name: `${operation} secret` }, ]; }; export const patchCommonSecretLabel = async (secret: SecretKind, add: boolean) => { if (!secret || !secret.metadata?.name || !secret.metadata?.namespace) { return; } const currentLabels = secret.metadata.labels || {}; const updatedLabels = { ...currentLabels }; if (add) { updatedLabels[SecretLabels.COMMON_SECRET_LABEL] = 'true'; } else { delete updatedLabels[SecretLabels.COMMON_SECRET_LABEL]; } return K8sQueryPatchResource({ model: SecretModel, queryOptions: { name: secret.metadata.name, ns: secret.metadata.namespace, }, patches: [ { op: 'replace', path: '/metadata/labels', value: updatedLabels, }, ], }); };