Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Hook up vault logic in UI

Joshen Lim295771da0bff
diff --git a/.turbo-cookie b/.turbo-cookie
deleted file mode 100755
index 9e5d1817106..00000000000
--- a/.turbo-cookie
+++ /dev/null
@@ -1 +0,0 @@
-cookie
\ No newline at end of file
diff --git a/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx b/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx
index 1e871404386..46c5105d027 100644
--- a/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx
+++ b/studio/components/interfaces/Database/Extensions/EnableExtensionModal.tsx
@@ -54,34 +54,36 @@ const EnableExtensionModal: FC<Props> = ({ visible, extension, onCancel }) => {
const onSubmit = async (values: any, { setSubmitting }: any) => {
setSubmitting(true)
- if (values.schema === 'custom') {
- const { error } = await meta.query(`create schema if not exists ${values.name}`)
- if (error) {
- return ui.setNotification({
- error,
- category: 'error',
- message: `Failed to create schema: ${error.message}`,
- })
- }
- }
- const schema = defaultSchema
- ? defaultSchema
- : values.schema === 'custom'
- ? values.name
- : values.schema
+ const schema =
+ defaultSchema !== undefined
+ ? defaultSchema
+ : values.schema === 'custom'
+ ? values.name
+ : values.schema
+
+ const { error: createSchemaError } = await meta.query(`create schema if not exists ${schema}`)
+ if (createSchemaError) {
+ return ui.setNotification({
+ error: createSchemaError,
+ category: 'error',
+ message: `Failed to create schema: ${createSchemaError.message}`,
+ })
+ }
- const { error } = await meta.extensions.create({
+ const { error: createExtensionError } = await meta.extensions.create({
schema,
name: extension.name,
version: extension.default_version,
cascade: true,
})
- if (error) {
+ if (createExtensionError) {
ui.setNotification({
- error,
+ error: createExtensionError,
category: 'error',
- message: `Failed to toggle ${extension.name.toUpperCase()}: ${error.message}`,
+ message: `Failed to toggle ${extension.name.toUpperCase()}: ${
+ createExtensionError.message
+ }`,
})
} else {
ui.setNotification({
diff --git a/studio/components/interfaces/Settings/Vault/EncryptionKeySelector.tsx b/studio/components/interfaces/Settings/Vault/Keys/EncryptionKeySelector.tsx
similarity index 91%
rename from studio/components/interfaces/Settings/Vault/EncryptionKeySelector.tsx
rename to studio/components/interfaces/Settings/Vault/Keys/EncryptionKeySelector.tsx
index a1fff01ee77..959d75c5ffc 100644
--- a/studio/components/interfaces/Settings/Vault/EncryptionKeySelector.tsx
+++ b/studio/components/interfaces/Settings/Vault/Keys/EncryptionKeySelector.tsx
@@ -4,7 +4,7 @@ import { useStore } from 'hooks'
interface Props {
id?: string
- descriptionId?: string
+ nameId?: string
label?: string
labelOptional?: string
selectedKeyId?: any
@@ -14,7 +14,7 @@ interface Props {
const EncryptionKeySelector: FC<Props> = ({
id = 'keyId',
- descriptionId = 'keyDescription',
+ nameId = 'keyName',
label = 'Encryption key',
labelOptional,
selectedKeyId,
@@ -30,6 +30,7 @@ const EncryptionKeySelector: FC<Props> = ({
id={id}
label={label}
size="small"
+ defaultValue={selectedKeyId}
value={selectedKeyId}
labelOptional={labelOptional}
onChange={onSelectKey}
@@ -61,9 +62,8 @@ const EncryptionKeySelector: FC<Props> = ({
</Listbox>
{selectedKeyId === 'create-new' && (
<Input
- id={descriptionId}
- label="Description"
- labelOptional="Optional"
+ id={nameId}
+ label="Name"
onChange={(event) => onUpdateDescription(event.target.value)}
/>
)}
diff --git a/studio/components/interfaces/Settings/Vault/EncryptionKeysManagement.tsx b/studio/components/interfaces/Settings/Vault/Keys/EncryptionKeysManagement.tsx
similarity index 90%
rename from studio/components/interfaces/Settings/Vault/EncryptionKeysManagement.tsx
rename to studio/components/interfaces/Settings/Vault/Keys/EncryptionKeysManagement.tsx
index a702aaaa809..2d50618beb1 100644
--- a/studio/components/interfaces/Settings/Vault/EncryptionKeysManagement.tsx
+++ b/studio/components/interfaces/Settings/Vault/Keys/EncryptionKeysManagement.tsx
@@ -26,7 +26,7 @@ const EncryptionKeysManagement: FC<Props> = ({}) => {
const { vault, ui } = useStore()
const [searchValue, setSearchValue] = useState<string>('')
- const [selectedSort, setSelectedSort] = useState<'comment' | 'created'>('created')
+ const [selectedSort, setSelectedSort] = useState<'name' | 'created'>('created')
const [showAddKeyModal, setShowAddKeyModal] = useState(false)
const [selectedKeyToRemove, setSelectedKeyToRemove] = useState<any>()
@@ -36,7 +36,7 @@ const EncryptionKeysManagement: FC<Props> = ({}) => {
searchValue
? vault.listKeys(
(key: any) =>
- (key?.comment ?? '').toLowerCase().includes(searchValue.toLowerCase()) ||
+ (key?.name ?? '').toLowerCase().includes(searchValue.toLowerCase()) ||
key.id.toLowerCase().includes(searchValue.toLowerCase())
)
: vault.listKeys()
@@ -50,7 +50,7 @@ const EncryptionKeysManagement: FC<Props> = ({}) => {
const addKey = async (values: any, { setSubmitting }: any) => {
setSubmitting(true)
- const res = await vault.addKey(values.description)
+ const res = await vault.addKey(values.name)
if (!res.error) {
ui.setNotification({ category: 'success', message: 'Successfully added new key' })
setShowAddKeyModal(false)
@@ -100,8 +100,8 @@ const EncryptionKeysManagement: FC<Props> = ({}) => {
<Listbox.Option id="created" value="created" label="Sort by created at">
Created at
</Listbox.Option>
- <Listbox.Option id="comment" value="comment" label="Sort by description">
- Description
+ <Listbox.Option id="name" value="name" label="Sort by name">
+ Name
</Listbox.Option>
</Listbox>
</div>
@@ -128,16 +128,16 @@ const EncryptionKeysManagement: FC<Props> = ({}) => {
<div className="space-y-1 min-w-[37%] max-w-[37%]">
<p
className="text-sm truncate text-scale-1200"
- title={key.comment || DEFAULT_KEY_NAME}
+ title={key.name || DEFAULT_KEY_NAME}
>
- {key.comment || DEFAULT_KEY_NAME}
+ {key.name || DEFAULT_KEY_NAME}
</p>
<p title={key.id} className="text-xs text-scale-1100 font-bold truncate">
ID: <span className="font-mono">{key.id}</span>
</p>
</div>
<div className="flex items-center space-x-2 w-[33%]">
- {key.status === 'default' && <Badge color="green">Default</Badge>}
+ {key.name === 'default_vault_key' && <Badge color="green">Default</Badge>}
</div>
<div className="flex items-center justify-end w-[30%] space-x-4">
<p className="text-sm text-scale-1100">
@@ -149,11 +149,11 @@ const EncryptionKeysManagement: FC<Props> = ({}) => {
type="default"
className="py-2"
icon={<IconTrash />}
- disabled={key.status === 'default'}
+ disabled={key.name === 'default_vault_key'}
onClick={() => setSelectedKeyToRemove(key)}
/>
</Tooltip.Trigger>
- {key.status === 'default' && (
+ {key.name === 'default_vault_key' && (
<Tooltip.Content side="bottom">
<Tooltip.Arrow className="radix-tooltip-arrow" />
<div
@@ -225,7 +225,7 @@ const EncryptionKeysManagement: FC<Props> = ({}) => {
</p>
<div className="space-y-2">
<p className="text-sm text-scale-1200">
- {selectedKeyToRemove?.comment ?? DEFAULT_KEY_NAME}
+ {selectedKeyToRemove?.name ?? DEFAULT_KEY_NAME}
</p>
<p className="text-xs text-scale-1100">
<code className="!mx-0">ID: {selectedKeyToRemove?.id}</code>
@@ -260,11 +260,14 @@ const EncryptionKeysManagement: FC<Props> = ({}) => {
<div className="py-4">
<Modal.Content>
<p className="text-sm mb-4">
- Keys are of standard UUID types - you can provide a description to your key for
- better identification.
+ Provide a name for your key for easier identification.
</p>
<div className="space-y-4 pb-4">
- <Input id="name" label="Key Name" />
+ <Input
+ id="name"
+ label="Key Name"
+ descriptionText="Keys are of standard UUID types."
+ />
</div>
</Modal.Content>
<Modal.Separator />
diff --git a/studio/components/interfaces/Settings/Vault/Secrets/AddNewSecretModal.tsx b/studio/components/interfaces/Settings/Vault/Secrets/AddNewSecretModal.tsx
index f579a5d1be9..ff74b6513bf 100644
--- a/studio/components/interfaces/Settings/Vault/Secrets/AddNewSecretModal.tsx
+++ b/studio/components/interfaces/Settings/Vault/Secrets/AddNewSecretModal.tsx
@@ -2,7 +2,7 @@ import { FC, useState, useEffect } from 'react'
import { Modal, Form, Input, IconHelpCircle, Button, IconEyeOff, IconEye } from 'ui'
import { useStore } from 'hooks'
-import EncryptionKeySelector from '../EncryptionKeySelector'
+import EncryptionKeySelector from '../Keys/EncryptionKeySelector'
import InformationBox from 'components/ui/InformationBox'
interface Props {
@@ -16,7 +16,7 @@ const AddNewSecretModal: FC<Props> = ({ visible, onClose }) => {
const [selectedKeyId, setSelectedKeyId] = useState<string>()
const keys = vault.listKeys()
- const defaultKey = keys.find((key) => key.status === 'default')
+ const defaultKey = keys.find((key) => key.name === 'default_vault_key') || keys[0]
useEffect(() => {
if (visible) setSelectedKeyId(defaultKey?.id)
@@ -24,37 +24,50 @@ const AddNewSecretModal: FC<Props> = ({ visible, onClose }) => {
const validate = (values: any) => {
const errors: any = {}
-
+ if (values.name.length === 0) errors.name = 'Please provide a name for your secret'
if (values.secret.length === 0) errors.secret = 'Please enter your secret value'
-
return errors
}
const onAddNewSecret = async (values: any, { setSubmitting }: any) => {
setSubmitting(true)
+ let encryptionKeyId = selectedKeyId
+
if (values.keyId === 'create-new') {
- const res = await vault.addKey(values.keyDescription || undefined)
- if (!res.error) {
- console.log('Add new secret', {
- keyId: res[0].id,
- secret: values.secret,
- description: values.description,
- })
- } else {
- ui.setNotification({
- error: res.error,
+ const addKeyRes = await vault.addKey(values.keyDescription || undefined)
+ if (addKeyRes.error) {
+ return ui.setNotification({
+ error: addKeyRes.error,
category: 'error',
- message: `Failed to create new key: ${res.error.message}`,
+ message: `Failed to create new key: ${addKeyRes.error.message}`,
})
+ } else {
+ encryptionKeyId = addKeyRes[0].id
}
+ }
+
+ const res = await vault.addSecret({
+ name: values.name,
+ description: values.description,
+ secret: values.secret,
+ key_id: encryptionKeyId,
+ })
+
+ if (!res.error) {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully added new secret ${values.name}`,
+ })
+ onClose()
+ setSubmitting(false)
} else {
- console.log('Add new secret', {
- keyId: values.keyId,
- secret: values.secret,
- description: values.description,
+ ui.setNotification({
+ error: res.error,
+ category: 'error',
+ message: `Failed to add secret ${values.name}: ${res.error.message}`,
})
+ setSubmitting(false)
}
- setSubmitting(false)
}
return (
@@ -68,7 +81,7 @@ const AddNewSecretModal: FC<Props> = ({ visible, onClose }) => {
>
<Form
id="add-new-secret-form"
- initialValues={{ secret: '', description: '', keyId: '', keyDescription: '' }}
+ initialValues={{ name: '', description: '', secret: '', keyId: '', keyDescription: '' }}
validate={validate}
validateOnBlur={false}
onSubmit={onAddNewSecret}
@@ -78,6 +91,8 @@ const AddNewSecretModal: FC<Props> = ({ visible, onClose }) => {
<div className="py-4">
<Modal.Content>
<div className="space-y-4 pb-4">
+ <Input id="name" label="Name" />
+ <Input id="description" label="Description" labelOptional="Optional" />
<Input
id="secret"
type={showSecretValue ? 'text' : 'password'}
@@ -92,7 +107,6 @@ const AddNewSecretModal: FC<Props> = ({ visible, onClose }) => {
</div>
}
/>
- <Input id="description" label="Description" labelOptional="Optional" />
</div>
</Modal.Content>
<Modal.Separator />
@@ -100,7 +114,7 @@ const AddNewSecretModal: FC<Props> = ({ visible, onClose }) => {
<div className="py-4 space-y-4">
<EncryptionKeySelector
id="keyId"
- descriptionId="keyDescription"
+ nameId="keyDescription"
label="Select a key to encrypt your secret with"
labelOptional="Optional"
selectedKeyId={selectedKeyId}
diff --git a/studio/components/interfaces/Settings/Vault/Secrets/DeleteSecretModal.tsx b/studio/components/interfaces/Settings/Vault/Secrets/DeleteSecretModal.tsx
index ef5fd2ba835..54c30e7c3bc 100644
--- a/studio/components/interfaces/Settings/Vault/Secrets/DeleteSecretModal.tsx
+++ b/studio/components/interfaces/Settings/Vault/Secrets/DeleteSecretModal.tsx
@@ -1,12 +1,37 @@
-import { FC } from 'react'
+import { FC, useState } from 'react'
import { Modal } from 'ui'
+import { VaultSecret } from 'types'
+import { useStore } from 'hooks'
interface Props {
- selectedSecret: any
+ selectedSecret: VaultSecret
onClose: () => void
}
const DeleteSecretModal: FC<Props> = ({ selectedSecret, onClose }) => {
+ const { vault, ui } = useStore()
+
+ const [isDeleting, setIsDeleting] = useState(false)
+
+ const onConfirmDeleteSecret = async () => {
+ setIsDeleting(true)
+ const res = await vault.deleteSecret(selectedSecret.id)
+ if (res.error) {
+ ui.setNotification({
+ error: res.error,
+ category: 'error',
+ message: `Failed to delete secret: ${res.error.message}`,
+ })
+ } else {
+ ui.setNotification({
+ category: 'success',
+ message: `Successfully deleted secret ${selectedSecret.name}`,
+ })
+ onClose()
+ }
+ setIsDeleting(false)
+ }
+
return (
<Modal
closable
@@ -14,7 +39,8 @@ const DeleteSecretModal: FC<Props> = ({ selectedSecret, onClose }) => {
alignFooter="right"
visible={selectedSecret !== undefined}
onCancel={onClose}
- onConfirm={onClose}
+ onConfirm={onConfirmDeleteSecret}
+ loading={isDeleting}
header={<h5 className="text-sm text-scale-1200">Confirm to delete secret</h5>}
>
<div className="py-4">
diff --git a/studio/components/interfaces/Settings/Vault/Secrets/EditSecretModal.tsx b/studio/components/interfaces/Settings/Vault/Secrets/EditSecretModal.tsx
index c839bc7b0a7..53991731c4c 100644
--- a/studio/components/interfaces/Settings/Vault/Secrets/EditSecretModal.tsx
+++ b/studio/components/interfaces/Settings/Vault/Secrets/EditSecretModal.tsx
@@ -1,8 +1,6 @@
import { FC, useState, useEffect } from 'react'
import { Modal, Form, Input, Button, IconEyeOff, IconEye } from 'ui'
-
-import { useStore } from 'hooks'
-import EncryptionKeySelector from '../EncryptionKeySelector'
+import EncryptionKeySelector from '../Keys/EncryptionKeySelector'
interface Props {
selectedSecret: any
@@ -43,8 +41,9 @@ const EditSecretModal: FC<Props> = ({ selectedSecret, onClose }) => {
<Form
id="add-new-secret-form"
initialValues={{
- secret: selectedSecret?.secret ?? '',
+ name: selectedSecret?.name ?? '',
description: selectedSecret?.description ?? '',
+ secret: selectedSecret?.secret ?? '',
}}
validate={validate}
validateOnBlur={false}
@@ -55,6 +54,8 @@ const EditSecretModal: FC<Props> = ({ selectedSecret, onClose }) => {
<div className="py-4">
<Modal.Content>
<div className="space-y-4 pb-4">
+ <Input id="name" label="Name" />
+ <Input id="description" label="Description" labelOptional="Optional" />
<Input
id="secret"
type={showSecretValue ? 'text' : 'password'}
@@ -69,7 +70,6 @@ const EditSecretModal: FC<Props> = ({ selectedSecret, onClose }) => {
</div>
}
/>
- <Input id="description" label="Description" labelOptional="Optional" />
</div>
</Modal.Content>
<Modal.Separator />
@@ -77,7 +77,7 @@ const EditSecretModal: FC<Props> = ({ selectedSecret, onClose }) => {
<div className="py-4">
<EncryptionKeySelector
id="keyId"
- descriptionId="keyDescription"
+ nameId="keyDescription"
label="Select a key to encrypt your secret with"
labelOptional="Optional"
selectedKeyId={selectedKeyId}
diff --git a/studio/components/interfaces/Settings/Vault/Secrets/SecretRow.tsx b/studio/components/interfaces/Settings/Vault/Secrets/SecretRow.tsx
index e1dc719bd80..11d639cc75b 100644
--- a/studio/components/interfaces/Settings/Vault/Secrets/SecretRow.tsx
+++ b/studio/components/interfaces/Settings/Vault/Secrets/SecretRow.tsx
@@ -1,5 +1,4 @@
import dayjs from 'dayjs'
-import { timeout } from 'lib/helpers'
import { FC, useState } from 'react'
import {
Button,
@@ -13,14 +12,17 @@ import {
IconMoreVertical,
IconLoader,
} from 'ui'
+import { VaultSecret } from 'types'
+import { useStore } from 'hooks'
interface Props {
- secret: any
+ secret: VaultSecret
onSelectEdit: (secret: any) => void
onSelectRemove: (secret: any) => void
}
const SecretRow: FC<Props> = ({ secret, onSelectEdit, onSelectRemove }) => {
+ const { vault } = useStore()
const [isLoading, setIsLoading] = useState(false)
const [revealedValue, setRevealedValue] = useState<string>()
const description = secret?.description ?? 'No description provided'
@@ -28,9 +30,11 @@ const SecretRow: FC<Props> = ({ secret, onSelectEdit, onSelectRemove }) => {
const revealSecret = async () => {
setIsLoading(true)
if (revealedValue === undefined) {
- // Some DB call
- await timeout(1000)
- setRevealedValue(secret.secret)
+ setRevealedValue(
+ secret.decryptedSecret !== undefined
+ ? secret.decryptedSecret
+ : await vault.fetchSecretValue(secret.id)
+ )
} else {
setRevealedValue(undefined)
}
diff --git a/studio/components/interfaces/Settings/Vault/Secrets/SecretsManagement.tsx b/studio/components/interfaces/Settings/Vault/Secrets/SecretsManagement.tsx
index d95d70c6f25..f2c0608313a 100644
--- a/studio/components/interfaces/Settings/Vault/Secrets/SecretsManagement.tsx
+++ b/studio/components/interfaces/Settings/Vault/Secrets/SecretsManagement.tsx
@@ -35,7 +35,9 @@ const SecretsManagement: FC<Props> = ({}) => {
}
})
- console.log(secrets)
+ const onConfirmUpdateSecret = async () => {
+ if (!selectedSecretToEdit) return
+ }
return (
<>
diff --git a/studio/components/interfaces/Settings/Vault/VaultToggle.tsx b/studio/components/interfaces/Settings/Vault/VaultToggle.tsx
index c27d6ff6123..85781585fec 100644
--- a/studio/components/interfaces/Settings/Vault/VaultToggle.tsx
+++ b/studio/components/interfaces/Settings/Vault/VaultToggle.tsx
@@ -10,18 +10,74 @@ import {
FormSectionContent,
} from 'components/ui/Forms'
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { checkPermissions } from 'hooks'
+import { checkPermissions, useStore } from 'hooks'
+import { PostgresExtension } from '@supabase/postgres-meta'
interface Props {}
const VaultToggle: FC<Props> = () => {
+ const { meta, ui } = useStore()
const formId = 'project-vault-settings'
const canToggleVault = checkPermissions(PermissionAction.TENANT_SQL_ADMIN_WRITE, 'extensions')
+ const [vaultExtension] = meta.extensions.list(
+ (ext: PostgresExtension) => ext.name.toLowerCase() === 'supabase_vault'
+ )
+
+ // [Joshen TODO] Need to put this logic correctly once i can toggle vault extension
+ const isEnabled = vaultExtension?.installed_version !== null
const initialValues = { enabled: true }
const onSubmit = async (values: any, { setSubmitting, resetForm }: any) => {
- console.log('onSubmit', values)
+ if (vaultExtension === undefined) return
+
+ setSubmitting(true)
+ if (values.enabled) {
+ // Enable Vault
+ const { error: createSchemaError } = await meta.query(
+ `create schema if not exists ${vaultExtension.schema}`
+ )
+ if (createSchemaError) {
+ return ui.setNotification({
+ error: createSchemaError,
+ category: 'error',
+ message: `Failed to create schema: ${createSchemaError.message}`,
+ })
+ }
+ const { error: createExtensionError } = await meta.extensions.create({
+ schema: vaultExtension.schema,
+ name: vaultExtension.name,
+ version: vaultExtension.default_version,
+ cascade: true,
+ })
+ if (createExtensionError) {
+ ui.setNotification({
+ error: createExtensionError,
+ category: 'error',
+ message: `Failed to enable Vault for your project: ${createExtensionError.message}`,
+ })
+ } else {
+ ui.setNotification({
+ category: 'success',
+ message: 'Vault is not enabled for your project',
+ })
+ }
+ } else {
+ // Disable Vault
+ const response: any = await meta.extensions.del(vaultExtension.name)
+ if (response.error) {
+ ui.setNotification({
+ category: 'error',
+ message: `Failed to disable Vault: ${response.error.message}`,
+ })
+ } else {
+ ui.setNotification({
+ category: 'success',
+ message: 'Vault is not disabled for your project',
+ })
+ }
+ }
+ setSubmitting(false)
}
return (
diff --git a/studio/components/interfaces/Settings/Vault/index.ts b/studio/components/interfaces/Settings/Vault/index.ts
index d52cebe8398..41f32a26d17 100644
--- a/studio/components/interfaces/Settings/Vault/index.ts
+++ b/studio/components/interfaces/Settings/Vault/index.ts
@@ -1,6 +1,6 @@
import VaultToggle from './VaultToggle'
import SecretsManagement from './Secrets/SecretsManagement'
-import EncryptionKeySelector from './EncryptionKeySelector'
-import EncryptionKeysManagement from './EncryptionKeysManagement'
+import EncryptionKeySelector from './Keys/EncryptionKeySelector'
+import EncryptionKeysManagement from './Keys/EncryptionKeysManagement'
export { VaultToggle, SecretsManagement, EncryptionKeySelector, EncryptionKeysManagement }
diff --git a/studio/stores/project/VaultStore.ts b/studio/stores/project/VaultStore.ts
index d13d2862bfa..943cb59234d 100644
--- a/studio/stores/project/VaultStore.ts
+++ b/studio/stores/project/VaultStore.ts
@@ -1,40 +1,8 @@
import { Query } from 'components/grid'
import { makeAutoObservable } from 'mobx'
+import { VaultSecret } from 'types'
import { IRootStore } from '../RootStore'
-const MOCK_SECRETS = [
- {
- key_id: '095f4bfe-f63c-420b-8849-f1e455ee3a02',
- description: 'Client access key for dashboard',
- created_at: '2022-11-01 06:43:48.492465',
- secret: '74d97ba2-f9e3-4a64-a032-8427cd6bd686', // encrypted secret value
- },
- {
- key_id: '095f4bfe-f63c-420b-8849-f1e455ee3a02',
- description: 'Secret key for server',
- created_at: '2022-11-20 06:43:48.492465',
- secret: '74d97ba2-f9e3-4a64-a032-8427cd6bd686',
- },
- {
- key_id: '57bfa919-e81b-4afc-a3b4-372981b2a39a',
- description: 'This is a bit more of a secret key',
- created_at: '2022-11-18 06:43:48.492465',
- secret: '74d97ba2-f9e3-4a64-a032-8427cd6bd686',
- },
- {
- key_id: '57bfa919-e81b-4afc-a3b4-372981b2a39a',
- description: undefined,
- created_at: '2022-11-05 06:43:48.492465',
- secret: '74d97ba2-f9e3-4a64-a032-8427cd6bd686',
- },
- {
- key_id: '57bfa919-e81b-4afc-a3b4-372981b2a39a',
- description: 'This is a pretty long description that Im testing if it should wrap or not',
- created_at: '2022-11-3 06:43:48.492465',
- secret: '74d97ba2-f9e3-4a64-a032-8427cd6bd686',
- },
-]
-
export interface IVaultStore {
isLoading: boolean
isInitialized: boolean
@@ -46,27 +14,22 @@ export interface IVaultStore {
addKey: (name?: string) => any
deleteKey: (id: string) => any
- listSecrets: (filter?: any) => Secret[]
- addSecret: (name?: string) => any
+ listSecrets: (filter?: any) => VaultSecret[]
+ addSecret: (secret: Partial<VaultSecret>) => any
updateSecret: (payload: any) => any
deleteSecret: (id: string) => any
+ fetchSecretValue: (id: string) => any
}
interface EncryptionKey {
id: string
key_id: number
+ name: string
comment: string
created: string
status: string
}
-interface Secret {
- key_id: string
- description: string
- created_at: string
- secret: string
-}
-
export default class VaultStore implements IVaultStore {
rootStore: IRootStore
@@ -77,7 +40,7 @@ export default class VaultStore implements IVaultStore {
LOADED: 'loaded',
}
- data: { keys: EncryptionKey[]; secrets: Secret[] } = { keys: [], secrets: [] }
+ data: { keys: EncryptionKey[]; secrets: VaultSecret[] } = { keys: [], secrets: [] }
state = this.STATES.INITIAL
error = null
@@ -101,14 +64,18 @@ export default class VaultStore implements IVaultStore {
async fetchData() {
const vault = { keys: [], secrets: [] }
- const query = new Query()
+ const keysQuery = new Query()
.from('key', 'pgsodium')
- .select('id,key_id,comment,created,status')
+ .select('id,key_id,name,comment,created,status')
.toSql()
- const keys = await this.rootStore.meta.query(query)
+ const keys = await this.rootStore.meta.query(keysQuery)
if (!keys.error) vault.keys = keys
- const secrets: any = MOCK_SECRETS
+ const secretsQuery = new Query()
+ .from('secrets', 'vault')
+ .select('id,name,description,secret,key_id,created_at')
+ .toSql()
+ const secrets = await this.rootStore.meta.query(secretsQuery)
if (!secrets.error) vault.secrets = secrets
this.data = vault
@@ -145,7 +112,7 @@ export default class VaultStore implements IVaultStore {
async addKey(name?: string) {
const res =
name !== undefined
- ? await this.rootStore.meta.query(`select * from pgsodium.create_key('${name}')`)
+ ? await this.rootStore.meta.query(`select * from pgsodium.create_key(name := '${name}')`)
: await this.rootStore.meta.query(`select * from pgsodium.create_key()`)
if (!res.error) {
this.data.keys = this.data.keys.concat(res)
@@ -176,9 +143,46 @@ export default class VaultStore implements IVaultStore {
}
}
- async addSecret(name?: string) {}
+ async addSecret(newSecret: Partial<VaultSecret>) {
+ const { name, description, secret, key_id } = newSecret
+ const query = new Query()
+ .from('secrets', 'vault')
+ .insert([{ name, description, secret, key_id }], { returning: true })
+ .toSql()
+ const res = await this.rootStore.meta.query(query)
+ if (!res.error) {
+ this.data.secrets = this.data.secrets.concat(res)
+ }
+ return res
+ }
async updateSecret(payload: any) {}
- async deleteSecret(id: string) {}
+ async deleteSecret(id: string) {
+ const query = new Query().from('secrets', 'vault').delete().match({ id }).toSql()
+ const res = await this.rootStore.meta.query(query)
+ if (!res.error) {
+ this.data.secrets = this.data.secrets.filter((secret) => secret.id !== id)
+ }
+ return res
+ }
+
+ async fetchSecretValue(id: string) {
+ const query = new Query()
+ .from('decrypted_secrets', 'vault')
+ .select('decrypted_secret')
+ .match({ id })
+ .toSql()
+ const res = await this.rootStore.meta.query(query)
+ if (!res.error) {
+ this.data.secrets = this.data.secrets.map((secret) => {
+ if (secret.id === id) {
+ return { ...secret, decryptedSecret: res[0].decrypted_secret }
+ } else {
+ return secret
+ }
+ })
+ }
+ return res[0].decrypted_secret
+ }
}
diff --git a/studio/types/ui.ts b/studio/types/ui.ts
index e14c8948e7e..a4fd0ddae12 100644
--- a/studio/types/ui.ts
+++ b/studio/types/ui.ts
@@ -19,3 +19,13 @@ export interface ChartIntervals {
startUnit: 'hour' | 'day'
format: 'MMM D, h:mma' | 'MMM D, ha' | 'MMM D'
}
+
+export interface VaultSecret {
+ id: string
+ name: string
+ description: string
+ secret: string
+ decryptedSecret?: string
+ key_id: string
+ created_at: string
+}