Users, authentication and authorization
This chapter is about securing your applications. How pgkiln itself is protected (and the security review) is in SECURITY.md.
Authentication: who is the user?
Each application chooses its authentication in Settings:
| Authentication | Behaviour |
|---|---|
| App users | A login page at /a/<alias>/login, checked against the user directory |
| HTTP header | A trusted reverse proxy names the user (below) |
| Database accounts | PostgreSQL login roles and their passwords (below) |
| Custom | Your own PL/pgSQL checks the user name and password (below) |
| None | A public application. Everybody is nobody |
In an app with a login, pages require sign-in unless Requires authentication is unchecked on the page (for a public start page, for example).
The user directory
Like APEX's workspace accounts, pgkiln has one account per person for the whole installation (Builder → Users, table meta.account):
| Field | Meaning |
|---|---|
| Username | Unique, not case-sensitive; no spaces or colons |
| Name, e-mail | For display |
| Password | bcrypt hash, following the password rules below. May be empty for accounts that only sign in through single sign-on |
| Active | Inactive accounts can't sign in anywhere; deactivating ends their sessions |
Passwords and My account
The builder and the runtime cover what APEX offers for its accounts:
| APEX | pgkiln |
|---|---|
APEX_UTIL.CHANGE_CURRENT_USER_PW | My account (user menu → My account, /a/<alias>/account): current password, new password twice. Other sessions of the account end |
| Require Change of Password on First Use | Checkbox when creating an account or setting its password in the builder (on by default). The next sign-in asks for a new password before continuing |
APEX_UTIL.RESET_PASSWORD | Users → account → Set password, or meta.set_password(username, password, change_on_first_use default true) |
APEX_UTIL.EXPIRE_END_USER_ACCOUNT / UNEXPIRE_… | Expire password / Unexpire password, or meta.expire_password(username) / meta.unexpire_password(username) |
| Account Password Lifetime (days) | Users → Account settings → Password lifetime (0 = never). Expired passwords must be changed at sign-in; My account shows the days left. (sprint 223) A workspace can set a shorter one for its applications (workspace account login controls) |
| Password complexity rules | Minimum length, letters and digits, and never containing the username (Account settings) |
| — (no APEX equivalent) | Refuse passwords known from data breaches (Account settings, off by default): see below |
| Maximum Login Failures / unlock | Sign-in locks for LOGIN_WINDOW_MINUTES after LOGIN_MAX_FAILURES_PER_USER failures. Unlock sign-in on the account lifts it at once. (sprint 223) A workspace can allow fewer failures, and ask for longer passwords, in its applications (workspace account login controls) |
Breached passwords
Users → Account settings → Refuse passwords known from data breaches (administrators; also the Password policy tile of Administration) checks every password that is set or changed, for developers (Developers → Change password, Add developer, pgkiln users password) and for application users (the builder's Users, My account, an expired password, Forgot password?, Create Application's administrator; not meta.set_password called from SQL), against Have I Been Pwned's Pwned Passwords. It is off by default. Signing in is never checked.
It uses the k-anonymity range API: the server computes the password's SHA-1 and sends only its first 5 hexadecimal characters (GET https://api.pwnedpasswords.com/range/<prefix>, with Add-Padding: true, so the size of the answer says nothing either); the answer lists the suffixes of every breached password with that prefix, and the server compares them itself. The password and its full hash never leave the server. A password that is on the list is refused (This password appears in known data breaches).
The request goes through pgkiln's outbound guard (src/webclient.ts) with an allow-list of that one host: the address it connects to is checked (no private, loopback or link-local address), redirects elsewhere are refused, and the whole exchange has a 3-second time limit. It fails open: when the service can't be reached, is slow or answers something else, the password is accepted and a warning goes to the server's log and the activity log (password_check_failed). An installation without outbound internet access should leave it off. The rule is the instance's, for every application; turning it on or off is logged (instance_settings).
The meta.set_password/expire/unexpire functions are owner-only. Grant them to an app role if you want to build user administration pages inside an application.
A user who forgot their password asks an administrator, who sets a temporary one under Users → account → Set password, with Require change of password on first use ticked (the default), or uses Forgot password? when the application offers it (below).
Forgot password
With Application settings → Sign-in methods → Offer "Forgot password?" the sign-in page (the built-in one or the application's own login page) has a Forgot password? link (APEX apps don't have one out of the box). It needs an enabled mail service with a From address for the application; without one the link isn't shown. It is for passwords of the user directory only: not for LDAP, single sign-on, database accounts or custom authentication.
- The user types their user name or e-mail address. The answer is always the same, whether or not an account matched, so the page doesn't tell who has an account.
- An active account with a password and an e-mail address that may use the application gets an e-mail (in the user's language) with a link to
/a/<alias>/password/reset?token=…, built fromPUBLIC_URL, never from the request'sHostheader. - The link works once, for 30 minutes, in this application only. Opening it moves the token into the session and out of the address bar; the user chooses a new password (the password policy applies).
- The new password ends every session and Keep me signed in token of the account, and makes the account's other open links useless.
Only a SHA-256 hash of each token is stored (meta.password_reset, owner only). Requests are limited to 5 per address in 15 minutes and 3 mails per account per hour; they count towards the application's daily mail limit and show in the activity log (password_reset_request, password_reset).
The login page
/a/<alias>/login shows pgkiln's sign-in page: the application's icon and name, the sign-in methods and, when the application has several languages, a language picker. (NX-U6) The card takes the application's look: its icon (the PWA icon when the application is installable, else its initial on the accent colour) and the theme's colours from Settings → User Interface (the header colour behind the card, the accent on the buttons). Remember username appears unless it is turned off and Keep me signed in when Settings → Sign-in → Keep me signed in (days) is set (both), Forgot password? when it is turned on and the application has a mail service (Forgot password); Sign in with a passkey when users may sign in with a passkey alone. To design your own (APEX: the login page, usually page 9999), choose Application settings → Sign-in methods → Create a login page: it adds page 9999 (or the next free number) that doesn't require authentication, with page template Minimal (no navigation) and a Login region, and makes it the application's Login page. From then on /a/<alias>/login (and every page that needs a signed-in user) sends visitors there.
Edit it like any page: add static content, images, lists of links or any other region around the Login region, which is the sign-in form (Sign in with a passkey, identity providers, user name and password, Remember username, Keep me signed in, Forgot password?). (sprint 231) Its attributes {"remember_username": false} and {"persistent_auth": false} leave those two boxes out (a region can hide Keep me signed in, never offer it where the application doesn't). The form still posts to /a/<alias>/login, so throttling, the CSRF check and every sign-in method work as on the built-in page; a failed sign-in comes back to the login page with its message and the user name. A login page that requires authentication, or doesn't exist, is ignored (the built-in page shows) and the Advisor reports it; so does a login page without a Login region.
(NX-U2) The Login page list offers only the pages that can be one: pages that don't require authentication and have a Login region. A note under it says how many pages were left out, and a current choice that no longer qualifies stays in the list with the reason, until you choose another.
With single sign-on, password changes happen at the identity provider; My account says so.
My account also holds the user's preferences: light or dark (when the app allows it) and the language (when the app has translations). See chapter 14.
Access control per application
Each application decides who may use it (Shared Components → Access control, like APEX's Application Access Control):
| Setting | Who may sign in |
|---|---|
| Only accounts listed (default) | Accounts that have been granted access to this application |
| Any active account | Every active account in the directory |
Granting access assigns roles for that application (admin, manager, …), which authorization schemes and meta.has_role() check. The same person can be an administrator in one app and a plain user in another. Grant access from the application (Access control) or from the account (Users → account → Application access).
Role names are free text, so under each roles field the builder lists the roles the application actually checks: role-type authorization schemes, meta.has_role('…') calls in SQL schemes and page components, identity-provider group mappings, and roles already given to other users. Click one to add it; hover over it to see where it is checked. A role that nothing checks has no effect.
Roles are resolved at sign-in and kept with the session. When you change someone's roles or revoke access, their sessions in that app end, so the change applies at their next sign-in.
An account without access to an app gets the same "Invalid username or password" as a wrong password, so the login page doesn't reveal which accounts exist or which apps they use.
In SQL (for scripts and migrations):
insert into meta.account (username, display_name, password_hash)
values ('alice', 'Alice Example', meta.hash_password('a-strong-password'));
insert into meta.app_access (app_id, account_id, roles)
select a.id, u.id, '{manager}'
from meta.app a, meta.account u
where a.alias = 'hr' and u.username = 'alice';Scripts written for older versions keep working: meta.app_user is now a view, and inserting into it creates the account (if needed) and grants access:
insert into meta.app_user (app_id, username, password_hash, roles)
select id, 'alice', meta.hash_password('a-strong-password'), '{manager}' from meta.app where alias = 'hr';Single sign-on (OpenID Connect)
Applications can let people sign in with your organisation's identity provider: Microsoft Entra ID, Google Workspace, Okta, Keycloak, Auth0 or any other OpenID Connect provider. (0.63) The same providers, SAML ones and LDAP directories can sign developers in to the builder too (chapter 3).
1. Register pgkiln at the provider as a web application (confidential client) using the authorization code flow. The redirect URI is <PUBLIC_URL>/sso/callback/<name>, for example https://apps.example.com/sso/callback/entra. Note the client ID and secret, and ask for a groups claim in the ID token if you want to map groups to roles.
2. Add the provider under Builder → Users → Identity providers:
| Field | Meaning |
|---|---|
| Name | Used in URLs (entra, google, keycloak) |
| Button label | "Sign in with …" |
| Issuer URL | e.g. https://login.microsoftonline.com/<tenant>/v2.0, https://accounts.google.com, https://keycloak.example.com/realms/acme. pgkiln reads <issuer>/.well-known/openid-configuration |
| Client ID / secret | From the registration. The secret is write-only in the builder and readable only by the owner connection |
| Scopes | Default openid profile email |
| Username claim | The claim that becomes the pgkiln username. Choose one users cannot change themselves: preferred_username (Keycloak), upn or email (Entra), email (Google) |
| Groups claim | Default groups; dot paths work (realm_access.roles) |
| Create accounts automatically | Create a directory account on first sign-in; otherwise only people with an account linked to the provider (or linked below) can sign in |
| Link existing accounts | On the first sign-in, link an existing account with the same username. Turn it on only when users can't choose the username claim at the provider, and off again once accounts are linked: otherwise someone could register an existing account's name there and sign in as that account. With the email claim only addresses the provider marks verified (email_verified: true) link |
Use Test discovery to check the issuer URL.
3. Enable it per application under Settings → Sign-in methods (tick the provider; untick Username and password for SSO-only apps).
4. Map groups to roles (optional) under Shared Components → Access control → Identity-provider groups → roles, e.g. hr-managers → manager. Members of a mapped group get the role in that app for their session, and may sign in even when they aren't listed individually.
How accounts are matched:
- The first sign-in links the identity (the provider's stable subject id,
sub) to the account with the same username when Link existing accounts is on, or creates the account when Create accounts automatically is on. Otherwise an existing account of that name is refused ("not linked to this identity provider"). - Identity providers, LDAP directories and the password policy are changed by administrators only (they decide who can sign in to every application).
- Later sign-ins use the link, so a user renaming themselves at the provider can't take over another account. An account can be linked to only one identity per provider.
- Access follows the same rules as passwords: the app's access control, the account's roles in the app, plus roles from mapped groups. Inactive accounts can't sign in.
Protections built in: PKCE (S256), a one-time state bound to the browser that started the sign-in (stops login CSRF and replay), a nonce in the ID token, and signature verification against the provider's published keys with issuer, audience and expiry checks.
Signing in to a second application with the same provider is silent: the provider's own session answers without asking for a password again.
Try it locally with the bundled Keycloak:
docker compose --profile sso up -d keycloak # http://127.0.0.1:8180 (admin / admin)
psql "$DATABASE_URL" -f examples/keycloak-sso.sqlThe HR sample's login page then shows Sign in with Keycloak. Keycloak users: king / king-sso (groups hr-admins and hr-managers), allen / allen-sso, and carol / carol-sso (hr-managers; she has no pgkiln account yet and is created on first sign-in).
Single sign-on (SAML 2.0)
For identity providers that speak SAML (ADFS, Shibboleth, Entra ID, Okta, Keycloak, …), add the provider under Users → Identity providers with protocol SAML 2.0:
| Field | Meaning |
|---|---|
| Issuer | The IdP's entity ID (from its metadata). Assertions from any other issuer are refused |
| Client ID | pgkiln's entity ID at the IdP. Empty: <PUBLIC_URL>/sso/saml/<name>/metadata |
| IdP sign-in URL | The IdP's SingleSignOnService location (HTTP-Redirect binding) |
| IdP signing certificate | The IdP's certificate (PEM, or the base64 from its metadata). Assertions must be signed with it |
| Username claim | nameID, or the name of an attribute (e.g. uid, email) |
| Groups claim | The attribute holding the groups (e.g. groups, memberOf) |
At the IdP, register pgkiln with the metadata at <PUBLIC_URL>/sso/saml/<name>/metadata (entity ID and assertion consumer service <PUBLIC_URL>/sso/saml/<name>, HTTP-POST binding), sign the assertions, and add a group attribute. Enable the provider per application and map its groups to roles exactly as for OpenID Connect; accounts are linked by the NameID.
pgkiln checks the assertion's signature, issuer, audience, recipient and validity period, and that the response answers an AuthnRequest this browser started, once (InResponseTo, a one-time RelayState and the browser-binding cookie, as for OpenID Connect). Because the IdP posts the response from another site, where SameSite=Lax cookies aren't sent, pgkiln answers with a short page that posts it on to itself (submitted by app.js; a Continue button without script).
Try it locally: the bundled Keycloak realm has a SAML client for pgkiln.
docker compose --profile sso up -d keycloak
psql "$DATABASE_URL" -f examples/keycloak-saml.sql # reads Keycloak's signing certificateThe HR login page then offers Sign in with Keycloak (SAML), with the same Keycloak users.
Multi-factor sign-in at the identity provider
With single sign-on the provider asks for the second factor, in its own sign-on policy (Entra ID Conditional Access, Okta and Keycloak authentication flows, OCI IAM sign-on policies). APEX trusts that policy blindly; pgkiln (0.66) can check that the provider really did it. On the provider (Users → Identity providers), under Multi-factor sign-in:
| Field | Meaning |
|---|---|
| Require multi-factor sign-in at this provider | Refuse every sign-in through this provider, to applications and to the builder, that the provider does not mark as multi-factor. The user sees The identity provider did not confirm a second factor; the Activity monitor logs it as a failed sign-in |
| Ask the provider for | Sent with every sign-in: OpenID Connect acr_values, or SAML AuthnContextClassRef values (a RequestedAuthnContext, comparison exact), separated by spaces. Empty: nothing is asked for |
| Values that mean multi-factor | The values that count, separated by spaces; any one is enough. OpenID Connect: an entry of the ID token's amr claim (RFC 8176) or its acr. SAML: the assertion's AuthnContextClassRef |
| Ask pgkiln's own second step after this provider | For providers that cannot require MFA themselves: see below |
The default values are mfa (Entra ID, Okta and Auth0 put it in amr after a second factor), Entra ID's SAML http://schemas.microsoft.com/claims/multipleauthn, and SAML's MobileTwoFactorContract and MobileTwoFactorUnregistered. For Keycloak, name the level of your step-up flow (for example request and accept gold, or 2 with the default level-of-authentication mapping); for a SAML IdP, the class it sends after a second factor. Without Require, a provider that does say mfa still counts: the session then has a recent second step for step-up, and the Activity monitor shows sso:<provider> (mfa).
Step-up through the provider. A user who signed in through a provider and opens a page behind an authorization scheme with Second step within (minutes) goes back to that provider, which is asked to sign them in again (OpenID Connect prompt=login and max_age=0; SAML ForceAuthn) with the requested context. The answer must carry one of the multi-factor values, a sign-in time (auth_time, or the SAML AuthnInstant) of the last ten minutes, and the identity already linked to the signed-in account; nothing is created or linked on the way. The page then opens.
pgkiln's own second step after the provider. With Ask pgkiln's own second step after this provider on, a sign-in through the provider is followed by the application's two-factor rule exactly as after a password (users add an app or a passkey on My account, or while signing in when the application requires one), and step-up asks for that factor instead of going back to the provider. For the builder, a developer with a second factor gives it after the provider; one without is treated like a password sign-in, so a two-factor rule of the instance or workspace makes them add one.
LDAP and Active Directory
Applications can check passwords against LDAP directories (OpenLDAP, Active Directory, 389 Directory Server, …), APEX's LDAP Directory scheme. The username and password form checks local accounts first, then the directories enabled for the app, in order.
Add a directory under Users → LDAP directories:
| Field | Meaning |
|---|---|
| URL | ldaps://host (TLS) or ldap://host:389; tick StartTLS to upgrade ldap://. Plain ldap:// sends passwords unencrypted |
| Service account DN / password | Searches users and groups. Empty: an anonymous search. The password is write-only |
| User search base / filter | Where users are and how to find one: (uid={username}), Active Directory (sAMAccountName={username}). {username} is escaped (RFC 4515) |
| Username attribute | The pgkiln username (uid, AD sAMAccountName) |
| Group attribute | e.g. memberOf (group DNs; the first value of each is the group name) |
| Group search base / filter | Optional: search groups too, e.g. (member={dn}) |
| Create accounts automatically | As for single sign-on |
Test connection binds as the service account and checks the search base (or looks a user up). Then tick the directory under the app's Settings → Sign-in methods (keep Username and password on) and map groups to roles under Access control, as for single sign-on.
Signing in searches the user, then binds as that user with the password given. Empty passwords are refused before that (LDAP treats them as an anonymous bind). Accounts are linked by the entry's entryUUID (or its DN), with the same rules as single sign-on; a local password keeps working next to the directory one. When a directory can't be reached, users see that, and the next directory is tried. Try it locally: docker compose --profile ldap up -d ldap, then psql "$DATABASE_URL" -f examples/ldap-directory.sql (users blake / blake-ldap, dora / dora-ldap).
HTTP header authentication (reverse proxy)
Behind a reverse proxy or single sign-on gateway that already authenticates users (Apache mod_auth_mellon, oauth2-proxy, an Entra ID application proxy, Kerberos at the proxy, …), an application can take the user name from a request header, APEX's HTTP Header Variable scheme. In Settings → Security choose Authentication HTTP header (reverse proxy) and set:
- User name header: the header the proxy sets (empty:
X-Remote-User); - Create accounts automatically: an unknown user name gets a new account with access to this app. Off: the account must exist, be active and have access (Users → Accounts), as for the other sign-in methods;
- Sign-out URL: where Sign out goes after the session ends, usually the proxy's own sign-out page (an
http(s)://URL or a path). Without it the user sees a "signed out" page; the next page they open signs them in again through the proxy.
Anyone can send a header, so pgkiln trusts it only from the proxies listed in the environment variable PGKILN_AUTH_HEADER_PROXIES (comma-separated IPs and CIDRs, e.g. PGKILN_AUTH_HEADER_PROXIES=10.0.0.5, 192.168.10.0/24). The check uses the address of the TCP connection itself, never X-Forwarded-For, so TRUST_PROXY doesn't change it. Unset, or a request from any other address: the app shows an error page and the activity log records a login_failed entry (header: untrusted peer …). Make sure users can't reach pgkiln directly, bypassing the proxy, and that the proxy removes the header from incoming requests before it sets its own.
The first request with the header signs the user in (activity log: login, detail header) and the session is bound to the header value: when a later request carries another user name, or none, the session ends (and, with another name, a new one starts for that user). The value must be 1 to 100 printable ASCII characters without spaces, colons or commas; a repeated header is refused. The password form, LDAP, single sign-on buttons and Keep me signed in are not used by these apps, and form submissions still need the session's CSRF token.
Database accounts (PostgreSQL roles)
APEX's Database Accounts scheme: users sign in with the name and password of a PostgreSQL login role. In Settings → Security choose Authentication Database accounts and set who may sign in:
- Allowed roles: login role names, comma separated (exact, case-sensitive names); and/or
- Or members of role: every member (direct or inherited) of this role may sign in too.
With neither set nobody can sign in. pgkiln never reads pg_authid: it checks the password by opening a short-lived connection as that role to its own database (host, port, database and SSL settings of DATABASE_URL), asks PostgreSQL whether the role is a superuser and a member of the membership role, and closes the connection. So PostgreSQL applies its own rules: the password, NOLOGIN, VALID UNTIL, CONNECTION LIMIT and pg_hba.conf (which must allow password logins for these roles from the pgkiln server). Superusers and pgkiln's own connection roles (the users of DATABASE_URL and RUNTIME_DATABASE_URL) are always refused, even when listed. An unlisted name is refused before any connection is made (unless a membership role is set).
The session's user (:APP_USER) is the role name; app roles come from Access control like for other users (an account of the same name, if there is one). The application's SQL still runs as the app's database role (parsing schema), not as the signed-in role. Wrong passwords, unknown, unlisted or refused roles all get the same "invalid" answer and count towards the sign-in throttling (LOGIN_MAX_FAILURES_PER_USER, LOGIN_MAX_FAILURES_PER_IP); the activity log has login (detail database) and login_failed with the reason (database: role not allowed, superuser refused, connection refused (28P01), …), never the password. When the database can't be reached the page says so (503). Keep me signed in, LDAP, single sign-on and the password-change form are not used by these apps.
Custom authentication (a PL/pgSQL function)
APEX's Custom authentication scheme: your own code decides whether a user name and password are valid, e.g. against a users table of your application. In Settings → Security choose Authentication Custom and fill in, under Custom authentication, one of:
- Function name: a function
(p_username text, p_password text) returns boolean, in lower case, optionally with its schema (app.check_login). The app's database role needsEXECUTEon it. It takes precedence over the body. - Or function body: PL/pgSQL with
p_usernameandp_password, returningtruefor a valid sign-in, either a barereturn …;or a wholedeclare … begin … endblock:
return exists (select 1 from app.users
where name = p_username and not locked
and pw_hash = crypt(p_password, pw_hash));- Or password hash query: SQL with
p_usernamereturning the user's stored password hash, for users whose passwords another system hashed (below).
Optionally, Post-authentication code runs after a successful check with p_username (and meta.app_user() set to it), e.g. to record the last sign-in; raising an exception refuses the sign-in. After login application processes run afterwards as usual.
Both run as the application's database role, in one transaction, in a temporary function that is dropped again; nothing is kept unless the check returns true and the post-authentication code succeeds. The password is only ever a query parameter: it is never part of the SQL text, never stored and never logged. A check that returns false or null, or raises an error, gets the same "invalid" answer as a wrong password and counts towards the sign-in throttling; the activity log has login (detail custom) and login_failed with custom: check returned false, check failed (<SQLSTATE>) or post-authentication failed (<SQLSTATE>), never the error message (it could repeat the password). With no function, body or hash query nobody can sign in; with more than one, the function wins, then the body.
The session's user (:APP_USER) is the user name as typed, unless the post-authentication code names it (below); app roles come from Access control like for other users (an account of the same name, if there is one), or from the app's own tables in authorization schemes.
Setting the user name
A check that signs users in by e-mail address accepts Jan@X.nl and jan@x.nl alike, but without more they would be two users (their own saved reports, preferences, created_by values and :APP_USER comparisons). APEX's apex_custom_auth.set_user sets the canonical name; in pgkiln the post-authentication code calls meta.set_auth_user(name) (sprint 241, migration 197):
perform meta.set_auth_user(lower(p_username));
-- or the account an e-mail address belongs to
perform meta.set_auth_user((select username from app.users where email = lower(p_username)));- The session is created for that name: roles from Access control, authorization schemes,
:APP_USER, Keep me signed in, the after login processes. The rest of the post-authentication code already sees it (meta.app_user(), audit columns). - The activity log's
loginrow has the new name, withcustom; signed in as typed: Jan@X.nl. Sign-in throttling counts the name as typed. - The name must be 1–100 characters without control, line-separator, zero-width or bidirectional formatting characters (spaces around it are dropped), and not
nobody(the user who isn't signed in);meta.auth_user_problem(name)says why one isn't. Otherwise the sign-in is refused (post-authentication failed). - It works only there: anywhere else (a page or application process, an Ajax callback, the check function itself, the SQL Workshop, another application) it raises an error. The server reads the name in one place, right after the post-authentication code of the application being signed into, in the same transaction, and checks it again; a setting written some other way (
set_config) before or after that point is never read. The session is a new one (no session fixation), as for every sign-in. The Advisor flagsmeta.set_auth_userin any other component. - The name is whatever your code says, so the code decides who the user is: name only the account the checked credentials belong to.
The App Gallery's Sample Processes signs DEMO, Demo and demo in as demo this way. The login page has the user name and password form only: Keep me signed in, LDAP, single sign-on and the password-change form are not used by these apps.
Password hashes of another system
(sprint 248, migration 204) When the users come from another system (a Django or PHP application, a database you migrate from), their passwords are hashes that system wrote. Checking them in PL/pgSQL is slow: Django's default of 1,000,000 PBKDF2 iterations takes over a second per sign-in there. Fill in Or password hash query instead: SQL with p_username that returns the stored hash (one row, one text column; no row or null for an unknown user):
select password from app.auth_user where username = lower(p_username) and is_activeThe query runs as the application's database role, read-only (in a temporary stable SQL function), and never sees the password. pgkiln then checks the password against the hash in the server and compares in constant time:
| Format | Written by | Checked with |
|---|---|---|
pbkdf2_sha256$<iterations>$<salt>$<base64> | Django (the default hasher) | Node's crypto.pbkdf2, about 0.15 s for 1,000,000 iterations |
pbkdf2_sha1$… | Django (PBKDF2SHA1PasswordHasher) | the same |
$2a$, $2b$, $2y$ | bcrypt: PHP's password_hash, Node, Python, Ruby | pgcrypto's crypt() in the database ($2b$ and $2y$ are the same algorithm as $2a$) |
bcrypt$$2b$…, bcrypt_sha256$$2b$… | Django's bcrypt hashers | the same (bcrypt_sha256 hashes the password with SHA-256 first, as Django does) |
Argon2 ($argon2id$…, Django's argon2$…) is not supported, nor bcrypt's old $2x$: such a user can't sign in, and the activity log says why. Store those users' hashes again with meta.make_password_hash, e.g. when they reset their password. PBKDF2 hashes with more than 10,000,000 iterations and bcrypt costs over 16 are refused as unreadable.
Every refusal looks the same: a wrong password, an unknown or inactive user (no row), a hash that can't be read, an unsupported format and a query that fails or returns more than one row all get the same "invalid" answer, count towards the sign-in throttling, and take about as long: an unknown user gets a dummy check of the same kind and cost as the application's last real one. The activity log has the reason: custom: hash query: wrong password, unknown user (no hash), hash query failed (<SQLSTATE>), the hash query returned more than one row, or what is wrong with the hash. The post-authentication code runs after a successful check as with the other kinds.
meta.make_password_hash(p_password, p_format, p_cost) writes a hash the check (and the other system) reads, e.g. on a password-change page or for a new user:
'bcrypt'(the default): pgcrypto's bcrypt,$2a$, costp_cost4–16 (default 12); PHP'spassword_verifyaccepts it.'pbkdf2_sha256'or'pbkdf2_sha1': Django's format with a random 22-character salt andp_costiterations (1,000–10,000,000, default 1,000,000). It is computed in PL/pgSQL, about 1.2 s for 1,000,000 iterations: fine when a password changes, too slow to check every sign-in with.
update app.auth_user set password = meta.make_password_hash(:P3_PASSWORD, 'pbkdf2_sha256')
where username = :APP_USERThe App Gallery's Sample Sign-in signs in against a Django-style auth_user table this way: demo / demo has a Django hash, php / php one PHP wrote, and Change my password stores a new one in either format.
Session timeout warning
Sessions end after the idle time (SESSION_IDLE_MINUTES, or Instance settings) and at their maximum length (SESSION_MAX_HOURS). Signed-in users are warned before (Settings → Errors and sessions → Session timeout warning, default 120 seconds; 0: no warning; APEX: Session Timeout Warning): a dialog says when the session ends and offers Stay signed in, which marks the session active (POST /a/<alias>/session/extend, with the session's CSRF token). At the maximum length the user can only save their work; when the session has ended the dialog offers to sign in again and comes back to the page.
Session limits per application
(sprint 189) Settings → Errors and sessions → Session management (APEX: Security Attributes → Session Management):
- Maximum idle time (1–1440 minutes) and Maximum session length (1–720 hours): empty uses the instance's. An application can only be stricter than the instance: the shorter of the two applies, so a payroll application can end idle sessions after 10 minutes while the others keep 60. The timeout warning uses the same limits.
- Page after a session timeout (APEX: Session Timeout URL): a page of the application without sign-in. A request that brings the cookie of a session that has ended opens it, once, instead of the sign-in page. A first visit without a cookie goes to the sign-in page as before. Only pages of the application can be chosen, so it can't redirect elsewhere.
- Deep linking (on by default): off sends every sign-in to the home page. The sign-in page then gets no
next=address, and one in a link or a posted form is ignored.
The values are meta.app.session_idle_minutes, session_max_hours, session_timeout_page and deep_linking (migration 169), exported with the application.
Remember username and Keep me signed in
(sprint 231, AX-13) The sign-in card has APEX's two boxes of the generated login page (P9999_REMEMBER and P9999_PERSISTENT_AUTH), on the built-in page and in the Login region of an own login page; the form fields are remember_username and remember.
Remember username is on by default (Settings → Sign-in methods → Staying signed in → Offer "Remember username", meta.app.remember_username, migration 189). After a successful sign-in with the box checked, the name that was typed is kept in the cookie pgkiln_user_<app id> of the application's path (/a/<alias>) for 180 days, and the form is filled in with it next time, the box checked and the cursor in the password field. Signing in with the box unchecked removes the cookie; a failed sign-in keeps nothing. The cookie holds the name only, never a token or password, so it signs nobody in; it is HttpOnly (only the server reads it), SameSite=Lax and Secure behind HTTPS (COOKIE_SECURE), and the name is escaped when it is filled in. Turned off, the box is gone and the cookie is neither read nor set. The developers' sign-in at /builder/login has its own Remember workspace and username.
Keep me signed in
Under Settings → Sign-in methods, "Keep me signed in" for (days) (1–365) adds a checkbox to the password form (APEX: persistent authentication). A browser that ticked it stays signed in for that many days after the sign-in, also after the session's idle or maximum time: a long-lived cookie holds a random token (only its SHA-256 is stored, in meta.persistent_login, readable by the owner connection only), which starts a new session and is then replaced by a fresh token, so a copied cookie works once at most. The expiry stays that of the original sign-in.
Each use checks the account again (active, access to the app, roles; directory and identity-provider groups from the sign-in are mapped to roles again). Signing out, a new password, deactivating the account or removing its access ends it, and My account → Sign out on all devices ends it for every browser. An expired password always needs the password form.
Session sharing between applications
Applications that use the user directory (App users) and have the same Session sharing group (Settings → Sign-in methods; lower case letters, digits and _) share a sign-in (APEX: session sharing). After signing in to one, opening another application of the group signs the user in there without the sign-in page:
- each application still checks its own access (an access row, any active account or mapped directory/identity provider groups) and gives its own roles; without access the user gets that application's sign-in page;
- the shared sign-in is a cookie for the whole site (path
/,HttpOnly,SameSite=Lax,Securebehind HTTPS) with a random token; only its SHA-256 is stored (meta.shared_login, readable by the owner connection only); - it ends after the session idle time without use or the maximum session length (Instance settings), when the account is deactivated, and when the user signs out of any application of the group, which also ends the sessions of the other applications that came from it.
Applications of different groups, and applications without a group, sign in on their own.
Two-factor sign-in
APEX has no second factor for an application's own accounts: its documented route is an identity provider whose sign-on policy asks for one, or a hand-written TOTP check in a custom authentication scheme. pgkiln has it built in. Application settings → Sign-in methods → Two-factor sign-in → Second step:
| Setting | Who gives a code after the password |
|---|---|
| Off (the default) | Nobody |
| Optional | Users who added an authenticator app or a passkey on My account |
| Required | Everybody. A user without one adds an app (a QR code, then its first code) or a passkey while signing in, then sees ten recovery codes once |
| Required for some roles | Users with one of the roles in Required for roles (for example admin, manager); others as with Optional |
How it works:
- The second step follows the user directory's password and LDAP directories. An identity provider (OpenID Connect, SAML) asks for its own second factor, which pgkiln can check, or leaves it to pgkiln's second step; database accounts, custom authentication and HTTP header authentication are not covered.
- The code comes from any authenticator app (TOTP, RFC 6238: Google Authenticator, Microsoft Authenticator, 1Password …), each code once, one 30-second step either side for clock drift. A recovery code (ten per account, each usable once) works instead, and leads to My account, which says how many are left.
- Until the code is right there is no session: the pending sign-in waits five minutes (ten while adding an app) in the signed-out session. Wrong codes count as failed sign-ins, so the usual lockout applies.
- An account's apps serve every application it uses, and each application decides whether it asks for them.
- My account → Two-factor sign-in adds an app (QR code or key, then its first code), shows new recovery codes, and removes an app with a current code or a recovery code. The last app can't be removed while the application requires a code of the user.
- A Keep me signed in or session-sharing sign-in skips the second step only when it was made with one (its method ends in
+2fa, shown in the Activity monitor); one made with just a password signs in again with the code. - Users → account → Two-factor sign-in shows who has an app; Reset two-factor sign-in (with a reason, logged as
2fa_reset) removes the apps and recovery codes after a lost phone and signs the account out everywhere. Where an application requires the step, the user adds a new app at the next sign-in. - The apps' secrets are encrypted with the instance key
PGKILN_SECRET_KEY(inmeta.account_factor, readable by the owner connection only); without that key Required can't be chosen, and the sign-in refuses rather than skips the step. Recovery codes are stored as SHA-256 hashes. - The Advisor warns when users with the role
adminsign in with only a password.
Passkeys
Next to authenticator apps, users add passkeys (WebAuthn: a fingerprint, face or screen lock on the device, or a security key) on My account, or while signing in when the application requires a second step and they have none yet (the page offers an app and a passkey). At the second step Use a passkey replaces the code. pgkiln checks the answer itself (challenge, origin, relying party, signature, counter), as for developers. A passkey works only at the host name it was made for (PUBLIC_URL's host, or PGKILN_RP_ID), not at an IP address, and needs JavaScript; codes keep working without either. Passkeys are public keys: they don't need the instance key. The first factor a user adds, app or passkey, brings ten recovery codes.
Signing in with a passkey alone
Beyond APEX, whose sign-in page has no passkeys: Settings → Sign-in → Sign-in methods → Users may sign in with a passkey alone (off by default; meta.app.passkey_signin, migration 173) puts Sign in with a passkey above the username and password, on the built-in sign-in page and in the Login region of an application's own login page. A user who added a passkey on My account taps it, the browser offers the passkeys it holds for the site, the device asks for the fingerprint, face or PIN, and the user is signed in, without typing a username.
- Only for the user directory's own accounts (App users with Username and password on). Identity providers, LDAP directories, database accounts, custom and HTTP header authentication are not covered: they keep their own sign-in.
- The authenticator must verify the user (WebAuthn
userVerification: required, the UV flag is checked), so a passkey sign-in counts as both factors: a user the application requires a second step of is not asked for one after it, and the session counts as having just had one (for step-up). Its method in the Activity monitor ispasskey+2fa, the sign-in's detail passkey (user verified). - The browser finds the passkey without a username (a discoverable credential; the server sends an empty allow list). With the setting on, a passkey added on My account is made discoverable (
residentKey: required); one added earlier, or while signing in as a required second step, may not be: it keeps working for the second step, and the user adds a new one on My account to sign in with it alone. - My account → Two-step sign-in shows the passkeys part when the setting is on, also when the application has no second step (authenticator apps are offered only where it has one). The first passkey brings ten recovery codes, which remove a passkey later.
- The same rules as a password sign-in: the challenge is single-use and kept in the signed-out session (five minutes); origin, relying party, signature and counter are checked as at the second step; the account must be active and may use the application (its access control); the lockout after failed sign-ins applies, also to the right passkey; an expired password is changed with the password first (the page says so); availability modes and authorization apply after sign-in as always. Every failure gives one message (The passkey did not sign you in) and is logged as
login_failedwith the reason (passkey: …), so it counts for the lockout. - Needs JavaScript and a host name (not an IP address). Without either the button is not shown and the password form works unchanged. The setting travels with the application's export and files (an older export imports with it off).
A code by e-mail
Offer a code by e-mail (same settings) adds E-mail me a code instead to the second step, for users who have an authenticator app or a passkey and an e-mail address in the user directory. The code (six digits, valid 10 minutes, once) goes through the application's mail service; at most three per sign-in and five per account per hour. It is never someone's only factor: it is not offered while a user adds their first one, so a lost mailbox or a mail outage never locks anyone out and a stolen mailbox alone never signs anyone in.
Asking again before a sensitive page (step-up)
An authorization scheme's Second step within (minutes) makes it pass only when the session's last second step (code, passkey, e-mail code or recovery code) is at most that old. A page behind such a scheme sends a user who passes the scheme otherwise to Confirm it's you (the second-step page) and back to the page afterwards; regions, buttons and processes behind it stay hidden or skipped until then. A user without a factor is told to add one on My account. Typical: SALARY_EDIT (role hr_manager, second step within 15 minutes) on the page that changes salaries. A Keep me signed in or shared session has no recent second step of pgkiln's own, so it is asked too; a single sign-on session goes back to its identity provider for a new multi-factor sign-in (or to pgkiln's own second step, when the provider leaves it to pgkiln). A form posted after the time ran out is not processed: the user confirms, comes back to the page and submits again.
REST API tokens
A developer's REST API → Issue a token acts as an account without its sign-in, so it is refused for accounts the application requires a second step of. Turn on REST API → Users create their own tokens and those users (and everyone else) create a token on My account → REST API token instead; one who must use two-factor sign-in gives a second step first when their last one is older than 15 minutes. The token is shown once. MCP has no tokens for application users, so nothing to cover there.
What sign-in protects against
- Brute force: after 5 failed attempts for a username (or 50 from one IP address) within 15 minutes, sign-in is refused for the rest of the window, even with the right password.
- User enumeration: unknown users and wrong passwords get the same message and take the same time.
- Session fixation: the session token is replaced at sign-in.
- Stale sessions: 60 minutes idle or 8 hours total (configurable).
- Stolen passwords: two-factor sign-in asks for a code from an authenticator app or a passkey, for every user or for some roles, and again before sensitive pages (step-up); with an identity provider (OpenID Connect, SAML) the provider asks for its own, and pgkiln checks that it did. A passkey alone replaces the password with a user-verified key that can't be phished or reused on another site. Developers have two-factor sign-in for the builder too.
- Weak builder passwords (sprint 201): a developer's new password has at least 12 characters (more when the users' minimum password length is higher), in the builder and with
pgkiln users … --developer; existing passwords keep working until they are changed. Application users keep their own policy. pgkiln doesn't check passwords against a list of breached passwords (it would send part of a hash to an outside service): use two-factor sign-in, or a password manager's check.
All sign-ins, failures and lockouts appear in the Activity monitor.
Authorization: what may the user do?
Authorization schemes
An authorization scheme is a named rule (Shared Components → Authorization schemes):
| Type | value | Passes when |
|---|---|---|
role | a role name, e.g. admin | the user has that role |
sql | a SQL boolean expression | the expression is true, e.g. meta.has_role('manager') or meta.has_role('admin') |
Plus the built-in MUST_NOT_BE_PUBLIC_USER (signed in). Reference a scheme by name in the authz property of a page, region, item, button, process, dynamic action or navigation entry; prefix it with ! to negate (!ADMIN). Unknown schemes fail closed (deny). Each scheme is evaluated at most once per request, and its error_message is shown when a page is refused. With Second step within (minutes) it also needs a recent second factor (step-up).
What happens when a scheme fails:
| On | Effect |
|---|---|
| Page | 403 page with the scheme's error message; links and menu entries to the page are hidden |
| Region | Not rendered, together with its items and buttons |
| Item | Not rendered, and cannot be set by a submit |
| Button | Not rendered, and cannot be pressed (a forged request gets 403) |
| Process | Skipped |
| Dynamic action | Not sent to the browser, and refused by the server |
| Navigation entry | Hidden |
Conditions
condition (regions, buttons) and readonly_condition (items) are SQL expressions evaluated per request. They're for state ("show Approve only while the request is pending") rather than identity, but they're enforced the same way: a hidden button can't be pressed.
Row level security: the database decides
Authorization schemes control the user interface. For data, the strongest and simplest protection is PostgreSQL's row level security, because it applies to every region, grid, list of values, process and dynamic action at once, and to any other tool that uses the same role.
The app's queries run as its database role with meta.app_user() and meta.has_role() available, so policies can reference the application user:
alter table tasks.task enable row level security;
-- everyone sees only their own tasks; admins see everything
create policy own_tasks on tasks.task
using (owner = meta.app_user() or meta.has_role('admin'))
with check (owner = meta.app_user());Patterns from the HR sample:
-- employees see their own leave requests, managers those of their team
create policy leave_visible on hr.leave_request for select
using (empno = hr.current_empno() or hr.is_manager_of(empno) or meta.has_role('admin'));A row hidden by RLS is simply absent: a report doesn't show it, and a form says "record not found" (identical to a row that doesn't exist, so nothing leaks).
Keep in mind:
- The table owner bypasses RLS (unless
FORCE ROW LEVEL SECURITY), so don't make the app role the owner. - Functions declared
SECURITY DEFINERrun as their owner and bypass RLS on purpose, which is useful for triggers that must write notifications for other users (hr.notify_leave_decided). Keep them small and setsearch_path.
The application's own database role
(sprint 186, NX-S2; APEX: the parsing schema) Every application runs as a database role of its own, its db_role: every page request, process, REST handler, automation, workflow, webhook and background job does SET LOCAL ROLE <db_role> in its transaction, so the grants below and row level security decide what it may do. The role is required, and some roles are refused:
- an empty role: refused by Settings → Security, by every import and by
meta.appitself (migration 167), so a forged settings post or a hand-writteninsertcan't make one either; - a powerful role (
meta.role_is_powerful): a superuser; a role withBYPASSRLS,CREATEROLE,CREATEDBorREPLICATION; pgkiln's own roles (pgkiln_runtime,pgkiln_app_code,pgkiln_authenticator,pgkiln_anon, the workspaces' logins) and PostgreSQL's (pg_*); the owner of pgkiln's schemas; and any role that is a member of one of these (it couldSET ROLEto it) or ofpg_read_all_data,pg_write_all_dataor the server file roles; (sprint 201) and a role with any right on one of pgkiln's own tables (a table inmeta, itself or through its roles:meta.role_reaches_meta). The SQL Workshop's developer logins (sprint 185) use the same check.
Both are refused when the role is saved and when the application runs: a role granted BYPASSRLS later stops the application within seconds.
Where the role comes from. Create Application (blank, from a file, a blueprint, the App Gallery) makes app_<alias> with rights on the application's schema. An import of a file without a role (an old export, an APEX import without --db-role) keeps the role of the application it replaces, or else gets app_<alias>: a new role that can't sign in, a member of pgkiln_runtime in a shared workspace (or one of an isolated workspace's roles), with the wizard's rights on the parsing schema when the import names one (pgkiln import-apex --schema, the builder's APEX import), else no rights yet. The import's result says so; the Advisor then lists the SQL the role can't run. An import never falls back to the owner or the runtime login. A working copy of an application without a role is refused until the application has one.
Applications made before 0.97 without a role (or with a powerful one) keep working for their developers only, until they get one; the upgrade (migration 167) grants nothing and changes no application. Until then:
- the Advisor reports an error, and Settings → Security checklist shows a red line;
- the server refuses to run it (HTTP 503, This application can't run: it has no database role of its own …) for end users, REST modules, AutoREST, automations, workflows, webhooks and background jobs: everything except development mode, a page request from a developer of the application who is signed in to the builder in the same browser (the developer toolbar shows). Even then it runs as the runtime login only when that login doesn't bypass row level security or own pgkiln (
RUNTIME_DATABASE_URLset to the least-privilege role). A powerful role is refused in development mode too; - Settings → Security offers Create app_<alias>: pgkiln creates the role (or reuses it when no other application has it and it isn't powerful) with the wizard's rights on the schema you choose (
USAGE; select, insert, update and delete on its tables; its sequences and functions; and the same for objects made later), and sets it as the application's role.
Database privileges
Give the app role only what the app needs:
grant usage on schema hr to hr_app;
grant select, insert, update on hr.leave_request to hr_app; -- no delete
grant select, update (read_at) on hr.notification to hr_app; -- column-level
grant execute on function hr.request_leave(date, date, text) to hr_app;Apps created in the builder get full DML on their schema by default; tighten this as the app matures. Privileges show up in SQL Workshop → Object Browser.
A data_load process loads files as the app role too, also with a data load definition: a definition naming a table the role can't write fails like any other insert, and a process only finds the definitions of its own application. XML files with a document type declaration are refused (chapter 16). The SQL Workshop (the SQL Worksheet, SQL Scripts, Quick SQL, the Query Builder, Load Data, Unload Data, Sample Data, the Data Modeler, ...) runs as the workspace's developer login (sprint 185, NX-S1): the rights of the workspace's applications' roles and schemas, none in meta, no CREATEROLE; RESET ROLE doesn't leave it. A developer's worksheet can't change pgkiln's own tables, accounts or another workspace's applications. Only an instance administrator may choose the Owner connection in the worksheet's Run as (red, with a reason; the choice and every statement are kept in meta.owner_sql_audit), see chapter 3. Developers still read and change their applications' data: keep developer accounts to people you trust with it. The lockout checks warn when DATABASE_URL is a superuser (chapter 1).
(sprint 201, SEC-1) The developer login reads none of pgkiln's own tables. Not meta.developer (password hashes, administrators), meta.workspace, the mail and AI services, builder tokens, sessions, factors, credentials, the SQL history, the Owner connection's audit or another workspace's rows: select password_hash from meta.developer fails with permission denied, also with Run as an application and with a builder token's run_query. What it may read in meta is a fixed list, checked by a test that enumerates every relation the login can use: the views for application code (meta.tasks, meta.task_events, meta.workflows, meta.workflow_events, meta.my_notifications, meta.process_jobs, meta.saved_reports, meta.data_reports, meta.user_forms, meta.temp_files), which show the rows of the application in pgkiln.app_id and of the session in pgkiln.session_id. A shared workspace's login can't set pgkiln.app_id to another workspace's application (meta.app_id() refuses it, as for isolated workspaces), so it can't use those views or the functions for application code (meta.send_mail, meta.set_app_setting, ...) as that application. Four layers keep it that way: a role with rights on a table in meta is powerful (no application runs as it, no developer login is a member of it); meta.workspace_sync_roles() takes back any right in meta granted to a workspace login itself (also before the server opens a developer login's connections, which fail when that isn't enough); the tables with secrets, credentials, sessions or every workspace's rows (meta.developer, meta.developer_factor, meta.builder_token, meta.workspace*, meta.mail_service, meta.ai_service, meta.instance_setting, meta.account_factor, meta.persistent_login, meta.owner_sql_audit, meta.sql_history, ...; migration 175) have row level security with one policy, the owner of meta and its members, so a grant that slips through shows no row; and the lockout check Developer logins (Instance settings) is an error while a developer login can use a table in meta.
The REST endpoints pgkiln serves (an application's REST modules and the tables and views published with SQL Workshop → RESTful Services, AutoREST) run as the app role too, never as the owner: these grants, column grants and the row level security below decide what an API caller may read and change. AutoREST refuses a role that owns the published object or bypasses row level security, and an object answers only to a bearer token of its application unless the developer chose public for it (chapter 13). (sprint 104) REST module handlers refuse to run as a superuser, a role that bypasses row level security or a member of pgkiln's owner (403). Their parameters are bound: SQL handlers get escaped literals, PL/pgSQL handlers read transaction-local settings through meta.rest_param(); a request can't set the server's binds (APP_USER, …) or real settings. Media handlers are served with a sandboxing Content-Security-Policy and nosniff. Try it in the SQL Workshop calls an endpoint as an account of the application, as a developer issuing a token could (chapter 13).
(sprint 106) The SQL Workshop's Change Log keeps the schema DDL developers run from the worksheet, Table Properties and Schema Comparison, per workspace (only the workspace's developers see it). Statements about roles, databases, servers, user mappings and subscriptions are never recorded, so passwords and connection strings stay out of it; it holds what the DDL says otherwise (defaults, comments, function bodies).
Database users and their passwords
(sprint 99) Administrators create and change PostgreSQL roles in the builder (Administration → Database users, chapter 3). Passwords never reach PostgreSQL or a page in plain text: pgkiln hashes a new password itself into a SCRAM-SHA-256 verifier (random salt, 4096 iterations, SASLprep, like psql's \password) and the statement carries only that verifier, as a literal built with pg's escapeLiteral. The review and the activity log show PASSWORD '********'; the password is typed on the review page, posted once with Apply and not stored, echoed or logged. A server with log_statement = ddl logs the verifier, not the password. Every name is quoted with escapeIdentifier, every value is checked (dates, numbers, schema names, grantable roles) and quoted. The page is for administrators only (others get 403), every change needs the CSRF token, and pgkiln's own roles can't be changed, dropped or granted from it, so the page can't take pgkiln's own connections away.
Data security per table: rows, columns and values
(sprint 119) PostgreSQL has row level security but no column masking, so pgkiln puts a table's security in three layers, all ordinary database objects, and shows them on one page: SQL Workshop → Object Browser → a table → Security (also Security… in the table's ⋯ menu). It is pgkiln's answer to APEX 26.2's Deep Data Security.
Rows: the table's row level security policies (above), listed with a link to Table Properties to switch row level security on and to Add policy.
Columns: a matrix of database roles × columns with read and update per cell. The rows are the roles that have privileges on the table and the database roles of the workspace's applications (with the applications that run as them). Apply writes
GRANT/REVOKE SELECT (c, …)andUPDATE (c, …). A column a role may not read is refused by PostgreSQL ("permission denied") whoever sends the query. The table's owner, superusers and roles that bypass row level security are listed apart: column privileges can't restrict them.Values: masked columns per application role (
meta.has_role()of the signed-in user). A column's mask is empty (null),***or***plus the last four characters; tick the application roles that see the real value, and Everyone else for users with none of the listed roles. The masks live in a masking view next to the table (default name<table>_masked):sqlcreate view sales.orders_masked with (security_barrier) as select t.id, t.customer, case when (select meta.has_role('manager')) then t.amount end as amount, case when false then t.iban::text else '***' || right(t.iban::text, 4) end as iban from sales.orders t;The view is owned by a role per schema,
<schema>_masking(nologin), which pgkiln creates the first time. That role is no owner, superuser or role that bypasses row level security (Apply checks it), so the table's policies still apply inside the view; and it is a member of the database roles that read the table, so policies writtento <role>apply as well. The configuration is kept in the view's comment, so it travels withpg_dump, Generate DDL and the change log; there is nometatable for it.
Preview SQL shows the statements, Apply runs them in one transaction (and records a change set in the Change Log), Open in the worksheet puts them there. Nothing is changed when one statement fails.
The mask holds only where the view is read. As long as a role may still read the raw column on the table, its queries on the table see the value; the preview warns about each such column. Point the application's pages, REST handlers and AI tools at the view, then untick read of the masked columns for the role, and the value is masked everywhere that role connects.
Every client meets the same rules because they all run as the application's database role with the same identity:
| Client | Runs as | meta.app_user() / meta.has_role() from |
|---|---|---|
| Pages, processes, dynamic actions, AI assistant and AI agent tools | the application's role (appTx) | the session |
| REST module handlers, AutoREST | the application's role | the bearer token (its user, the user's roles) |
The MCP server's run_query with alias (and user) | the application's role | the user's roles in the application (chapter 20) |
| psql, other tools | whatever role they log in as | — (only grants and policies apply) |
Policies and masks that use meta.has_role() can be combined: with a policy that shows a manager the rows of their department, and amount masked for everyone but manager, a clerk reads their own rows with an empty amount. Policies written per database role (to sales_app) apply to the masking role for every role it is a member of, so prefer policies on meta.app_user() / meta.has_role() on tables with a masking view. The HR example's page 48 Salaries (masked) reads hr.emp_masked (examples/hr/hr_70_data_security.sql).
Webhooks and callbacks
(sprint 177) Two places where the server runs your SQL without a signed-in user:
- Inbound webhooks (chapter 13). A webhook handler has no token: the signature is its authentication. It is an HMAC-SHA256 with a shared secret over the raw bytes of the body (or Stripe's
t.body, with a tolerance for the timestamp against replay), compared in constant time; a request without a valid one is answered 401 and nothing of it is stored. The secret is a web credential's: encrypted withPGKILN_SECRET_KEY, write-only in the builder, never exported, never logged. An event id is processed once. The handler's block runs later, as the application's database role withmeta.app_user()nobody, so row level security applies as for a public handler: write it for an anonymous caller. Stored events (raw bodies) are readable only through the builder, by developers of the application's workspace. Treat the body as untrusted input even when signed: cast and check it, and never build SQL from it. - Callbacks of web requests (chapter 9). The callback is named when the request is queued and must be a function
(bigint)the application's role may execute; it runs as that role, with the user who queued the request asmeta.app_user().
Neither ever runs as pgkiln's owner, a superuser or a role that bypasses row level security: such an event or callback fails instead. Every attempt of a queued web request, also a retry hours later, goes through the host allow-list, the workspace's network access list and the private address checks again.
Session state protection
- URL items: on pages with protection Arguments must have checksum (the default), item values in a URL are accepted only with a valid checksum. It's an HMAC bound to the application, page and user, so a link can't be edited (
?P3_EMPNO=7839→7902) and one user's links don't work for another. Build links in SQL withmeta.page_url(3, '{"P3_EMPNO": 7839}'). - Submitted values: only editable, visible items are taken from a submit. Hidden, display-only, read-only and unauthorized items keep their server-side values. (167) A hidden item with
{"value_protected": false}is the exception the developer chooses: a hidden input whose posted value is user input, like a text field's. - Grid defaults: a new grid row posts the default values it started with (
_def), only to tell an untouched row from a filled-in one; it never sets a column. - Grid rows: every row's primary key is signed the same way.
- Master-detail selection: a master grid's select links carry a signature bound to the application, page, user, region and value; only then does the value go into the item (protected hidden items are never taken from a submit, and URL items need the page checksum). The detail endpoint
GET …/region/:idserves only lazy regions and details of a visible master, after the page's and region's authorization and conditions. A detail grid's master column is filled from the session item on insert and can't be edited. - Grid layouts and saved grid reports: the layout endpoints (
POST …/grid/:id/layout,…/layout/reset,…/saved/:sid/apply) check the CSRF token, page access and that the grid is on the page and visible to the user. The layout is cleaned on the server (known shapes only, widths numbers between 40 and 1000, at most 5 frozen columns, at most 6000 characters) and only ever reorders columns the query returns anyway. In the database,meta.save_grid_layout/meta.reset_grid_layout(security definer) only touch the signed-in user's own row of a grid of the current application; layout rows are never visible to other users, even if marked public. Applying a saved report works for the user's own and public reports of that grid only. - Calendar drag and drop: the browser only names an event (its key) and a slot. The server checks the token, the page's and region's authorization and condition and the region's
move_authz, and that the event is in the region's query for this user (as the application's database role, with RLS), validates the slot as a date, and passes the new start and end to themoveSQL as literals. Your function still decides who may move what (e.g. only the organizer). - Chart and calendar links (drill-down, create on click) are checksummed like report links.
- CSRF: every POST carries a per-session token.
Expire bookmarks (sprint 189; APEX: Session State Protection → Expire Bookmarks): Settings → Errors and sessions → Expire bookmarks raises the application's url_epoch, which is part of every checksum the application makes (meta.url_checksum and the server use it alike). Every checksummed link made before stops working: bookmarks, links in e-mails, notifications and push messages. A user who opens one sees This link has expired instead of the checksum error that a tampered link gets. Pages open in a browser at that moment need to be opened again, because their grid rows and selections are signed too. The settings page shows when it was last done, and the activity log records who did it (expire_bookmarks).
Checksums prevent tampering but aren't a substitute for RLS. A user who legitimately received a link for record 7839 can open it. Whether they may see record 7839 at all is the database's decision.
Browser security
(sprint 188) Like APEX's Security Attributes → Browser Security, Settings → Security → Browser security chooses what browsers may do with an application's pages. It applies to every response under /a/<alias>/; the builder and the rest of the server keep pgkiln's defaults. The values are stored in meta.app.browser_security (migration 168) and travel with the application's export.
| Setting | Choices | Sent as |
|---|---|---|
| Embed in frames | Only pages of this server (default), Never, This server and the origins below | CSP frame-ancestors 'self' + X-Frame-Options: SAMEORIGIN; 'none' + DENY; 'self' https://portal.example.com … without X-Frame-Options (it can't list origins) |
| Origins that may embed the application | up to 10 https origins (https://host or https://host:port, no path, no wildcard) | in frame-ancestors |
| Referrer policy | same-origin (default), strict-origin-when-cross-origin, strict-origin, no-referrer | Referrer-Policy |
| Search engines | Automatic (default: not indexed when the application needs a sign-in), May index, Never index | X-Robots-Tag: noindex, nofollow |
| Extra response headers | up to 20 lines Name: value | as given |
What can't be weakened per application: pages always carry pgkiln's Content-Security-Policy (only frame-ancestors changes), nosniff, the Permissions-Policy and Cache-Control: no-store (a page holds the session's CSRF token). Its img-src grows only with what the page renders: the https origins of display image items and of the pictures of template components and report column templates (sprint 235; at most 50 per page, never a wildcard; see pictures from other sites). Extra headers may not be one pgkiln sets for security or one the protocol needs (Content-Security-Policy, X-Frame-Options, Referrer-Policy, X-Robots-Tag, Set-Cookie, Cache-Control, Strict-Transport-Security, Access-Control-*, Cross-Origin-*, Content-Type, Location …), and a value has no line breaks. unsafe-url isn't offered as a referrer policy, since it would send the page's address, with its checksummed item values, to other sites.
The policy's script-src is 'self'. (sprint 239) A page that shows a text item with a Scan button adds 'wasm-unsafe-eval', so the bundled barcode decoder (WebAssembly, served by pgkiln) can run where the browser has no BarcodeDetector (chapter 17); it allows compiling WebAssembly, not eval(), and no other page gets it.
The form refuses such values. A value that reaches the database another way (an import, a hand edit) is left out when the pages are sent, with the default in its place, and the Advisor warns about it. The Settings → Security checklist lists the headers the application's pages send.
Embedding and sign-in: session cookies are SameSite=Lax, which browsers send to a frame only when the portal and pgkiln are the same site (e.g. portal.example.com framing apps.example.com). A portal on another site can embed public pages; pages that need a sign-in show the sign-in page there and the session never reaches the frame. Single sign-on providers usually refuse to be framed, too.
Checklist for a new application
- A dedicated
db_rolewith minimal grants (required since sprint 186; never a superuser or a role withBYPASSRLS). - RLS on tables where rows belong to users or teams.
- Authorization schemes on pages and buttons that change data.
- Checksum protection on pages (the default).
- Business rules in constraints, triggers or functions, not only in validations.
- Debug mode and debug messages off.
- Two-factor sign-in required at least for administrators (the Advisor checks it).
- Browser security: embedding only where a portal needs it.
- Review the app's Settings → Security checklist and Activity monitor now and then. (sprint 198) On a window of 1280 px or wider the checklist stays in view beside the Security and Sign-in tabs, under jump links to their sections (Authentication, Browser security; Sign-in methods, Two-factor sign-in) and to Session management and Expire bookmarks on Errors and Sessions.