Skip to main content

PG environment authorization model

Access permissions in PG mode depend on the entry point and the credentials used by the request. Running code in a Cloud Function does not automatically grant database access.

For PostgreSQL REST API requests, OPA first decides whether to allow the request. PostgreSQL then enforces object privileges (GRANT) and row-level security policies (RLS). Management APIs use CAM authorization and bypass OPA.

An OPA allow does not grant database privileges. A Cloud Function's CAM runtime role and its PostgreSQL database role are configured separately.

Entry points​

Call typeOPAOther permission checks
Cloud Function calls through JS SDK v3+ or Node SDK v4+EvaluatedDatabase access from function code requires separate database permission checks
Native Mini Program wx.cloud.callFunction calls to PG environmentsEvaluatedSame as above
Cloud Function calls through the HTTP API or HTTP gatewayEvaluatedSame as above
PostgreSQL REST APIEvaluatedPostgreSQL role, GRANT, and RLS
pgdoc Document interfacesEvaluated for HTTP API requests; bypassed by the native Mini Program Document SDKBasic collection permissions
HTTP /v1/rdb/exec-pgsqlEvaluatedAdministrators only; always executes as cloudbase_postgres
Cloud API and Manager SDK management operationsBypassedCAM; SQL execution is also subject to database role privileges
Direct PostgreSQL connections, such as pg.PoolBypassedDatabase account authentication, GRANT, and RLS
Timer triggers, database triggers, and internal platform callsBypassedRequests issued by function code are checked according to their own call type

Manager SDK functions.invokeFunction is a management invocation method and is not restricted by client OPA policies. It uses a different entry point from Node SDK callFunction; the two do not share an invocation permission configuration.

SDK, HTTP API, and direct database requests issued by Cloud Function code use the checks for their respective entry points above. For complete SDK coverage, see OPA SDK scope.

Control plane and data plane​

The control plane covers management operations through Cloud APIs and the Manager SDK. The data plane covers application requests, such as invoking functions and reading or writing database records.

Control plane​

CAM authorizes management API calls. After a successful ExecutePGSql call, SQL executes as the selected database role.

When a management API invokes a function, CAM checks that invocation only. Function code issues new requests when accessing other resources.

Data plane​

The diagram below covers PostgreSQL REST API requests and direct database connections. It does not cover pgdoc Document interfaces, which use basic collection permissions.

Credentials and database roles​

Call type and credentialDatabase roleRLS
REST API with a user access tokenUsually authenticatedEnforces RLS policies for that role
REST API with a Publishable Key for signed-out accessanonEnforces RLS policies for that role
Cloud API ExecutePGSql with Tencent Cloud credentialsThe role specified by Role, or cloudbase_postgres if omittedEnforced according to the role; cloudbase_postgres has BYPASSRLS
HTTP /v1/rdb/exec-pgsql with administrator credentialsAlways cloudbase_postgres; cannot be changed with roleBypasses RLS
Database connection stringThe database account in the connection stringEnforced according to the role; privileged roles can bypass RLS

A Cloud Function runtime role's temporary credentials authorize Tencent Cloud API requests. They do not map automatically to a PostgreSQL role with the same name. When using a user token, API Key, or database password instead, permissions depend on that credential and the API being called.

The two SQL interfaces handle role parameters differently. See Cloud API ExecutePGSql and the HTTP SQL interface.

warning

Do not expose Tencent Cloud keys, administrator API Keys, service_role credentials, or database passwords in client code.

Permission configuration​

ScenarioConfiguration
A function executes SQL through the Cloud APIAttach a policy granting tcb:ExecutePGSql on the target environment to the runtime role; see the example below
A function reads specific tables onlyUse a separate database account with USAGE on the target schema and SELECT on the target tables
Users read their own records through the REST APIGrant SELECT to authenticated and configure an RLS policy that filters on auth.uid()
Clients must not invoke a specific functionUse OPA deny to restrict the HTTP API and gateway entry points; see the policy example. Management APIs use separate CAM authorization
Inspect the current OPA configurationUse the CLI or policy-query API; see Read-only diagnostics

Cloud Function runtime roles and CAM​

The following policy allows ExecutePGSql on the target environment. Replace <region> and <env-id>. The resource format is documented in the CAM CloudBase service support table.

{
"version": "2.0",
"statement": [
{
"effect": "allow",
"action": ["tcb:ExecutePGSql"],
"resource": ["qcs::tcb:<region>:uin/:env/<env-id>"]
}
]
}

To configure the runtime role:

  1. Create a custom policy in CAM with the JSON above.
  2. Create a runtime role for the Cloud Function service (scf.qcloud.com) and attach the policy.
  3. Open the target function's configuration in the Serverless console and click "Edit". Enable "Runtime role", select the role, and save the configuration.

For complete instructions, see Cloud Function roles and policies. If the role already has broad grants such as tcb:*, remove or narrow those policies. Adding a narrower allow does not revoke existing grants.

Ordinary event functions that are not created from container images expose runtime role temporary credentials through these environment variables:

CredentialEnvironment variableManager SDK initialization parameter
SecretIdTENCENTCLOUD_SECRETIDsecretId
SecretKeyTENCENTCLOUD_SECRETKEYsecretKey
SessionTokenTENCENTCLOUD_SESSIONTOKENtoken

Read the current credentials inside main rather than caching them at module scope. When initializing the Manager SDK explicitly, pass all three parameters. See Function environment variables and Manager SDK initialization.

HTTP functions do not receive these authentication environment variables and require explicit authentication configuration. Functions created from container images receive credentials differently; see Cloud Function roles and policies.

warning

ExecutePGSql permits arbitrary SQL, and callers can change or omit Role; selecting a read-only role does not restrict a caller who holds this API permission.

CAM does not inspect table names or operation types within SQL. For table-level read-only access, use the database account approach below instead of granting ExecutePGSql to application code.

Database roles and RLS​

This example assumes a separate database account named app_reader and an existing public.todos table. The account must not own the objects, be a superuser, or have BYPASSRLS. See Create a service account.

grant usage on schema public to app_reader;
grant select on public.todos to app_reader;

These statements add read privileges without revoking existing grants. Also check role inheritance, PUBLIC privileges, existing grants, and object ownership.

If RLS is enabled on the table, configure the required row policies for app_reader. Direct database connections do not automatically carry the end-user JWT, so auth.uid() does not automatically identify the calling user.

Use this account to connect to PostgreSQL from the server, with connection details stored in environment variables. Verify that the account can read the intended records but cannot write to the target table or access tables without grants.

These settings configure PostgreSQL role privileges only; they do not bind the role to a Cloud Function's CAM runtime role. pgdoc collection permissions and PostgreSQL table privileges are configured separately. See pgdoc permission management.

Related content​

External references: