# PostgreSQL SSO with OIDC, RBAC, and SQL Audit Logs

Use AlmaForge, a self-hosted infrastructure access platform, to give engineers PostgreSQL access with [corporate SSO](https://almaforge.com/sso.md), just-in-time approvals, and per-user SQL audit logs. Engineers can use `psql` or a GUI client. AlmaForge connects to PostgreSQL with short-lived client certificates, and the database can stay on a private network.

Setup takes four steps. Create a join token, configure PostgreSQL and the database agent, grant access through AlmaForge RBAC, and run a query.

info

Running CockroachDB? See the [CockroachDB database access guide](https://almaforge.com/access/databases/cockroachdb.md).

## Prerequisites[​](#prerequisites "Direct link to Prerequisites")

### PostgreSQL CLI[​](#postgresql-cli "Direct link to PostgreSQL CLI")

**On your computer**, check `psql`, the PostgreSQL command-line client:

******Terminal

```bash
psql --version
psql (PostgreSQL) 18.6 (Homebrew)
```

If it is missing, install `libpq`, which includes the client:

******Terminal

```bash
brew install libpq
...
==> Summary
...
export PATH="$(brew --prefix libpq)/bin:$PATH"
psql --version
psql (PostgreSQL) 18.6 (Homebrew)
```

`export` prints nothing. Add the same `export` line to `~/.zshrc` to keep the PATH setting in future terminals. For other operating systems, use [PostgreSQL downloads](https://www.postgresql.org/download/).

### PostgreSQL server[​](#postgresql-server "Direct link to PostgreSQL server")

**On your computer**, open a second terminal and SSH into the database server. Replace `<ssh-user>` and `<database-host>` with your SSH account and server address:

******Terminal

```bash
ssh <ssh-user>@<database-host>
...
[<ssh-user>@<database-host> ~]$
```

**On the database server**, check that you can run administrator commands, then check the operating system and installed database package:

******Terminal

```bash
sudo -v
# No output on success. A password prompt may appear first.
grep -E '^(ID_LIKE|VERSION_ID)=' /etc/os-release
ID_LIKE="rhel centos fedora"
VERSION_ID="9.8"
rpm -q postgresql-server
postgresql-server-13.23-6.el9_8.x86_64
```

`sudo -v` must succeed. If PostgreSQL is not installed, install the distribution's `postgresql-server` package and initialize the database with `postgresql-setup --initdb` before continuing.

This guide uses the `postgresql` systemd service and `/var/lib/pgsql/data` directory. Packages from other repositories may use different service names and paths.

### AlmaForge CLI[​](#almaforge-cli "Direct link to AlmaForge CLI")

**On your computer**, check whether `alma` is installed:

******Terminal

```bash
alma version --client
Client Version: v2026.2.30+gc45932ada6
```

If the command is not found, install it and repeat the check:

******Terminal

```bash
curl -fL https://get.almaforge.com/install.sh | sh
...
==> AlmaForge installed successfully
alma version --client
Client Version: v2026.2.30+gc45932ada6
```

The installer supports Linux and macOS on both amd64 and arm64. See [CLI installation](https://almaforge.com/cli.md#install) for package-specific options.

### AlmaForge Cluster[​](#almaforge-cluster "Direct link to AlmaForge Cluster")

**On your computer**, sign in to your cluster and check your permissions.

Get your cluster's hostname from its administrator. If you do not have an AlmaForge cluster yet, complete the [standalone deployment](https://almaforge.com/deployment/standalone.md) before continuing (or try a local [Quick Start](https://almaforge.com/quickstart.md) evaluation with `alma demo` first). Replace `almaforge.example.com` below with that hostname. Run the login command and complete the sign-in in your browser:

******Terminal

```bash
alma login --proxy=almaforge.example.com:443
```

text

```text
...

> Profile URL:        https://almaforge.example.com:443

  Logged in as:       alice@example.com

  Cluster:            almaforge.example.com

  Roles:              admin

  ...
```

After signing in, check your account and roles:

******Terminal

```bash
alma status
```

text

```text
> Profile URL:        https://almaforge.example.com:443

  Logged in as:       alice@example.com

  Cluster:            almaforge.example.com

  Roles:              admin

  ...
```

In the status output, check that:

* `Cluster` names the cluster you intend to configure.
* `Logged in as` shows your account.
* `Roles` includes `admin`.

If `admin` is missing, ask a cluster administrator to grant that role, then run `alma logout` and repeat the login and status commands. Continue once `Roles` includes `admin`.

## Step 1. Create AlmaForge join token[​](#step-1-create-almaforge-join-token "Direct link to Step 1. Create AlmaForge join token")

**On your computer**, create an AlmaForge [join token](https://almaforge.com/reference/cli.md#tokens). The database agent uses it to join your AlmaForge cluster:

******Terminal

```bash
alma create token --services=database
Token created.
  client_id:     <client-id>
  client_secret: <client-secret>
```

You will copy `client_id` and `client_secret` into the agent configuration in Step 2. They are valid for 30 minutes. If they expire before the agent joins, create a new token and use its values.

## Step 2. Configure the PostgreSQL server[​](#step-2-configure-the-postgresql-server "Direct link to Step 2. Configure the PostgreSQL server")

### Install and configure the agent[​](#install-and-configure-the-agent "Direct link to Install and configure the agent")

The agent is `almad` with its [Database Service](https://almaforge.com/access/databases.md#architecture) enabled. It connects outward to your cluster on port 443 and carries connections between users and PostgreSQL.

**On the PostgreSQL server**, check whether `almad` is installed:

******Terminal

```bash
almad version
AlmaForge v2026.2.30+gc45932ada6
```

If the command is not found, install the AlmaForge package:

******Terminal

```bash
curl -fL https://get.almaforge.com/install.sh | sh
...
==> AlmaForge installed successfully
almad version
AlmaForge v2026.2.30+gc45932ada6
```

On an RPM-based system, the installer uses the RPM package and installs the `almad` systemd service. It supports both amd64 and arm64. The version command must succeed before you configure the agent. For other Linux distributions, see [Linux package installation](https://almaforge.com/deployment/standalone.md#step-1-install-the-package).

Already running an agent on this host?

Keep its existing settings and enable [`ALMA_DATABASE_SERVICE=true`](https://almaforge.com/reference/environment.md#roles). Preserve the other services and label selectors. The join credentials must permit the `database` service. The local target created below does not need a label selector.

**On the PostgreSQL server**, open the agent configuration:

******Terminal

```bash
sudoedit /etc/almaforge/almad.env
# Your text editor opens.
```

For a new agent, enter the settings below. Replace [`ALMA_PROXY`](https://almaforge.com/reference/environment.md#bootstrap) with your cluster's hostname and port 443. Set `ALMA_CLIENT_ID` and `ALMA_CLIENT_SECRET` to the values from Step 1:

[`almad.env`](https://almaforge.com/examples/databases/postgresql/agent/almad.env):

/etc/almaforge/almad.env

```env
# Database Service agent on the PostgreSQL host.

# Install at /etc/almaforge/almad.env as root:root with mode 0600.

ALMA_PROXY=almaforge.example.com:443



# Printed by `alma create token --services=database`.

ALMA_CLIENT_ID=paste-client-id-here

ALMA_CLIENT_SECRET=paste-client-secret-here



ALMA_DATABASE_SERVICE=true

ALMA_SSH_SERVICE=false



# Agent labels, separate from the database's labels.

ALMA_LABELS=env=demo
```

Save the file and close the editor. Restrict it to root because it contains the join credentials:

******Terminal

```bash
sudo chown root:root /etc/almaforge/almad.env
# No output on success.
sudo chmod 0600 /etc/almaforge/almad.env
# No output on success.
```

### Create the TLS certificates[​](#create-the-tls-certificates "Direct link to Create the TLS certificates")

The agent and PostgreSQL run on the same server. Their connection uses the loopback interface (`localhost`, or `127.0.0.1`), so this traffic stays on that server. A self-signed certificate for `localhost` is sufficient. You do not need a public hostname or a certificate from a public CA.

PostgreSQL uses the AlmaForge database CA to verify client certificates presented by the agent.

Keep running these commands **on the PostgreSQL server**.

Download your cluster's public database CA. Replace `almaforge.example.com` with your cluster's hostname:

******Terminal

```bash
curl -fsS -o almaforge-db-ca.pem 'https://almaforge.example.com:443/api/v1/auth/export?type=db'
# No output on success.
openssl x509 -in almaforge-db-ca.pem -noout
# No output means the file contains a valid certificate.
sudo install -o postgres -g postgres -m 0644 almaforge-db-ca.pem /var/lib/pgsql/data/server.cas
# No output on success.
```

Create a self-signed server certificate and private key for `localhost`:

******Terminal

```bash
sudo openssl req -x509 -newkey rsa:2048 -nodes -days 3650 \
    -subj '/CN=localhost' \
    -addext 'subjectAltName=DNS:localhost,IP:127.0.0.1' \
    -keyout /var/lib/pgsql/data/server.key -out /var/lib/pgsql/data/server.crt
...
-----
sudo chown postgres:postgres /var/lib/pgsql/data/server.key /var/lib/pgsql/data/server.crt
# No output on success.
sudo chmod 0600 /var/lib/pgsql/data/server.key
# No output on success.
```

### Enable TLS in PostgreSQL[​](#enable-tls-in-postgresql "Direct link to Enable TLS in PostgreSQL")

Open the PostgreSQL configuration on the server:

******Terminal

```bash
sudoedit /var/lib/pgsql/data/postgresql.conf
# Your text editor opens.
```

Configure PostgreSQL to require TLS and use the certificate files:

[`postgresql.conf`](https://almaforge.com/examples/databases/postgresql/auth/postgresql.conf):

/var/lib/pgsql/data/postgresql.conf

```ini
# Local TLS configuration on a dedicated PostgreSQL host.

# Configures mutual TLS using the local server certificate and AlmaForge database CA.

listen_addresses = 'localhost'

ssl = on

ssl_cert_file = 'server.crt'

ssl_key_file = 'server.key'

ssl_ca_file = 'server.cas'
```

Open `pg_hba.conf` and require client certificates for local TCP connections:

******Terminal

```bash
sudoedit /var/lib/pgsql/data/pg_hba.conf
# Your text editor opens.
```

Replace any existing password or `ident` rules for `127.0.0.1/32` and `::1/128` with the `hostssl ... cert` rules below. PostgreSQL uses the first matching rule, so put these rules above any broader rule that also matches loopback connections. Keep a `local` rule for the `postgres` user's Unix-socket connection.

[`pg_hba.conf`](https://almaforge.com/examples/databases/postgresql/auth/pg_hba.conf):

/var/lib/pgsql/data/pg\_hba.conf

```text
# Local TLS configuration on a dedicated PostgreSQL host.

# Local root and postgres connect over the socket. TCP connections require client certificates.

local   all  all                peer

hostssl all  all  127.0.0.1/32  cert

hostssl all  all  ::1/128       cert
```

Save the file and restart PostgreSQL:

******Terminal

```bash
sudo systemctl restart postgresql
# No output on success.
systemctl is-active postgresql
active
```

### Create the database and accounts[​](#create-the-database-and-accounts "Direct link to Create the database and accounts")

From `/tmp`, run `psql` as the `postgres` user over the local socket to create the demo database, the administrative account for automatic user provisioning, the user role, and the sample table. If you run the command from a home directory with mode `0700`, `sudo -u postgres psql` can print the harmless warning `could not change directory ... Permission denied`.

******Terminal

```bash
cd /tmp
# No output on success.
sudo -u postgres psql -v ON_ERROR_STOP=1 <<'EOF'
SELECT 'CREATE DATABASE demo' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = 'demo')\gexec
SELECT 'CREATE ROLE "alma-admin" LOGIN CREATEROLE' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'alma-admin')\gexec
SELECT 'CREATE ROLE "alma-auto-user"' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'alma-auto-user')\gexec
SELECT 'CREATE ROLE "alma-demo-reader"' WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = 'alma-demo-reader')\gexec
GRANT "alma-auto-user" TO "alma-admin" WITH ADMIN OPTION;
GRANT "alma-demo-reader" TO "alma-admin" WITH ADMIN OPTION;
\c demo
REVOKE CREATE ON SCHEMA public FROM PUBLIC;
GRANT USAGE, CREATE ON SCHEMA public TO "alma-admin";
CREATE TABLE IF NOT EXISTS demo (id INT PRIMARY KEY, name TEXT);
INSERT INTO demo VALUES (1, 'alice'), (2, 'bob'), (3, 'carol') ON CONFLICT DO NOTHING;
GRANT USAGE ON SCHEMA public TO "alma-demo-reader";
GRANT SELECT ON ALL TABLES IN SCHEMA public TO "alma-demo-reader";
EOF
```

### Register PostgreSQL with the agent[​](#register-postgresql-with-the-agent "Direct link to Register PostgreSQL with the agent")

Still **on the PostgreSQL server**, display the public server certificate:

******Terminal

```bash
sudo cat /var/lib/pgsql/data/server.crt
-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----
```

Copy the entire certificate, including the `BEGIN` and `END` lines. The agent uses it to verify PostgreSQL. Then open the [`DatabaseTarget` configuration](https://almaforge.com/reference/configuration.md#databasetarget):

******Terminal

```bash
sudo install -d -o root -g root -m 0700 /etc/almaforge/almad.d
# No output on success.
sudoedit /etc/almaforge/almad.d/postgres.yaml
# Your text editor opens.
```

For a new file, copy the following YAML. If the file already exists, update the existing resource and preserve its other settings. Replace `<paste the complete server certificate here>` with the certificate you copied. Indent every certificate line by six spaces beneath `caCert: |`:

[`target.yaml.in`](https://almaforge.com/examples/databases/postgresql/target.yaml.in):

/etc/almaforge/almad.d/postgres.yaml

```yaml
# PostgreSQL target for an agent running on the database server.

# Replace caCert with the complete server certificate or its issuing CA.

apiVersion: almaforge.com/v1

kind: DatabaseTarget

metadata:

  name: postgres

  labels:

    db: postgresql

    env: prod

spec:

  protocol: postgres

  uri: 127.0.0.1:5432

  adminUser:

    name: alma-admin

    defaultDatabase: demo

  tls:

    caCert: |

      <paste the complete server certificate here>
```

Check that the certificate includes both its `BEGIN` and `END` lines, then save the file and close the editor. Restrict the file to root:

******Terminal

```bash
sudo chown root:root /etc/almaforge/almad.d/postgres.yaml
# No output on success.
sudo chmod 0600 /etc/almaforge/almad.d/postgres.yaml
# No output on success.
```

### Start and check the agent[​](#start-and-check-the-agent "Direct link to Start and check the agent")

Enable the services at boot and start the agent:

******Terminal

```bash
sudo systemctl enable postgresql almad
...
sudo systemctl restart almad
# No output on success.
systemctl is-active postgresql almad
active
active
```

Both services must report `active`. If either fails, inspect its log:

******Terminal

```bash
sudo journalctl -u postgresql -u almad -n 50 --no-pager
...
<date> <time> <database-host> almad[<pid>]: <log-message>
...
```

Resolve any reported errors before continuing. The agent reads the target configuration at startup, so restart `almad` after changing `/etc/almaforge/almad.d/postgres.yaml`.

## Step 3. Grant access[​](#step-3-grant-access "Direct link to Step 3. Grant access")

**On your computer**, confirm that the agent has registered the database:

******Terminal

```bash
alma get db
Host             Name            Protocol       URI                 Labels             Version
---------------- --------------- -------------- ------------------- ------------------ --------
<database-host>  postgres        postgres       <database-uri>      db=postgresql ... 2026.2.30
```

Check that `postgres` appears with protocol `postgres` and your database server in the `Host` column. If either is missing, see [Database is missing or has no host](#database-is-missing-or-has-no-host).

Download [`postgres-access.yaml`](https://almaforge.com/examples/databases/postgresql/roles/postgres-access.yaml) and save it locally. This role allows access to targets labeled `db: postgresql` and to the `demo` database. [`createDbUserMode: keep`](#automatic-user-provisioning) creates a database account named after the user's full AlmaForge login, such as `alice@example.com`, and retains it after the session ends. PostgreSQL grants control what the account can do inside the database. The `alma-demo-reader` role permits reading the sample table.

examples/databases/postgresql/roles/postgres-access.yaml

```yaml
# Allow access to the dedicated PostgreSQL target.

# Map an SSO group to this role in your OIDC connector.

apiVersion: almaforge.com/v1

kind: Role

metadata:

  name: postgresql-access

spec:

  options:

    createDbUserMode: keep # Create an account for the AlmaForge login and retain it after disconnect.

  allow:

    databaseLabels:

      db: postgresql

    databaseRoles:

      - alma-demo-reader

    databaseNames:

      - demo
```

Apply the role:

******Terminal

```bash
alma apply -f postgres-access.yaml
role 'postgresql-access' has been created
```

Creating the role does not assign it to anyone. To grant it to an SSO group, list your connectors:

******Terminal

```bash
alma get oidc
Kind          Name
------------- -----------
OIDCConnector company-sso
```

Find the connector your team uses to sign in. Replace `<connector-name>` with its name from the output, then open it in your text editor:

******Terminal

```bash
alma edit oidc/<connector-name>
# Your text editor opens. After saving your changes:
oidc connector "<connector-name>" has been updated
```

Under `spec.claimsToRoles`, find the entry for the group that should have PostgreSQL access. Add `postgresql-access` to that entry's `roles` list. Preserve the existing roles and mappings, including those that grant `admin`, then save and close the editor. The command applies your changes. If the group has no mapping yet, follow [OIDC role mapping](https://almaforge.com/sso/oidc.md#step-3-write-the-oidcconnector) to add one, or check [Identity provider group mapping](#identity-provider-group-mapping) below for Okta, Microsoft Entra ID, and Google Workspace group formats.

## Step 4. Connect[​](#step-4-connect "Direct link to Step 4. Connect")

**On your computer**, sign out of saved sessions, then sign back in with an account in the group granted access in Step 3. `logout` clears saved sessions for all clusters. Use your cluster's hostname in the login command.

If you're switching accounts, open the sign-in link in a private browser window or select a different account when your identity provider prompts you. Otherwise, the browser may reuse your previous sign-in.

******Terminal

```bash
alma logout
Logged out all users from all proxies.
alma login --proxy=almaforge.example.com:443
...
> Profile URL:        https://almaforge.example.com:443
  Logged in as:       alice@example.com
  Cluster:            almaforge.example.com
  Roles:              postgresql-access
  ...
alma status
> Profile URL:        https://almaforge.example.com:443
  Logged in as:       alice@example.com
  Cluster:            almaforge.example.com
  Roles:              postgresql-access
  ...
```

Check that `Roles` includes `postgresql-access`. If it is missing, check your SSO group membership and the mapping from Step 3 before continuing.

Connect to the sample database with [`alma exec`](https://almaforge.com/reference/cli.md#alma-exec) and `psql` as shown below. For DataGrip, DBeaver, or pgAdmin, follow [GUI clients and scripts](#gui-clients-and-scripts) to open a local connection.

******Terminal

```bash
alma exec db/postgres --db-name=demo
...
demo=> SELECT current_user, current_database();
   current_user    | current_database
-------------------+------------------
 alice@example.com | demo
(1 row)

demo=> SELECT count(*) FROM demo;
 count
-------
     3
(1 row)
```

The first query must show your full AlmaForge login and database `demo`. The second must return `3`. These results confirm that account creation, certificate authentication, and access to the sample data work. Type `\q` to exit.

## Optional audit log verification[​](#optional-audit-log-verification "Direct link to Optional audit log verification")

In AlmaForge, the SQL audit log records the engineer's SSO identity even when several engineers use the same PostgreSQL role. Run the audit command with an `admin` or `auditor` account. If you're signed in as the test user, switch accounts using the browser sign-in guidance in [Step 4](#step-4-connect).

******Terminal

```bash
alma logout
Logged out all users from all proxies.
alma login --proxy=almaforge.example.com:443
...
alma status
...
  Roles:              admin
  ...
alma audit --last=1h --type=DatabaseSessionQuery --limit=1 -o json
```

[`audit-event.json`](https://almaforge.com/examples/databases/postgresql/audit-event.json):

examples/databases/postgresql/audit-event.json

```json
[

  {

    "apiVersion": "almaforge.com/v1",

    "kind": "AuditEvent",

    "spec": {

      "id": "da455e0f-c27d-459f-a218-4e83b3db9426",

      "type": "DatabaseSessionQuery",

      "code": "TDB02I",

      "verb": "execute",

      "outcome": "success",

      "index": 2,

      "timestamp": "2026-05-18T22:24:11.503000Z",

      "clusterName": "almaforge.example.com",

      "actor": {

        "name": "alice@example.com",

        "type": "user"

      },

      "session": {

        "id": "1cdcd17c-9d9f-4806-9a3c-dffe3f873b0c"

      },

      "status": {

        "success": true

      },

      "database": {

        "service": "postgres",

        "protocol": "postgres",

        "uri": "127.0.0.1:5432",

        "name": "demo",

        "user": "alice@example.com",

        "roles": ["alma-demo-reader"],

        "type": "self-hosted",

        "origin": "config-file"

      },

      "databaseSessionQuery": {

        "dbQuery": "SELECT count(*) FROM demo;"

      }

    }

  }

]
```

In this event, `spec.actor.name` identifies the engineer and `spec.databaseSessionQuery.dbQuery` contains the SQL. The database login is `alice@example.com` in `spec.database.user`, and the role granted for the session is `alma-demo-reader` in `spec.database.roles`. PostgreSQL's `log_line_prefix` setting (`%u`) identifies the database session user in local logs, including [pgAudit output](https://github.com/pgaudit/pgaudit/blob/main/README.md).

`DatabaseSessionQuery` carries the simple text statements that `psql` sends in this example. Clients that use prepared statements, such as DBeaver, DataGrip, or pgAdmin, record prepared statements across `PostgresParse` (query text), `PostgresBind` (parameters), and `PostgresExecute` instead. A `DatabaseSessionQuery` filter does not return those events. Repeat `--type` for each event type you want, or omit the flag to list every event in the window:

******Terminal

```bash
alma audit --last=1h \
  --type=DatabaseSessionQuery --type=PostgresParse \
  --type=PostgresBind --type=PostgresExecute
```

See [Audit events](https://almaforge.com/reference/audit.md#database-access) for the full event list and the [storage guide](https://almaforge.com/storage.md#audit-events) to export `AuditEvent` streams to S3 or a SIEM.

## Identity provider group mapping[​](#identity-provider-group-mapping "Direct link to Identity provider group mapping")

Each [`OIDCConnector`](https://almaforge.com/reference/configuration.md#oidcconnector) resource maps identity provider groups to AlmaForge roles under `spec.claimsToRoles`. Group delivery differs across providers:

| Identity provider                                                       | Value to match in `spec.claimsToRoles`    | Where the value comes from                                                                                                                                                                                       |
| ----------------------------------------------------------------------- | ----------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Okta](https://almaforge.com/sso/okta.md)                               | Exact group name                          | The `groups` claim, preferably from a custom authorization server.                                                                                                                                               |
| [Microsoft Entra ID (Azure AD)](https://almaforge.com/sso/microsoft.md) | Security group's Object ID                | The app registration's `groups` claim. For users with more than 200 groups, [configure the app to emit assigned groups](https://almaforge.com/sso/microsoft.md#admin-group-missing-for-a-user-with-many-groups). |
| [Google Workspace](https://almaforge.com/sso/google.md)                 | Group's primary email address             | The Cloud Identity Groups API, accessed through a service account with [domain-wide delegation](https://almaforge.com/sso/google.md#step-5-grant-domain-wide-delegation).                                        |
| [Generic OIDC](https://almaforge.com/sso/oidc.md)                       | Exact value in the configured group claim | The identity provider's ID token. Applies to Keycloak, Authentik, Auth0, Zitadel, and Dex.                                                                                                                       |

Google Workspace ID tokens omit group memberships. AlmaForge looks up Google Groups through the Cloud Identity Groups API.

## Advanced configuration[​](#advanced-configuration "Direct link to Advanced configuration")

### Automatic user provisioning[​](#automatic-user-provisioning "Direct link to Automatic user provisioning")

The example enables `createDbUserMode: keep`. The agent connects as `alma-admin`, creates an account named after the user's full AlmaForge login, and grants `alma-demo-reader` for the session. It does not provision an arbitrary name supplied through `--user`. The account remains after disconnect. Use `bestEffortDrop` to request its removal instead.

If you prefer not to create per-engineer roles in `pg_roles`, you can omit automatic user provisioning and map an AlmaForge role to a pre-existing shared PostgreSQL role (such as a read-only role). In both models, `spec.actor.name` in the AlmaForge audit log records which SSO user ran each query. See [automatic user provisioning](https://almaforge.com/rbac.md#database-access-with-auto-provisioned-users) for role settings and cleanup behavior. Removing an engineer from the identity provider blocks their next AlmaForge login. A [cluster lock](https://almaforge.com/reference/cli.md#alma-create-lock) can terminate active sessions.

### Standing read-only access with just-in-time read-write elevation[​](#standing-read-only-access-with-just-in-time-read-write-elevation "Direct link to Standing read-only access with just-in-time read-write elevation")

PostgreSQL's built-in `CREATE ROLE ... VALID UNTIL` clause sets an expiration timestamp only for password authentication. PostgreSQL does not enforce `VALID UNTIL` on certificate-authenticated logins and does not close sessions that are already open.

To enforce time-bounded elevation, keep `postgresql-access` mapped to your SSO group for routine `SELECT` queries through `alma-demo-reader`. Put write or schema administration privileges in a separate AlmaForge role, such as `postgresql-rw`, with a short `maxSessionTTL`. Engineers can request that role when they need elevated access.

Allow the baseline role to request `postgresql-rw`, then designate a reviewer role as shown in [Just-in-Time Access](https://almaforge.com/just-in-time-access.md#configuration) or enable [PagerDuty on-call auto-approval](https://almaforge.com/just-in-time-access.md#auto-approval). When an engineer needs write access, they submit an access request:

******Terminal

```bash
alma request create \
  --roles=postgresql-rw \
  --reason="incident-42: backfill missing order rows"
```

A reviewer [inspects and approves the request](https://almaforge.com/just-in-time-access.md#reviewing-access) from the CLI or Web UI:

******Terminal

```bash
alma request ls --reviewable
alma request review <request-id> --approve --reason="approved for incident-42"
```

After approval, close any open PostgreSQL sessions for that user so the agent can update their granted database roles, then assume the request and reconnect until the elevated certificate's TTL expires. You can also pass `--wait` to `request create` to wait for a review:

******Terminal

```bash
alma request assume <request-id>
alma exec db/postgres --db-name=demo
```

Set `disconnectExpiredCert: true` on the elevated role to terminate open database sessions automatically when the window closes.

### Dynamic labels[​](#dynamic-labels "Direct link to Dynamic labels")

Use `spec.dynamicLabels` for values that a command on the agent refreshes, such as the PostgreSQL version. The command must be available on that host.

[`postgres-dynamic-labels.yaml`](https://almaforge.com/examples/databases/postgresql/kinds/postgres-dynamic-labels.yaml):

examples/databases/postgresql/kinds/postgres-dynamic-labels.yaml

```yaml
# Self-hosted PostgreSQL with dynamic labels. Each entry under

# `spec.dynamicLabels` runs a shell command on the agent at the

# configured period and stores stdout as the label value. Use this

# for values that change between deployments — engine version,

# replica role, pgBouncer pool name — instead of hard-coding them

# under `metadata.labels`.

apiVersion: almaforge.com/v1

kind: DatabaseTarget

metadata:

  name: orders-postgres

  labels:

    env: prod

    team: payments

spec:

  protocol: postgres

  uri: orders-prod.internal:5432

  dynamicLabels:

    engine_version:

      period: 5m # Refresh every five minutes.

      command: # Argv form; the agent runs the binary directly, no shell parsing.

        - /bin/sh

        - -c

        - psql --version | awk '{print $3}'
```

### Multiple PostgreSQL instances per agent[​](#multiple-postgresql-instances-per-agent "Direct link to Multiple PostgreSQL instances per agent")

Add a target file per database under `/etc/almaforge/almad.d/` and restart the agent. For centrally applied targets, configure [`ALMA_MATCH_LABELS`](https://almaforge.com/reference/environment.md#service-matchers) to match their labels. The agent must reach each target's address, and the server certificates must cover those addresses.

### Identity files for non-interactive `psql`[​](#identity-files-for-non-interactive-psql "Direct link to identity-files-for-non-interactive-psql")

For unattended jobs, use [workload identity](https://almaforge.com/workload-identity.md#cli-workload-sessions) and grant only the database names and roles the job needs.

### GUI clients and scripts[​](#gui-clients-and-scripts "Direct link to GUI clients and scripts")

For a GUI client such as DataGrip, DBeaver, or pgAdmin, or for local scripts, leave [`alma port-forward`](https://almaforge.com/reference/cli.md#alma-port-forward) running:

******Terminal

```bash
alma port-forward db/postgres --db-name=demo
Forwarding from 127.0.0.1:5432 -> 5432
...
```

Use the address and port it prints, your full AlmaForge login as the user, and `demo` as the database. Use plain TCP (`sslmode=disable` if the client defaults to TLS) to the local listener on `127.0.0.1`. Leave the password field blank and remove matching `~/.pgpass` or `PGPASSWORD` entries so the client does not send stale credentials. AlmaForge authenticates the session over mTLS through the encrypted tunnel.

## Architecture[​](#architecture "Direct link to Architecture")

The AlmaForge database agent reaches PostgreSQL on localhost or a private interface and opens an outbound TLS tunnel to your self-hosted proxy on port `443`. Engineers sign in through your OIDC provider and connect through AlmaForge. The proxy and SQL traffic stay on your infrastructure.

PostgreSQL verifies the agent's short-lived client certificate against your cluster's database CA. The agent verifies the PostgreSQL server certificate against `spec.tls.caCert` and sends [SQL audit events](#optional-audit-log-verification) to the cluster. See the [database architecture](https://almaforge.com/access/databases.md#architecture) for the Auth, Proxy, and Database Service roles.

![PostgreSQL database access topology](data:image/svg+xml;base64,PCEtLQpDb3B5cmlnaHQgMjAyNiBBbG1hRm9yZ2UgUHJvamVjdC4KQWxsIHJpZ2h0cyByZXNlcnZlZC4KU1BEWC1MaWNlbnNlLUlkZW50aWZpZXI6IExpY2Vuc2VSZWYtQWxtYUZvcmdlCi0tPgo8c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDY0MCAzMDAiIGZvbnQtZmFtaWx5PSJ1aS1zYW5zLXNlcmlmLCBzeXN0ZW0tdWksIHNhbnMtc2VyaWYiIGZvbnQtc2l6ZT0iMTMiIGZpbGw9IiMxZjI5MzciPgogIDxkZWZzPgogICAgPG1hcmtlciBpZD0iYXJyb3ciIHZpZXdCb3g9IjAgMCAxMCAxMCIgcmVmWD0iOSIgcmVmWT0iNSIgbWFya2VyV2lkdGg9IjgiIG1hcmtlckhlaWdodD0iOCIgb3JpZW50PSJhdXRvLXN0YXJ0LXJldmVyc2UiPgogICAgICA8cGF0aCBkPSJNMCwwIEwxMCw1IEwwLDEwIHoiIGZpbGw9IiMxZjI5MzciLz4KICAgIDwvbWFya2VyPgogIDwvZGVmcz4KCiAgPGcgc3Ryb2tlPSIjMWYyOTM3IiBzdHJva2Utd2lkdGg9IjEuNSIgZmlsbD0ibm9uZSI+CiAgICA8Y2lyY2x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yMDAiCiAgICAgICAgc3Ryb2tlPSIjMWYyOTM3IiBzdHJva2Utd2lkdGg9IjEuNSIgbWFya2VyLWVuZD0idXJsKCNhcnJvdykiLz4KICA8cmVjdCB4PSI0ODMiIHk9IjE2NSIgd2lkdGg9IjY2IiBoZWlnaHQ9IjE0IiBmaWxsPSIjZmZmZmZmIi8+CiAgPHRleHQgeD0iNDg2IiB5PSIxNzYiIGZpbGw9IiMzNzQxNTEiIGZvbnQtc2l6ZT0iMTEiPlRMUyA6NTQzMjwvdGV4dD4KCiAgPHRleHQgeD0iMzIwIiB5PSIyOTQiIHRleHQtYW5jaG9yPSJtaWRkbGUiIGZpbGw9IiM2YjcyODAiIGZvbnQtc2l6ZT0iMTEiPgogICAgTm8gcHVibGljIGRhdGFiYXNlIHBvcnRzOiBhbG1hZCAtLWRhdGFiYXNlLXNlcnZpY2UgY29ubmVjdHMgdG8gdGhlIFByb3h5IHRocm91Z2ggdGhlIHJldmVyc2UgdHVubmVsLgogIDwvdGV4dD4KPC9zdmc+Cg==)

## Troubleshooting[​](#troubleshooting "Direct link to Troubleshooting")

### Database is missing or has no host[​](#database-is-missing-or-has-no-host "Direct link to Database is missing or has no host")

On the database server, check that `/etc/almaforge/almad.d/postgres.yaml` exists and `ALMA_DATABASE_SERVICE=true` is set in `/etc/almaforge/almad.env`. The agent must reach your cluster on [port 443](https://almaforge.com/networking.md#multiplex-floor). If the agent logs `connection refused` when dialing PostgreSQL, verify that PostgreSQL is active and listening on `127.0.0.1:5432` (or the target URI in `postgres.yaml`). Inspect the service logs:

******Terminal

```bash
sudo journalctl -u almad -n 50 --no-pager
...
<date> <time> <database-host> almad[<pid>]: <log-message>
...
```

Restart `almad` after correcting its configuration, then repeat `alma get db` on your computer.

### Access is denied[​](#access-is-denied "Direct link to Access is denied")

Run `alma status` and check for `postgresql-access`:

* **Role missing after login**: Verify the SSO group mapping from [Step 3](#step-3-grant-access). Confirm that Okta uses the exact group name, Microsoft Entra ID uses the group's Object ID UUID rather than its display name, and Google Workspace uses the group's primary email address with Cloud Identity API delegation configured. Then run `alma logout` and `alma login`.
* **Database or table denied**: Check that the role's database labels match `postgres.yaml`, `--db-name` matches an allowed database name, and the PostgreSQL role (`alma-demo-reader`) has `USAGE` on the schema and `SELECT` on the target tables.
* **Session disconnects when certificate expires**: Your role or just-in-time request reached `maxSessionTTL`, and the role sets [`disconnectExpiredCert: true`](https://almaforge.com/rbac.md#specoptions). Run `alma login` or submit a new access request to obtain a fresh certificate.
* **Denied with lock in force**: An administrator placed a cluster lock on your user, role, or target. Ask a cluster administrator to review active locks.
* **Agent join token rejected**: Create a fresh database token with `alma create token --services=database` (valid for 30 minutes) and update `ALMA_CLIENT_ID` and `ALMA_CLIENT_SECRET` in `/etc/almaforge/almad.env`.

### Account creation fails[​](#account-creation-fails "Direct link to Account creation fails")

Check that the target file has `adminUser.name: alma-admin` and `adminUser.defaultDatabase: demo`, and that your role has `createDbUserMode: keep`. The `alma-admin` account must have `LOGIN`, `CREATEROLE`, permission to install its procedures, and `WITH ADMIN OPTION` permission to grant `alma-auto-user` and `alma-demo-reader` (required on PostgreSQL 16 and later). Connect with your own AlmaForge login, which the CLI selects automatically. See [automatic user provisioning](#automatic-user-provisioning).

### PostgreSQL rejects the certificate login[​](#postgresql-rejects-the-certificate-login "Direct link to PostgreSQL rejects the certificate login")

For `no pg_hba.conf entry`, `Ident authentication failed`, or a password prompt from PostgreSQL, check `/var/lib/pgsql/data/pg_hba.conf`. The setup uses `hostssl ... cert` for both localhost addresses (`127.0.0.1/32` and `::1/128`). PostgreSQL uses the first matching rule, so an earlier `ident`, `scram-sha-256`, or `md5` rule on `localhost` changes how the connection authenticates. Keep the `local all all peer` rule for maintenance over the Unix socket, and restart PostgreSQL after editing `pg_hba.conf`.

### Certificate validation fails[​](#certificate-validation-fails "Direct link to Certificate validation fails")

PostgreSQL's `ssl_ca_file` must reference `server.cas`, the public AlmaForge database CA downloaded from the cluster. The agent's `spec.tls.caCert` must contain the PostgreSQL server certificate, and that certificate must be within its validity dates and include the target host or IP in `subjectAltName`. These files establish trust in opposite directions. If you rotate the server certificate, update `/etc/almaforge/almad.d/postgres.yaml` and restart `almad`.

## Self-hosted PostgreSQL access options compared[​](#self-hosted-postgresql-access-options-compared "Direct link to Self-hosted PostgreSQL access options compared")

With AlmaForge, engineers sign in through OIDC and the database agent connects to PostgreSQL over mutual TLS (mTLS) using short-lived client certificates. This can replace shared passwords in `.pgpass` files and `PGPASSWORD` variables.

| Approach                           | How users authenticate                           | How SQL activity identifies users                                         |
| ---------------------------------- | ------------------------------------------------ | ------------------------------------------------------------------------- |
| Shared PostgreSQL login            | Shared database password                         | PostgreSQL logs show the shared database role.                            |
| PostgreSQL LDAP or PAM             | Password checked through LDAP or PAM             | PostgreSQL logs show the database role, which must already exist.         |
| PostgreSQL 18 native OAuth         | OAuth token checked by a server-side validator   | PostgreSQL logs show the database role.                                   |
| Vault dynamic database credentials | Password issued per lease                        | Correlate the Vault lease with PostgreSQL logs.                           |
| AlmaForge                          | OIDC sign-in and short-lived client certificates | The cluster audit event records the SSO user alongside the database role. |

For temporary write access, use an [approval-gated access request](#standing-read-only-access-with-just-in-time-read-write-elevation). AlmaForge can close open PostgreSQL sessions when the elevated certificate expires. The proxy and SQL traffic stay on your infrastructure.

## Frequently asked questions[​](#frequently-asked-questions "Direct link to Frequently asked questions")

### Does PostgreSQL support Okta, Entra ID, Google Workspace, or Keycloak SSO natively?[​](#does-postgresql-support-okta-entra-id-google-workspace-or-keycloak-sso-natively "Direct link to Does PostgreSQL support Okta, Entra ID, Google Workspace, or Keycloak SSO natively?")

PostgreSQL 18 [introduced native OAuth 2.0 authentication compatible with OIDC providers](https://www.postgresql.org/docs/18/auth-oauth.html). To use it, configure a validator for your provider's tokens, map identities to PostgreSQL roles, and use a client that supports OAuth. AlmaForge handles SSO for your existing PostgreSQL clients and adds [automatic user provisioning](#automatic-user-provisioning), [just-in-time approvals](#standing-read-only-access-with-just-in-time-read-write-elevation), and [per-user SQL audit logs](#optional-audit-log-verification) across [supported databases](https://almaforge.com/access/databases.md#supported-databases).

### Can you use the same corporate SSO for self-hosted PostgreSQL, AWS RDS, Google Cloud SQL, and Azure Database for PostgreSQL?[​](#can-you-use-the-same-corporate-sso-for-self-hosted-postgresql-aws-rds-google-cloud-sql-and-azure-database-for-postgresql "Direct link to Can you use the same corporate SSO for self-hosted PostgreSQL, AWS RDS, Google Cloud SQL, and Azure Database for PostgreSQL?")

Yes. Engineers can sign in to AlmaForge with the same [corporate SSO](https://almaforge.com/sso.md) for self-hosted PostgreSQL and [supported managed databases](https://almaforge.com/access/databases.md#managed-and-cloud-native), including Amazon RDS, Google Cloud SQL, and Azure Database for PostgreSQL. Configure the database connection using each service's authentication settings.

### How do you replace shared PostgreSQL passwords and `.pgpass` files with corporate SSO?[​](#how-do-you-replace-shared-postgresql-passwords-and-pgpass-files-with-corporate-sso "Direct link to how-do-you-replace-shared-postgresql-passwords-and-pgpass-files-with-corporate-sso")

Use AlmaForge to sign engineers in through your identity provider and connect them to PostgreSQL with short-lived client certificates. In [Step 2](#step-2-configure-the-postgresql-server), configure `hostssl ... cert` in `pg_hba.conf` for the agent connection. After [verifying access](#step-4-connect), remove the old `.pgpass` entries and `PGPASSWORD` settings for that connection.

### How do Okta, Microsoft Entra ID (Azure AD), and Google Workspace groups map to PostgreSQL roles?[​](#how-do-okta-microsoft-entra-id-azure-ad-and-google-workspace-groups-map-to-postgresql-roles "Direct link to How do Okta, Microsoft Entra ID (Azure AD), and Google Workspace groups map to PostgreSQL roles?")

In AlmaForge, the OIDC connector tells the cluster which access role to grant when an engineer signs in. In `spec.claimsToRoles`, use the Okta group name, the Entra ID security group's Object ID, or the Google group's primary email address. See [Identity provider group mapping](#identity-provider-group-mapping) for how each provider supplies that value.

### Why use a self-hosted database access proxy instead of PostgreSQL LDAP authentication or HashiCorp Vault dynamic credentials?[​](#why-use-a-self-hosted-database-access-proxy-instead-of-postgresql-ldap-authentication-or-hashicorp-vault-dynamic-credentials "Direct link to Why use a self-hosted database access proxy instead of PostgreSQL LDAP authentication or HashiCorp Vault dynamic credentials?")

Use AlmaForge when engineers need corporate SSO, approval before gaining write access, and an audit log that names the person who ran a query. LDAP validates a password, and Vault issues a temporary database password. With AlmaForge, the agent connects using a short-lived certificate and records the engineer's SSO identity. See [PostgreSQL access options compared](#self-hosted-postgresql-access-options-compared).

### How do developers connect to private PostgreSQL databases without a VPN or SSH bastion?[​](#how-do-developers-connect-to-private-postgresql-databases-without-a-vpn-or-ssh-bastion "Direct link to How do developers connect to private PostgreSQL databases without a VPN or SSH bastion?")

Engineers sign in to your self-hosted AlmaForge proxy, then connect with `psql` or a GUI client. The database agent opens an outbound TLS tunnel to the proxy on port `443`, so PostgreSQL can stay on a private network without a public database port, VPN, or SSH bastion. See [Architecture](#architecture).

### How do you grant just-in-time read-write access to production PostgreSQL?[​](#how-do-you-grant-just-in-time-read-write-access-to-production-postgresql "Direct link to How do you grant just-in-time read-write access to production PostgreSQL?")

Use AlmaForge to give engineers read-only PostgreSQL access by default. When they need to write, they request a separate role. After approval, they activate it and reconnect with a short-lived certificate. Follow [Set up just-in-time read-write access](#standing-read-only-access-with-just-in-time-read-write-elevation) and see `maxSessionTTL` and `disconnectExpiredCert` in the [Role reference](https://almaforge.com/rbac.md#specoptions) for certificate expiry and session cutoff.

### How do you audit PostgreSQL queries by SSO identity when engineers share a database role?[​](#how-do-you-audit-postgresql-queries-by-sso-identity-when-engineers-share-a-database-role "Direct link to How do you audit PostgreSQL queries by SSO identity when engineers share a database role?")

In the AlmaForge SQL audit log, `spec.actor.name` identifies the engineer even when several people use the same PostgreSQL login. Read `spec.database.user` for the database login and `spec.database.roles` for roles granted when the agent provisions a user. See [Verify the SQL audit log](#optional-audit-log-verification) for a sample event.

### How do you automate PostgreSQL user provisioning and offboarding through corporate SSO?[​](#how-do-you-automate-postgresql-user-provisioning-and-offboarding-through-corporate-sso "Direct link to How do you automate PostgreSQL user provisioning and offboarding through corporate SSO?")

Enable [automatic user provisioning](#automatic-user-provisioning) so AlmaForge creates a PostgreSQL account from the engineer's SSO login on first connection and grants the database roles you configured. Remove the engineer from your identity provider to block their next AlmaForge sign-in. Apply a [cluster lock](https://almaforge.com/reference/cli.md#alma-create-lock) to end active sessions immediately.

### How do you connect DataGrip, DBeaver, or pgAdmin to PostgreSQL using corporate SSO?[​](#how-do-you-connect-datagrip-dbeaver-or-pgadmin-to-postgresql-using-corporate-sso "Direct link to How do you connect DataGrip, DBeaver, or pgAdmin to PostgreSQL using corporate SSO?")

Sign in to AlmaForge and run `alma port-forward db/postgres --db-name=demo`. Point your GUI client at the local address and port the command prints. Use your full AlmaForge login as the database username and leave the password blank. Follow [GUI clients and scripts](#gui-clients-and-scripts) for the connection settings.

### How do you enable corporate OIDC SSO for PostgreSQL running in Docker or Kubernetes?[​](#how-do-you-enable-corporate-oidc-sso-for-postgresql-running-in-docker-or-kubernetes "Direct link to How do you enable corporate OIDC SSO for PostgreSQL running in Docker or Kubernetes?")

Run the AlmaForge database agent where it can reach PostgreSQL. For Docker, follow the [container environment-file example](https://almaforge.com/reference/environment.md#use-docker---env-file) and replace `ALMA_SSH_SERVICE=true` with `ALMA_DATABASE_SERVICE=true`. For Kubernetes, use the [agent Helm chart](https://almaforge.com/reference/helm.md#agent-chart). Follow [Step 2](#step-2-configure-the-postgresql-server) for PostgreSQL TLS settings and use a server certificate that covers the address the agent uses.

## References[​](#references "Direct link to References")

* [Quick Start](https://almaforge.com/quickstart.md): run a local `alma demo` evaluation in ten minutes.
* [Single sign-on](https://almaforge.com/sso.md): configure [Okta](https://almaforge.com/sso/okta.md), [Microsoft Entra ID](https://almaforge.com/sso/microsoft.md), [Google Workspace](https://almaforge.com/sso/google.md), or [OIDC](https://almaforge.com/sso/oidc.md) (including Keycloak, Authentik, Auth0, Zitadel, and Dex).
* [Database access overview](https://almaforge.com/access/databases.md): architecture and supported databases, including [ClickHouse](https://almaforge.com/access/databases/clickhouse.md), [CockroachDB](https://almaforge.com/access/databases/cockroachdb.md), [MongoDB](https://almaforge.com/access/databases/mongodb.md), [MySQL](https://almaforge.com/access/databases/mysql.md), and [Valkey](https://almaforge.com/access/databases/valkey.md), plus MariaDB, Redis, Cassandra, ScyllaDB, TiDB, and Elasticsearch.
* [Server access (SSH)](https://almaforge.com/access/servers.md) and [Kubernetes access](https://almaforge.com/access/kubernetes.md): apply the same OIDC roles to Linux hosts and Kubernetes clusters.
* [Just-in-time access](https://almaforge.com/just-in-time-access.md) and [RBAC reference](https://almaforge.com/rbac.md): standing read-only roles and approval-gated read-write elevation.
* [Audit events](https://almaforge.com/reference/audit.md) and [Declarative configuration](https://almaforge.com/reference/configuration.md): `AuditEvent` JSON records and the `DatabaseTarget` schema.
