This service provides a unified web interface for secure, controlled access to company databases. It enables employees
to run queries on production databases while enforcing access control (ACL) policies. For example, team leads may
have permissions to execute both SELECT and INSERT queries on certain tables, while other team members are
restricted to read-only (SELECT) access. This approach ensures that database interactions are managed safely and
that each user's access is tailored to their role and responsibilities.
- Run approved SQL against multiple PostgreSQL targets from one web UI.
- Authenticate users via OIDC and enforce ACL rules by user, target, operation, and table/column.
- Store query results (with shareable links and execution metadata) for debugging and auditing.
- TL;DR
- Architecture Overview
- Quickstart with example setup
- Features
- Advanced Configuration
- Performance Optimizations
- Security Considerations
- Edge Cases and Troubleshooting
- Interesting projects
This application acts as a secure gateway to multiple PostgreSQL instances, allowing authenticated users to run approved queries through a unified web interface, with fine-grained ACLs controlling access.
┌───────────────────────────┐
│ PROD ┌─────────────┐ │
│ ┌───┤ Postgres1 │ │
┌────────┐ ┌────────┐ │ └─────────────┘ │
│ USER │────│ DBGW │───┼ │
└────────┘ └────────┘ │ ┌─────────────┐ │
│ └───┤ Postgres2 │ │
│ └─────────────┘ │
└───────────────────────────┘
-
Local PostgreSQL Database:
- Stores query results, user profiles, and ACLs.
- Acts as a cache for query results, allowing unique links for debugging without re-execution.
-
Remote PostgreSQL Instances:
- Host production data and are accessed only through the app.
- Queries are run only if authorized by ACLs, limiting access to specific users, tables, and query types.
-
OIDC Authentication:
- Users authenticate via an external OIDC provider.
- User roles are mapped to ACLs, defining what queries each user can run.
-
Access Control Lists (ACLs):
- Define user permissions at the instance, table, and query type levels.
- Stored in the local database, restricting queries based on user identity.
-
Web Interface:
- Provides login, query submission, and result viewing.
- Shows error feedback for unauthorized or restricted queries.
- Authentication: Users log in via OIDC, and their identity maps to ACL permissions.
- Query Submission: Authorized queries are checked against ACLs, then run on remote instances.
- Result Caching: Results are stored locally with unique links for easy access and debugging.
This architecture ensures secure, controlled access to production data, balancing usability with data protection.
Run commands to get a local dbgw instance with 3 PostgreSQL instances.
git clone https://github.com/kazhuravlev/database-gateway.git
cd database-gateway/example
docker compose up --pull always --force-recreate -d
open 'http://127.0.0.1:8080'
# Authentik and test users are bootstrapped automatically.The example setup uses self-hosted Authentik as the OIDC provider. ACLs are stored in config.json.
Bootstrap details for local Authentik:
- OIDC app is created from
example/authentik-blueprint.yaml. - Static users are created with password
password:admin@example.comuser1@example.com
admin@example.combelongs todbgw-adminsanddbgw-users;user1@example.combelongs todbgw-users.- Authentik admin user:
akadmin@example.com/password
Choose local-1, run this query select id, name from clients, then click Run. 
Admins can inspect recent stored requests and open a detailed result view with execution metadata and exported formats.
- Integrates with OpenID Connect for user authentication
- Enforces access filtering through ACLs
- Fine-grained table-level permissions
- Column-level access control
- SQL parsing to enforce query type restrictions (SELECT, INSERT, etc.)
- Query validation and sanitization
- Session management with token expiration
- Secure cookie handling
- Supports any PostgreSQL wire-protocol database
- Interactive web UI with keyboard shortcuts (Shift+Enter to run queries)
- Provides query result output in HTML format
- Provides query result output in JSON format
- Query bookmarks (save, list, run, delete)
- Recent queries feed on the main page (last 50 per user) with quick result access
- Unique links for query results (useful for debugging)
LRPC endpoint is exposed on the same port as the web facade:
GET /api/v1/token(returns current session access token for frontend app)POST /api/v1/:methodGET /api/v1/schemaGET /api/v1/query-results/export/:token
Available methods:
targets.list.v1- list user-available targetstargets.get.v1- get a single target bytarget_idbookmarks.list.v1- list all bookmarks, or filter by optionaltarget_idbookmarks.add.v1- save a bookmark fortarget_id,title, andquerybookmarks.delete.v1- delete a bookmark byidqueries.list.v1- list recent queries, with optionallimitquery.run.v1- run query for a target and return table dataquery-results.get.v1- get stored query result byquery_result_id; users can read their own results and admins can read any user's resultquery-results.export-link.v1- issue a short-lived export link forjsonorcsv
Download endpoints:
/api/v1/query-results/export/:token- download an exported file using a short-lived signed token
All API requests require an OIDC access token in the header:
Authorization: Bearer <access_token>params are method-specific. User identity and role are resolved from the verified token claims.
- Includes query execution stats in results (full round trip, parsing time, network round trip)
- Connection pooling for performance optimization
The service uses OIDC authentication:
{
"users": {
"client_id": "db-gateway",
"client_secret": "db-gateway-secret",
"issuer_url": "http://localhost:9000/application/o/db-gateway/",
"redirect_url": "http://localhost:8080/auth/callback",
"access_token_audience": "db-gateway",
"scopes": ["groups", "email", "profile"],
"role_claim": "groups",
"role_mapping": {
"dbgw-admins": "admin",
"dbgw-users": "user"
}
}
}access_token_audience is optional. If omitted, client_id is used for access-token audience validation.
Access control lists define user permissions with fine-grained control:
{
"acls": [
{
"user": "role:admin",
"op": "*",
"target": "*",
"tbl": "*",
"allow": true
},
{
"user": "role:user",
"op": "select",
"target": "pg-5433",
"tbl": "*",
"allow": true
},
{
"user": "user:max@example.com",
"op": "select",
"target": "pg-5434",
"tbl": "sales",
"allow": true
}
]
}Wildcards (*) allow all operations, targets, or tables. Specific permissions override broader ones.
Configure performance settings for each database connection:
{
"connection": {
"host": "postgres1",
"port": 5432,
"user": "pg01",
"password": "pg01",
"db": "pg01",
"use_ssl": false,
"max_pool_size": 4
}
}For a complete working config, see example/config.json.
- Connection Pooling: Configurable connection pool sizes for each database target
- Query Result Caching: Results are stored in the local database for later reference
- Efficient Query Execution: Parsed and validated for optimal performance
- SQL Injection Protection: All queries are parsed and validated before execution
- No Direct Database Access: Remote databases are only accessible through the gateway
- Column-Level Restrictions: ACLs can limit which fields users can query
- Query Type Restrictions: Limit users to specific operations (SELECT, INSERT, etc.)
- Session Security: Secure cookie handling with configurable expiration
- Error Handling: Error messages are sanitized to prevent information leakage
- Multiple Schema Support: Tables can be specified with schema names (
schema.table) - Complex Query Handling: Some complex queries might be rejected by the parser
- Connection Failures: The service gracefully handles database connection failures
- Missing Tables/Fields: Queries referencing unknown tables or fields are rejected
- ACL Conflicts: When multiple ACL rules apply, the most specific rule takes precedence
- https://github.com/antlr/grammars-v4/tree/master/sql/postgresql/Go
- https://github.com/auxten/postgresql-parser
- https://github.com/blastrain/vitess-sqlparser
- https://github.com/cockroachdb/cockroach/pkg/sql/parser
- https://github.com/pganalyze/pg_query_go/
- https://github.com/pingcap/tidb/tree/master/pkg/parser
- https://github.com/topics/sql-parser?l=go
- https://github.com/vitessio/vitess
- https://github.com/xwb1989/sqlparser


