Skip to content

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

big database refactor

Coppleddc24fdc832e
diff --git a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
index 12c5df4b5d5..747abf433a3 100644
--- a/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
+++ b/apps/docs/components/Navigation/NavigationMenu/NavigationMenu.constants.ts
@@ -508,14 +508,33 @@ export const database: NavMenuConstant = {
title: 'Database',
url: '/guides/database',
items: [
- { name: 'Database Connections', url: '/guides/database/connecting-to-postgres' },
- { name: 'Tables and Data', url: '/guides/database/tables' },
- { name: 'Database Functions', url: '/guides/database/functions' },
- { name: 'Database Webhooks', url: '/guides/database/webhooks' },
- { name: 'Full Text Search', url: '/guides/database/full-text-search' },
- { name: 'Database Testing', url: '/guides/database/testing' },
- { name: 'Managing Secrets with Vault', url: '/guides/database/vault' },
- { name: 'Column Encryption', url: '/guides/database/column-encryption' },
+ { name: 'Overview', url: '/guides/database' },
+ {
+ name: 'Fundamentals',
+ url: undefined,
+ items: [
+ { name: 'Connecting to your database', url: '/guides/database/connecting-to-postgres' },
+ { name: 'Managing tables, views, and data', url: '/guides/database/tables' },
+ { name: 'Managing database functions', url: '/guides/database/functions' },
+ { name: 'Managing indexes', url: '/guides/database/postgres/indexes' },
+ { name: 'Managing database webhooks', url: '/guides/database/webhooks' },
+ { name: 'Managing database replication', url: '/guides/database/replication' },
+ { name: 'Managing secrets with Vault', url: '/guides/database/vault' },
+ ],
+ },
+ {
+ name: 'Postgres Guides',
+ url: undefined,
+ items: [
+ { name: 'Implementing Full Text Search', url: '/guides/database/full-text-search' },
+ { name: 'Implementing Cascade Deletes', url: '/guides/database/postgres/cascade-deletes' },
+ { name: 'Implementing column encryption', url: '/guides/database/column-encryption' },
+ { name: 'Testing your database', url: '/guides/database/testing' },
+ { name: 'Managing Timeouts', url: '/guides/database/timeouts' },
+ { name: 'Managing Passwords', url: '/guides/database/managing-passwords' },
+ { name: 'Configuring Timezones', url: '/guides/database/managing-timezones' },
+ ],
+ },
{
name: 'Extensions',
url: undefined,
@@ -622,17 +641,9 @@ export const database: NavMenuConstant = {
],
},
{
- name: 'Postgres resources',
+ name: 'Examples',
url: undefined,
items: [
- {
- name: 'Managing Indexes',
- url: '/guides/database/postgres/indexes',
- },
- {
- name: 'Cascade Deletes',
- url: '/guides/database/postgres/cascade-deletes',
- },
{
name: 'Drop All Tables in Schema',
url: '/guides/database/postgres/dropping-all-tables-in-schema',
@@ -647,16 +658,6 @@ export const database: NavMenuConstant = {
},
],
},
- {
- name: 'Configuration',
- url: undefined,
- items: [
- { name: 'Timeouts', url: '/guides/database/timeouts' },
- { name: 'Replication', url: '/guides/database/replication' },
- { name: 'Passwords', url: '/guides/database/managing-passwords' },
- { name: 'Timezones', url: '/guides/database/managing-timezones' },
- ],
- },
],
}
diff --git a/apps/docs/pages/guides/api.mdx b/apps/docs/pages/guides/api.mdx
index 390dcadd33d..7ca9052585d 100644
--- a/apps/docs/pages/guides/api.mdx
+++ b/apps/docs/pages/guides/api.mdx
@@ -74,6 +74,17 @@ Supabase provides a Realtime API using [Realtime](https://github.com/supabase/re
Realtime leverages PostgreSQL's built-in logical replication. You can manage your Realtime API simply by managing Postgres publications.
Go to your project's [Replication section](https://app.supabase.com/project/_/database/replication) to get started.
+## API URL and Keys
+
+You can find the API URL and Keys in the [Dashboard](https://app.supabase.com/project/_/settings/api).
+
+<video width="99%" muted playsInline controls={true}>
+ <source
+ src="https://xguihxuzqibwxjnimxev.supabase.co/storage/v1/object/public/videos/docs/api/api-url-and-key.mp4"
+ type="video/mp4"
+ />
+</video>
+
export const Page = ({ children }) => <Layout meta={meta} children={children} />
export default Page
diff --git a/apps/docs/pages/guides/database/column-encryption.mdx b/apps/docs/pages/guides/database/column-encryption.mdx
index 80ed59f1705..5539bfc0a37 100644
--- a/apps/docs/pages/guides/database/column-encryption.mdx
+++ b/apps/docs/pages/guides/database/column-encryption.mdx
@@ -3,20 +3,17 @@ import Layout from '~/layouts/DefaultGuideLayout'
export const meta = {
id: 'column-encryption',
title: 'Column Encryption',
- description: 'Use Supabase to store and serve files.',
+ description: 'Encrypt columns using Transparent Column Encryption.',
+ subtitle: 'Encrypt columns using Transparent Column Encryption.',
sidebar_label: 'Overview',
video: 'https://www.youtube.com/v/J9mTPY8rIXE',
}
-Encrypted Columns for Tables
+Supabase provides a secure method for encrypting columns using [Vault](/docs/guides/database/vault), our Postgres secrets manager. Vault is Postgres extension with an integrated UI intended to act as a secure global secrets management for you project.
-## Transparent Column Encryption (TCE)
+Vault enables an advance feature called Transparent Column Encryption (TCE) which provides a safe way to encrypt your data so that it doesn't leak into logs and backups. TCE provides a safe way to encrypt your data so that it doesn't leak into logs and backups. It can also provide row-level authenticated encryption.
-TCE provides a safe way to encrypt your data so that it doesn't leak into logs and backups. It can also provide row-level authenticated encryption.
-
-TCE is the primary building block of [Vault](/docs/guides/database/vault), Supabase's Postgres secrets manager. Vault is a built-in table with an integrated UI intended to act as a secure global secrets management for you project. However if you need more fine-grain control over your encrypted data, such as encrypting columns in your own tables, you can use TCE directly. Any Postgres value that can be cast to `text` or `bytea` can be encrypted using TCE.
-
-### Encrypting columns
+## Encrypting columns
When creating a new column in the Dashboard, you can choose to encrypt a `text` or `bytea` column. You will choose which key you would like to encrypt it with by selecting an existing key ID or creating a new one.
@@ -26,10 +23,50 @@ Once you've created an encrypted column, you can insert data into the table like
![Encrypted data](/docs/img/guides/database/vault-encrypted-data.png)
+## Decrypting data
+
Decrypted data is accessed using a special view that is automatically created after adding an encrypted column to a table. This view decrypts the data row-by-row as you access it. By default, this view is called `decrypted_<your-table-name>`. In the example below, the decryption view for the `profiles` table is called `decrypted_profiles`. Notice there is a new column in the view called `decrypted_emails` that contains the decrypted email value.
![Decrypted data](/docs/img/guides/database/vault-decrypted-data.png)
+## Using an Encrypted Table
+
+Now that you have TCE setup for a table, it's easy to use by simply inserting data into the table, and querying that data by looking at its generated view. The view is named `decrypted_<table_name>` and by default is in the same schema as your table:
+
+```sql
+insert into secrets
+ (secret, account_id)
+values
+ ('1234-5678-8765-4321', 123);
+```
+
+Now that you have inserted data, look at the table and notice how the secret is encrypted. This is the data that is stored on disk, the encrypted card number, the key id, and the account id, **but the key itself is not stored**. This means if someone gets a backup or dump of your database, they cannot decrypt the secret, they do not have the key, only the key ID:
+
+```sql
+> select * from secrets where account_id = 123;
+-[ RECORD 1 ]------+---------------------------------------------------------------------
+id | 1
+secret | jf8KfImkKTr+j4gzyDZQtLDEFL9eSlFuKjNlNEJvDg+OIKUr2wjF/8NnYcLisb5F9xiN
+account_id | 123
+key_id | 7f753c4f-8c68-457a-8801-1798b2e9f44d
+nonce | \x300a14aa721184ff7cf0f6bf088da267
+```
+
+For you, the developer, you need the unencrypted secret for you application. No problem, you can access that data using the dynamically generated decryption view `decrypted_secrets`:
+
+```sql
+> select * from decrypted_secrets where account_id = 123;
+-[ RECORD 1 ]----------------+---------------------------------------------------------------------
+id | 1
+secret | jf8KfImkKTr+j4gzyDZQtLDEFL9eSlFuKjNlNEJvDg+OIKUr2wjF/8NnYcLisb5F9xiN
+decrypted_secret | 1234-5678-8765-4321
+account_id | 123
+key_id | 7f753c4f-8c68-457a-8801-1798b2e9f44d
+nonce | \x300a14aa721184ff7cf0f6bf088da267
+```
+
+Notice how there is a new column called `decrypted_secret`. This column is not stored in database or on disk at all, it is generated “on-the-fly” as you select from the view. Database dumps do not contain this information, only the view itself, and most importantly, **raw decryption keys are never stored**.
+
## How Key Derivation Works
The current state-of-the-art in encryption libraries is [libsodium](https://doc.libsodium.org/).
@@ -202,43 +239,7 @@ security label for pgsodium
The new label indicates which column is to be associated with the secret, and that's it! Your `account_id` and secret are now protected under the same authentication signature as the secret itself.
-## Using an Encrypted Table
-
-Now that you have TCE setup for a table, it's easy to use by simply inserting data into the table, and querying that data by looking at its generated view. The view is named `decrypted_<table_name>` and by default is in the same schema as your table:
-
-```sql
-insert into secrets
- (secret, account_id)
-values
- ('1234-5678-8765-4321', 123);
-```
-
-Now that you have inserted data, look at the table and notice how the secret is encrypted. This is the data that is stored on disk, the encrypted card number, the key id, and the account id, **but the key itself is not stored**. This means if someone gets a backup or dump of your database, they cannot decrypt the secret, they do not have the key, only the key ID:
-
-```sql
-> select * from secrets where account_id = 123;
--[ RECORD 1 ]------+---------------------------------------------------------------------
-id | 1
-secret | jf8KfImkKTr+j4gzyDZQtLDEFL9eSlFuKjNlNEJvDg+OIKUr2wjF/8NnYcLisb5F9xiN
-account_id | 123
-key_id | 7f753c4f-8c68-457a-8801-1798b2e9f44d
-nonce | \x300a14aa721184ff7cf0f6bf088da267
-```
-
-For you, the developer, you need the unencrypted secret for you application. No problem, you can access that data using the dynamically generated decryption view `decrypted_secrets`:
-
-```sql
-> select * from decrypted_secrets where account_id = 123;
--[ RECORD 1 ]----------------+---------------------------------------------------------------------
-id | 1
-secret | jf8KfImkKTr+j4gzyDZQtLDEFL9eSlFuKjNlNEJvDg+OIKUr2wjF/8NnYcLisb5F9xiN
-decrypted_secret | 1234-5678-8765-4321
-account_id | 123
-key_id | 7f753c4f-8c68-457a-8801-1798b2e9f44d
-nonce | \x300a14aa721184ff7cf0f6bf088da267
-```
-
-Notice how there is a new column called `decrypted_secret`. This column is not stored in database or on disk at all, it is generated “on-the-fly” as you select from the view. Database dumps do not contain this information, only the view itself, and most importantly, **raw decryption keys are never stored**.
+## Resources
- [Supabase Vault](/docs/guides/database/vault)
- Read more about Supabase Vault in the [blog post](https://supabase.com/blog/vault-now-in-beta)
diff --git a/apps/docs/pages/guides/database/connecting-to-postgres.mdx b/apps/docs/pages/guides/database/connecting-to-postgres.mdx
index 0ac5493110d..e2c421054da 100644
--- a/apps/docs/pages/guides/database/connecting-to-postgres.mdx
+++ b/apps/docs/pages/guides/database/connecting-to-postgres.mdx
@@ -1,4 +1,5 @@
import Layout from '~/layouts/DefaultGuideLayout'
+import StepHikeCompact from '~/components/StepHikeCompact'
export const meta = {
id: 'connecting-to-postgres',
@@ -8,82 +9,76 @@ export const meta = {
Supabase provides several options for programmatically connecting to your Postgres database:
-## Types of Connection
+1. Direct connections using Postgres' standard connection system
+2. Connection pooling using PgBouncer
+3. Programmatic access uing the [Serverless APIs](/docs/guides/api)
-- HTTP connections using the API.
-- Direct connections using Postgres' standard connection system.
-- Connection pooling using PgBouncer.
+## Serverless APIs
-### Direct vs Pooling vs API
-
-- A "direct connection" is when a connection is made to the database using Postgres' native connection implementation. You should use this for tools which are always alive - usually installed on a long-running server.
-- A "connection pool" is a system (external to Postgres) which keeps connections "open". You should use this for serverless functions and tools which disconnect from the database frequently.
-- The API is an auto-generated REST interface. You should use this for all browser and application interactions. The API server internally handles a connection pool.
-
-Why would you use a connection pool? Primarily because the way that Postgres handles connections isn't very scalable for a large number of _temporary_ connections.
-You can use these simple questions to determine which connection method to use:
-
-- Are you connecting to a database and _maintaining_ a connection? If yes, use a direct connection.
-- Are you connecting to your database and then _disconnecting_ immediately (e.g. a serverless environment)? If yes, use a connection pool.
-
-## API
-
-Supabase provides an auto-updating [API](/docs/guides/database/api). This is the easiest way to get started if you are managing data (fetching, inserting, updating).
-
-### Interfaces
-
-We provides several types of API to suit your preferences and use-case:
+Supabase provides auto-updating [APIs](/docs/guides/database/api). This is the easiest way to get started if you are managing data (fetching, inserting, updating). We provides several types of API to suit your preferences:
- [REST](/docs/guides/database/api#rest-api): interact with your database through a REST interface.
- [GraphQL](/docs/guides/database/api#graphql-api): interact with your database through a GraphQL interface.
- [Realtime](/docs/guides/database/api#realtime-api): listen to database changes over websockets.
-You cannot manage the database schema via the API (for security reasons). To do that you can use the dashboard or connect directly to your database.
+## Direct connections
-### API URL and Keys
+Every Supabase project provides a full Postgres database. You can connect to the database using [any tool which supports Postgres](#integrations). You can find the connection string in the [Database settings](https://app.supabase.com/project/_/settings/database) inside the dashboard:
-You can find the API URL and Keys in the [Dashboard](https://app.supabase.com/project/_/settings/api).
+1. Go to the `Settings` section.
+2. Click `Database`.
+3. Find your Connection Info and Connection String. Direct connections are on port `5432`.
<video width="99%" muted playsInline controls={true}>
<source
- src="https://xguihxuzqibwxjnimxev.supabase.co/storage/v1/object/public/videos/docs/api/api-url-and-key.mp4"
+ src="https://xguihxuzqibwxjnimxev.supabase.co/storage/v1/object/public/videos/docs/postgres-connection.mp4"
type="video/mp4"
/>
</video>
-## Direct connections
+## Connection Pooler
-Every Supabase project provides a full Postgres database. You can connect to the database using any tool which supports Postgres.
-
-### Finding your connection string
+Every Supabase project comes with PgBouncer for connection pooling. A connection pooler is useful for managing a large number of _temporary_ connections. For example, if you are using [Prisma](/docs/guides/integrations/prisma), Drizzle, Kysely, or anything deployed to a Serverless environment (AWS Lambdas or Edge Functions). You can find the connection pool config in the [Database settings](https://app.supabase.com/project/_/settings/database) inside the dashboard:
1. Go to the `Settings` section.
2. Click `Database`.
-3. Find your Connection Info and Connection String. Direct connections are on port `5432`.
+3. Find your Connection Info and Connection String. Connection pooling is on port `6543`.
<video width="99%" muted playsInline controls={true}>
<source
- src="https://xguihxuzqibwxjnimxev.supabase.co/storage/v1/object/public/videos/docs/postgres-connection.mp4"
+ src="https://xguihxuzqibwxjnimxev.supabase.co/storage/v1/object/public/videos/docs/connection-pool-config.mp4"
type="video/mp4"
/>
</video>
-## Connection Pool
+## Choosing a connection method
+
+- The Serverless APIs provide programmatic access and have built-in connection pooling. You can use these for all browser and application interactions. We recommend using these wherever possible.
+- A "direct connection" is Postgres' native connection system. You should use this for tools which are always alive - usually installed on a long-running server, like Node.js, Ruby, Python, etc.
+- A "connection pooler" is a tool which keeps connections "alive". You should use this for serverless functions and tools which disconnect from the database frequently, like Prisma, Drizzle, Kysely, etc.
+
+Why would you use a connection pool? Primarily because the way that Postgres handles connections isn't very scalable for a large number of _temporary_ connections. You can use these simple questions to determine which connection method to use:
+
+- Are you connecting to a database and _maintaining_ a connection? If yes, use a direct connection.
+- Are you connecting to your database and then _disconnecting_ immediately (e.g. a serverless environment)? If yes, use a connection pool.
+
+## Connecting with SSL
+
+You should connect to your database using SSL wherever possible, to prevent snooping and man-in-the-middle attacks.
-Connection pools are useful for managing a large number of _temporary_ connections. For example, if you are using [Prisma](/docs/guides/integrations/prisma) deployed to a Serverless environment.
+You can obtain your connection info and Server root certificate from your application's dashboard:
-### How connection pooling works
+![Connection Info and Certificate.](/docs/img/guides/database/connection-info-cert.png)
+
+## How connection pooling works
A "connection pool" is a system (external to Postgres) which manages connections, rather than PostgreSQL's native system. Supabase uses [PgBouncer](https://www.pgbouncer.org/) for connection pooling.
-When a client makes a request, PgBouncer "allocates" an available connection to the client.
-When the client transaction or session is completed the connection is returned to the pool and is free to be used by another client.
+When a client makes a request, PgBouncer "allocates" an available connection to the client. When the client transaction or session is completed the connection is returned to the pool and is free to be used by another client.
![Connection pooling](/docs/img/guides/database/connection-pool.png)
-### Pool modes
-
-Pool Mode determines how PgBouncer handles a connection.
+Pgbounce provides several Pool Modes, each handling connections differently:
#### Session
@@ -93,57 +88,97 @@ All PostgreSQL features can be used with this option.
#### Transaction
-This is the suggested option for serverless functions. A connection is only assigned to the client for the duration of a transaction. Two consecutive transactions from the same client
-could be executed over two different connections.
+This is the suggested option for serverless functions. A connection is only assigned to the client for the duration of a transaction. Two consecutive transactions from the same client could be executed over two different connections.
-Some session-based PostgreSQL features such as prepared statements are not available with this option.
-A comprehensive list of incompatible features can be found [here](https://www.pgbouncer.org/features.html).
+Some session-based PostgreSQL features such as prepared statements are not available with this option. A comprehensive list of incompatible features can be found [here](https://www.pgbouncer.org/features.html).
#### Statement
This is the most granular option. Connections are returned to the pool after every statement. Transactions with multiple statements are not allowed. This is best used when `AUTOCOMMIT` is in use.
-### Finding the connection pool config
+## Integrations
-1. Go to the `Settings` section.
-2. Click `Database`.
-3. Find your Connection Info and Connection String. Connection pooling is on port `6543`.
+### Connecting with psql
-<video width="99%" muted playsInline controls={true}>
- <source
- src="https://xguihxuzqibwxjnimxev.supabase.co/storage/v1/object/public/videos/docs/connection-pool-config.mp4"
- type="video/mp4"
- />
-</video>
+[`psql`](https://www.postgresql.org/docs/current/app-psql.html) is a command-line tool that comes with Postgres.
-## Connecting with SSL
+Assuming you've downloaded your SSL certificate to `$HOME/Downloads/prod-supabase.cer`, and your host address is `db.ref.supabase.co` you connect to your database via SSL:
+
+```shell
+psql "sslmode=verify-full sslrootcert=$HOME/Downloads/prod-supabase.cer host=db.ref.supabase.co dbname=postgres user=postgres"
+```
-Use this when connecting to your database to prevent snooping and man-in-the-middle attacks.
+### Connecting with pgAdmin
-Obtain your connection info and Server root certificate from your application’s dashboard.
-![Connection Info and Certificate.](/docs/img/guides/database/connection-info-cert.png)
+[`pgAdmin`](https://www.pgadmin.org/) is a GUI tool for managing Postgres databases. You can use it to connect to your database via SSL:
-Assuming you’ve downloaded your certificate and it’s located at `$HOME/Downloads/prod-ca-2021.cer`, and your Host address is `db.abcdefghijklm.supabase.co` you can connect to the DB with
-SSL enabled as illustrated below:
+<StepHikeCompact>
-1. With `psql`
+ <StepHikeCompact.Step step={1}>
-```
-psql "sslmode=verify-full sslrootcert=$HOME/Downloads/prod-ca-2021.cer host=db.abcdefghijklm.supabase.co dbname=postgres user=postgres"
-```
+ <StepHikeCompact.Details title="Register">
+
+ Register a new Postgres server.
+
+ </StepHikeCompact.Details>
+
+ <StepHikeCompact.Code>
+
+ ![Register a new postgres server.](/docs/img/guides/database/register-server-pgAdmin.png)
+
+ </StepHikeCompact.Code>
+
+ </StepHikeCompact.Step>
+
+ <StepHikeCompact.Step step={2}>
+
+ <StepHikeCompact.Details title="Name">
+
+ Name your server.
+
+ </StepHikeCompact.Details>
+
+ <StepHikeCompact.Code>
+
+ ![Name Postgres Server.](/docs/img/guides/database/name-pg-server.png)
+
+ </StepHikeCompact.Code>
+
+ </StepHikeCompact.Step>
+
+ <StepHikeCompact.Step step={3}>
+
+ <StepHikeCompact.Details title="Connect">
+
+ Add the connection info. You can use the "Direct connection" config, which you can find in your Supabase dashboard.
+
+ </StepHikeCompact.Details>
+
+ <StepHikeCompact.Code>
+
+ ![Add Connection Info.](/docs/img/guides/database/add-pg-server-conn-info.png)
+
+ </StepHikeCompact.Code>
+
+ </StepHikeCompact.Step>
+
+ <StepHikeCompact.Step step={4}>
+
+ <StepHikeCompact.Details title="SSL">
+
+ Navigate to the SSL tab and change the SSL mode to Require. Next navigate to the Root certificate input, it will open up a file-picker modal. Select the certificate you downloaded from your Supabase dashboard and save the server details. PgAdmin should now be able to connect to your Postgres via SSL.
+
+ </StepHikeCompact.Details>
+
+ <StepHikeCompact.Code>
+
+ ![Add Connection Info.](/docs/img/guides/database/add-ssl-config.png)
-2. With `pgAdmin`
- a. Register a new Postgres server
- ![Register a new postgres server.](/docs/img/guides/database/register-server-pgAdmin.png)
+ </StepHikeCompact.Code>
- b. Name your server to your liking and add the connection info.
- ![Name Postgres Server.](/docs/img/guides/database/name-pg-server.png)
- ![Add Connection Info.](/docs/img/guides/database/add-pg-server-conn-info.png)
+ </StepHikeCompact.Step>
-3. Navigate to the SSL tab and change the SSL mode to Require. Next navigate to the Root certificate input, it will open up a
- file-picker modal. Select the certificate you downloaded from your Supabase dashboard and save the server details. PgAdmin
- should now be able to connect to your Postgres via SSL.
- ![Add Connection Info.](/docs/img/guides/database/add-ssl-config.png)
+</StepHikeCompact>
export const Page = ({ children }) => <Layout meta={meta} children={children} />
diff --git a/apps/docs/pages/guides/database/vault.mdx b/apps/docs/pages/guides/database/vault.mdx
index 683d383219b..0d32b241104 100644
--- a/apps/docs/pages/guides/database/vault.mdx
+++ b/apps/docs/pages/guides/database/vault.mdx
@@ -3,19 +3,15 @@ import Layout from '~/layouts/DefaultGuideLayout'
export const meta = {
id: 'vault',
title: 'Vault',
- description: 'Use Supabase to store and serve files.',
+ description:
+ 'Vault is a Postgres extension and accompanying Supabase UI that makes it safe and easy to store encrypted secrets.',
+ subtitle: 'Managing secrets in Postgres.',
sidebar_label: 'Overview',
video: 'https://www.youtube.com/v/J9mTPY8rIXE',
}
-Supabase Vault provides encrypted secret storage and Encrypted Columns for Tables.
-
Vault is a Postgres extension and accompanying Supabase UI that makes it safe and easy to store encrypted secrets and other data in your database. This opens up a lot of possibilities to use Postgres in ways that go beyond what is available in a stock distribution.
-From a product perspective, Supabase groups a number of related features under the “Vault banner”. Let's explore a few of these features.
-
-## Secrets Management
-
Under the hood, the Vault is a table of Secrets and Encryption Keys that are stored using [Authenticated Encryption](https://en.wikipedia.org/wiki/Authenticated_encryption) on disk. They are then available in decrypted form through a Postgres view so that the secrets can be used by applications from SQL. Because the secrets are stored on disk encrypted and authenticated, any backups or replication streams also preserve this encryption in a way that can't be decrypted or forged.
Supabase provides a dashboard UI for the Vault that makes storing secrets easy. Click a button, type in your secret, and save. Optionally create your own keys you can use to encrypt your secret. Your secret will then be stored on disk encrypted using the specified key.
@@ -31,79 +27,48 @@ Supabase provides a dashboard UI for the Vault that makes storing secrets easy.
There are two main parts to the Vault UI, Secrets and Encryption Keys:
-- **Secrets:** Use the Vault to store Secrets - everything from Environment Variables to API Keys. You can use these Secrets anywhere in your database: Postgres [Functions](/docs/guides/database/functions), Triggers, and [Webhooks](/docs/guides/database/webhooks). From a SQL perspective, accessing secrets is as easy as querying a table (or in this case, a view). The underlying secrets tables will be stored in encrypted form.
-- **Encryption Keys:** These are keys used to encrypt data inside your database. You can create different Encryption Keys for different purposes, for example: one for encrypting user-data, and another for application-data. Each key is encrypted itself using a root encryption key that lives outside of the database. See **[Encryption key location](#encryption-key-location)** for more details.
+## Secrets
-## Deep Dive on How The Vault works
+You can use the Vault to store secrets - everything from Environment Variables to API Keys. You can then use these secrets anywhere in your database: Postgres [Functions](/docs/guides/database/functions), Triggers, and [Webhooks](/docs/guides/database/webhooks). From a SQL perspective, accessing secrets is as easy as querying a table (or in this case, a view). The underlying secrets tables will be stored in encrypted form.
-<div className="video-container">
- <iframe
- src="https://www.youtube-nocookie.com/embed/QHLPNDrdN2w"
- title="YouTube video player"
- frameborder="0"
- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
- allowfullscreen
- ></iframe>
-</div>
+## Encryption Keys
-As we mentioned, the Vault uses pgsodium's Transparent Column Encryption (TCE) to store secrets in an authenticated encrypted form. There are some details around that you may be curious about, what does authenticated mean, and where are encryption keys store? This section explains those details.
+These are keys used to encrypt data inside your database. You can create different Encryption Keys for different purposes, for example: one for encrypting user-data, and another for application-data. Each key is encrypted itself using a root encryption key that lives outside of the database. See **[Encryption key location](#encryption-key-location)** for more details.
-### Authenticated Encryption with Associated Data
-
-The first important feature of TCE is that it uses an [Authenticated Encryption with Associated Data](<https://en.wikipedia.org/wiki/Authenticated_encryption#Authenticated_encryption_with_associated_data_(AEAD)>) encryption algorithm (based on libsodium).
-
-### Encryption key location
-
-**Authenticated Encryption** means that in addition to the data being encrypted, it is also signed so that it cannot be forged. You can guarantee that the data was encrypted by someone you trust, which you wouldn't get with encryption alone. The decryption function verifies that the signature is valid _before decrypting the value_.
-
-**Associated Data** means that you can include any other columns from the same row as part of the signature computation. This doesn't encrypt those other columns - rather it ensures that your encrypted value is only associated with columns from that row. If an attacker were to copy an encrypted value from another row to the current one, the signature would be rejected (assuming you used a unique column in the associated data).
-
-Another important feature of pgsodium is that the encryption keys are never stored in the database alongside the encrypted data. Instead, only a **Key ID** is stored, which is a reference to the key that is only accessible outside of SQL. Even if an attacker can capture a dump of your entire database, they will see only encrypted data and key IDs, _never the raw key itself_.
-
-This is an important safety precaution - there is little value in storing the encryption key in the database itself as this would be like locking your front door but leaving the key in the lock! Storing the key outside the database fixes this issue.
+## Using the Vault
-Where are the keys stored? Supabase creates and manages the root keys (from which all key IDs are derived) in our secured backend systems. We keep this root key safe and separate from your data. You remain in control of your keys - a separate API endpoint is available that you can use to access the key if you want to decrypt your data outside of Supabase.
+You can manage secrets and encryption keys from the UI or using SQL.
-## Using the Vault
+### Adding secrets
-Using the vault is as simple as `INSERT`ing data into the
-`vault.secret` table.
+There is also a handy function for creating secrets called `vault.create_secret()`:
```sql
-postgres=> insert into vault.secrets (secret) values ('s3kre3t_k3y') returning *;
--[ RECORD 1 ]-------------------------------------------------------------
-id | d91596b8-1047-446c-b9c0-66d98af6d001
-name |
-description |
-secret | S02eXS9BBY+kE3r621IS8beAytEEtj+dDHjs9/0AoMy7HTbog+ylxcS22A==
-key_id | 7f5ad44b-6bd5-4c99-9f68-4b6c7486f927
-nonce | \x3aa2e92f9808e496aa4163a59304b895
-created_at | 2022-12-14 02:29:21.3625+00
-updated_at | 2022-12-14 02:29:21.3625+00
+select vault.create_secret('my_s3kre3t');
```
-There is also a handy function for creating secrets called
-`vault.create_secret()`:
+The function returns the UUID of the new secret.
+
+<details>
+<summary>Show Result</summary>
```sql
-postgres=> select vault.create_secret('another_s3kre3t');
-[ RECORD 1 ]-+-------------------------------------
create_secret | c9b00867-ca8b-44fc-a81d-d20b8169be17
-
```
-The function returns the UUID of the new secret.
-
-## Name and Description
+</details>
-Secrets can also have an optional _unique_ name, or an optional description. These are also arguments to `vault.create_secret()`:
+Secrets can also have an optional _unique_ name and an optional description. These are also arguments to `vault.create_secret()`:
```sql
-postgres=> select vault.create_secret('another_s3kre3t', 'unique_name', 'This is the description');
--[ RECORD 1 ]-+-------------------------------------
-create_secret | 7095d222-efe5-4cd5-b5c6-5755b451e223
+select vault.create_secret('another_s3kre3t', 'unique_name', 'This is the description');
+```
+
+<details>
+<summary>Show Result</summary>
-postgres=> select * from vault.secrets where id = '7095d222-efe5-4cd5-b5c6-5755b451e223';
+```sql
-[ RECORD 1 ]-----------------------------------------------------------------
id | 7095d222-efe5-4cd5-b5c6-5755b451e223
name | unique_name
@@ -115,12 +80,49 @@ created_at | 2022-12-14 02:34:23.85159+00
updated_at | 2022-12-14 02:34:23.85159+00
```
-## Querying Data from the Vault
+</details>
+
+Alternatively, you can create a secret by `insert`ing data into the `vault.secret` table:
+
+{/* prettier-ignore */}
+```sql
+insert into vault.secrets (secret)
+values ('s3kre3t_k3y') returning *;
+```
+
+<details>
+<summary>Show Result</summary>
+
+```sql
+-[ RECORD 1 ]-------------------------------------------------------------
+id | d91596b8-1047-446c-b9c0-66d98af6d001
+name |
+description |
+secret | S02eXS9BBY+kE3r621IS8beAytEEtj+dDHjs9/0AoMy7HTbog+ylxcS22A==
+key_id | 7f5ad44b-6bd5-4c99-9f68-4b6c7486f927
+nonce | \x3aa2e92f9808e496aa4163a59304b895
+created_at | 2022-12-14 02:29:21.3625+00
+updated_at | 2022-12-14 02:29:21.3625+00
+```
+
+</details>
+
+### Viewing secrets
If you look in the `vault.secrets` table, you will see that your data is stored encrypted. To decrypt the data, there is an automatically created view `vault.decrypted_secrets`. This view will decrypt secret data on the fly:
+{/* prettier-ignore */}
+```sql
+select *
+from vault.decrypted_secrets
+order by created_at desc
+limit 3;
+```
+
+<details>
+<summary>Show Result</summary>
+
```sql
-postgres=> select * from vault.decrypted_secrets order by created_at desc limit 3;
-[ RECORD 1 ]----+-----------------------------------------------------------------
id | 7095d222-efe5-4cd5-b5c6-5755b451e223
name | unique_name
@@ -153,17 +155,30 @@ created_at | 2022-12-14 02:29:21.3625+00
updated_at | 2022-12-14 02:29:21.3625+00
```
+</details>
+
Notice how this view has a `decrypted_secret` column that contains the decrypted secrets. Views are not stored on disk, they are only run at query time, so the secret remains encrypted on disk, and in any backup dumps or replication streams.
You should ensure that you protect access to this view with the appropriate SQL privilege settings at all times, as anyone that has access to the view has access to decrypted secrets.
-## Updating Secrets
+### Updating Secrets
A secret can be updated with the `vault.update_secret()` function, this function makes updating secrets easy, just provide the secret UUID as the first argument, and then an updated secret, updated optional unique name, or updated description:
```sql
-postgres=> select vault.update_secret('7095d222-efe5-4cd5-b5c6-5755b451e223', 'n3w_upd@ted_s3kret',
- 'updated_unique_name', 'This is the updated description');
+select
+ vault.update_secret(
+ '7095d222-efe5-4cd5-b5c6-5755b451e223',
+ 'n3w_upd@ted_s3kret',
+ 'updated_unique_name',
+ 'This is the updated description'
+ );
+```
+
+<details>
+<summary>Show Result</summary>
+
+```sql
-[ RECORD 1 ]-+-
update_secret |
@@ -180,6 +195,38 @@ created_at | 2022-12-14 02:34:23.85159+00
updated_at | 2022-12-14 02:51:13.938396+00
```
+</details>
+
+## Deep Dive on How The Vault works
+
+<div className="video-container">
+ <iframe
+ src="https://www.youtube-nocookie.com/embed/QHLPNDrdN2w"
+ title="YouTube video player"
+ frameborder="0"
+ allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
+ allowfullscreen
+ ></iframe>
+</div>
+
+As we mentioned, the Vault uses pgsodium's Transparent Column Encryption (TCE) to store secrets in an authenticated encrypted form. There are some details around that you may be curious about, what does authenticated mean, and where are encryption keys store? This section explains those details.
+
+### Authenticated Encryption with Associated Data
+
+The first important feature of TCE is that it uses an [Authenticated Encryption with Associated Data](<https://en.wikipedia.org/wiki/Authenticated_encryption#Authenticated_encryption_with_associated_data_(AEAD)>) encryption algorithm (based on libsodium).
+
+### Encryption key location
+
+**Authenticated Encryption** means that in addition to the data being encrypted, it is also signed so that it cannot be forged. You can guarantee that the data was encrypted by someone you trust, which you wouldn't get with encryption alone. The decryption function verifies that the signature is valid _before decrypting the value_.
+
+**Associated Data** means that you can include any other columns from the same row as part of the signature computation. This doesn't encrypt those other columns - rather it ensures that your encrypted value is only associated with columns from that row. If an attacker were to copy an encrypted value from another row to the current one, the signature would be rejected (assuming you used a unique column in the associated data).
+
+Another important feature of pgsodium is that the encryption keys are never stored in the database alongside the encrypted data. Instead, only a **Key ID** is stored, which is a reference to the key that is only accessible outside of SQL. Even if an attacker can capture a dump of your entire database, they will see only encrypted data and key IDs, _never the raw key itself_.
+
+This is an important safety precaution - there is little value in storing the encryption key in the database itself as this would be like locking your front door but leaving the key in the lock! Storing the key outside the database fixes this issue.
+
+Where are the keys stored? Supabase creates and manages the root keys (from which all key IDs are derived) in our secured backend systems. We keep this root key safe and separate from your data. You remain in control of your keys - a separate API endpoint is available that you can use to access the key if you want to decrypt your data outside of Supabase.
+
## Internal Details
To encrypt data, you need a _key id_. You can use the default key id created automatically for every project, or create your own key ids Using the `pgsodium.create_key()` function. Key ids are used to internally derive the encryption key used to encrypt secrets in the vault. Vault users typically do not have access to the key itself, only the key id.
@@ -209,7 +256,7 @@ And then restart your project from the dashboard to enable that change.
In the future we are researching various ways to refine the way statement logging interacts with sensitive columns.
-## See also
+## Resources
- Read more about Supabase Vault in the [blog post](https://supabase.com/blog/vault-now-in-beta)
- [Supabase Vault on GitHub](https://github.com/supabase/vault)