Skip to main content

Writing OPA policies

OPA decides whether to allow HTTP API and HTTP gateway requests. Policies are saved per environment and written in Rego v1.

Scope​

OPA evaluates HTTP API and HTTP gateway requests, including SDK calls made through those entry points. A request with input.cloudbase.resource_type set to functions invokes a Cloud Function.

Management APIs, timer triggers, database triggers, and internal platform calls bypass OPA. HTTP API requests subsequently issued by function code are evaluated separately. For SDK coverage, see OPA SDK scope.

An input.subject.auth_type of administrator means the request holds administrator credentials. It does not prove that the code runs on a server.

Relation to database authorization​

After OPA allows a database request, PostgreSQL still enforces the database role's GRANT privileges and RLS policies. OPA policies do not replace table privileges or row policies. See Credentials and database roles.

Configure a policy​

Configure policies under "Authorization policies" in the console using form mode or syntax mode. Saved policies take effect immediately for HTTP API and HTTP gateway requests in the current environment.

In syntax mode, the package name must be authz.user. If a user policy already exists, merge the rules below into that package without replacing other rules. For complete syntax and platform defaults, see OPA authorization policies.

OPA Demo: Restrict function calls​

Functions for batch jobs or data migrations can be restricted to management API invocations. Use OPA to deny HTTP API and gateway requests without affecting management API calls authorized by CAM.

The following example restricts HTTP API calls to a function named privateProbe, including callFunction requests through that entry point. Replace privateProbe with the actual function name. The rules match the function path and its subpaths for every identity, including administrator.

package authz.user

private_api_path if {
input.request.path == "/v1/functions/privateProbe"
}

private_api_path if {
startswith(input.request.path, "/v1/functions/privateProbe/")
}

deny contains "function is not available through the HTTP API" if {
input.cloudbase.entrypoint_type == "tcbopenapi"
input.cloudbase.resource_type == "functions"
private_api_path
}

If the function is also bound to an HTTP gateway, restrict its gateway routes as well. Gateway requests have an entrypoint_type of tcbgateway, and path is the actual request path rather than the HTTP API function path.

For a gateway route of /privateProbe, add the following rules to the same authz.user package:

private_gateway_path if {
input.request.path == "/privateProbe"
}

private_gateway_path if {
startswith(input.request.path, "/privateProbe/")
}

deny contains "function is not available through the gateway" if {
input.cloudbase.entrypoint_type == "tcbgateway"
private_gateway_path
}

The gateway uses prefix route matching, so the rules restrict both /privateProbe and subpaths such as /privateProbe/xxx. Update both paths when replacing the route. If the function is exposed through multiple domains or routes, cover every route that can reach it.

input.request.path retains URL encoding. This example uses string matching and does not define the gateway's path normalization behavior. Include the path forms accepted by your application when validating the policy.

Validate the policy​

User deny takes precedence over user allow and platform default allow rules. default allow := false does not reject requests allowed by the platform default; use explicit deny rules to restrict access.

Before applying the policy in production, save it in a test environment and check the following requests:

RequestExpected result
HTTP API call to privateProbe, including its subpathsDenied
HTTP API call to privateProbe with administrator credentialsDenied
Gateway request to /privateProbe or its subpathsDenied
Request through another gateway route bound to the same functionDenied; requires rules for those routes
Call to an unrestricted application functionExisting policy behavior is preserved
Management API call to privateProbeUnaffected by these OPA rules; still requires CAM authorization

PG mode does not support function-level security rules, so invoke: false has no effect. If a new function must not be briefly accessible to clients after deployment, configure the OPA restrictions before deploying it.

Request fields​

OPA input contains three objects: subject, request, and cloudbase. The table below lists fields commonly used in policies. For complete definitions, see OPA authorization policies.

FieldType and valuesUse
input.cloudbase.entrypoint_typestring: tcbopenapi or tcbgatewayDistinguish HTTP API and HTTP gateway entry points
input.cloudbase.resource_typestring, such as functions or storagesMatch the resource type; combine with the request path to match a specific function
input.subject.auth_typestring: administrator, internal, external, anonymous, unauthenticated, service_role, anon, or authenticatedMatch the identity associated with the credential; case-sensitive
input.subject.user_idstring; "" when not signed inMatch the end-user ID
input.subject.groupsstring[]Match user role groups from the request JWT, not CAM policies
input.cloudbase.env_id and input.cloudbase.regionstringMatch the environment ID and region
input.request.method, input.request.path, and input.request.hoststringMatch the method, path, and domain; methods are uppercase, paths retain URL encoding, and hosts are lowercased with ports removed
input.request.client_ipstring: empty, IPv4, or IPv6Match the request source IP
input.request.header and input.request.header_mapobject<string, string[]> and object<string, string>, respectivelyRead multi-value or single-value headers; keys use HTTP Canonical form, such as X-Env-Id

Sensitive headers such as Authorization and Cookie are removed. A custom header or source IP alone cannot prove that a request comes from a specific Cloud Function. input does not include a function runtime role ID, so these fields cannot automatically distinguish browser code from function code.

Read-only diagnostics​

1. Retrieve the current policies​

These commands read the user policy and platform extension policy without changing configuration or invoking functions. Replace <env-id> with the actual environment ID.

tcb policy get -e <env-id> --json
tcb policy get -e <env-id> --extension --json

The platform extension policy is not the complete platform default policy. Also consult the Platform default policy when checking default access behavior. For command parameters, see Get policy contents.

You can also use the Manager SDK permission APIs:

MethodMinimum versionReturns
permission.describeAuthzProfile()v5.10.4The active authorization engine; opa for PG environments
permission.describeEnvAuthzConfig()v5.5.5Policy contents for authz.user.rego and authz.platform.extension.rego

These APIs return configuration, not a request's input or a rule-by-rule trace. An empty legacy security-rule list does not mean the OPA policy is empty.

2. Inspect existing denied responses​

If a policy uses deny contains "reason", a denied response can include that custom reason. Boolean deny does not provide a custom reason.

Retain the response's RequestId, error code, request time, environment ID, and request path, and check existing logs. A request ID alone cannot reconstruct the full OPA input or rule matches.

warning

Do not add denial rules that output user identities or credentials for debugging; denial reasons may be returned to clients.

3. Local tests and limits​

Use local opa test with test input to check rule logic without changing cloud configuration. Cover the target path, subpaths, other function paths, and administrator identities.

Local tests do not issue cloud requests. Validate cloud compatibility and actual request denials in a test environment. Check database privileges and RLS separately; see Permission and RLS issues.

Cloud policies must use the authz.user package and Rego v1 syntax. Policy size is limited to 2 KiB, including comments and blank lines, with at most 20 non-default rules. Built-ins are restricted by an allowlist. For detailed limits, see OPA authorization policies.