AppDBDocsOpen console

Documentation DBL guide

Identity and permissions

Decide who can call an operation, issue scoped sessions for customers and guests, and forward a user’s identity from a trusted service.

Choose the caller

Use a named database user for a backend, a registered app user for a signed-in customer, and a guest for a short-lived visitor. All three belong to a specific database. A console account manages infrastructure through its organization memberships. Signing up for the console gives that account no application role in a tenant database.

Database user
Create one on the database’s detail page in the console. Keep its generated db.<username>.<password> credential on the server. A database user can hold operational permissions such as issuing tokens or publishing schemas.
Registered app user
Your application verifies the person’s login and maps it to a stable numeric subject inside this database. Grant a role to that subject, then issue a signed token. Keep account attributes and login records in your application’s tables or identity provider.
Guest
Have a trusted service issue a guest token. Each issuance creates a fresh session identity, with no registered user or grant row. Presenting the same token preserves the guest identity across calls.

Protect an operation

This example gives readers access to shared note titles and visitors access to a greeting. A permission names an action, a role groups permissions, and a decorator states what a function requires. The DBL blocks in this chapter form one notes.dbl file. Start with these declarations.

DBL · notes.dbl
namespace notes;

permissions(read_notes)
role reader(db::read, read_notes)
role visitor()
role registrar(db::write, db::manage_app_roles, db::mint_app_tokens, db::mint_guest_tokens)

table Note {
    id: UInt8,
    title: Text,
    primary key(id),
}

@requires_permissions(read_notes)
export fn title(id: UInt8) -> Text {
    return Note.require(id).title;
}

Calling title requires both db::read for the table lookup and notes::read_notes for the decorator. A role with db::write already includes general read access. Every permission in a decorator is required. A function that calls a protected helper must also declare its action permissions, which the DBL compiler checks.

Here any authorized reader can look up any note ID. For private notes, store the owner with the note and check it against auth::subject() inside each operation that exposes or changes it. A client-supplied owner ID alone cannot establish ownership.

visitor() grants no permissions. Its members can still call an exported greeting that only inspects their own identity. The registrar role belongs to a trusted backend. It can write data, manage app-role grants and issue both kinds of token. Split those capabilities among separate roles if different services own them.

Built-in permissions

db::read and db::write
Read or mutate application data. Either user kind can receive data and custom action permissions.
db::read_jobs
Inspect background jobs and their retained progress or history.
db::read_schema and db::write_schema
Inspect schema, exported operations and settings, or publish schema changes and run mutating maintenance.
db::manage_app_roles and db::act_as_user
Manage registered users’ role memberships or select a registered user by ID when invoking a function.
db::mint_app_tokens and db::mint_guest_tokens
Issue registered or guest credentials, respectively. App users cannot acquire operational authority through an app-role grant.

Grant and revoke roles

After deploying the package, create a database user named notes-api for the trusted service. From a shell with the database’s full root credential supplied as APPDB_TOKEN, list deployed versions. Use your database’s actual HTTPS origin.

Terminal · find the current version
export APPDB_URL=https://field-notes-lab.db.appdb.cloud
appdb admin "$APPDB_URL" versions

Set APPDB_VERSION to the exact current version printed by the command. Grant the backend its database-user role. The app-user example uses 42 as the stable subject your application assigned to one customer.

Terminal · grant roles and inspect membership
appdb admin "$APPDB_URL" grant-role database notes-api "$APPDB_VERSION" notes::registrar
appdb admin "$APPDB_URL" grant-role app 42 "$APPDB_VERSION" notes::reader
appdb admin "$APPDB_URL" list-roles app 42

Root manages database-user grants. A database user with db::manage_app_roles can manage registered app users’ grants. The first grant creates the subject’s membership record. Repeating a grant or revoke is safe. Root also needs explicit grants for custom application permissions.

Terminal · revoke a reader
appdb admin "$APPDB_URL" revoke-role app 42 "$APPDB_VERSION" notes::reader

To grant a membership while creating an account, add the following function to the package. A trusted backend calls it after authenticating and identifying the account. A registration function can stage this grant and issue a token in the same transaction. The signed result is released after commit. The admin CLI handles revocation.

DBL · notes.dbl
@requires_permissions(db::manage_app_roles)
export write fn grant_reader(id: UInt8) -> () {
    auth::grant_app_role(id, "notes::reader");
}

Issue a member or guest token

Choose the role and claims type in the DBL return type. The service supplies claims and, for registered users, the subject it authenticated. Keep the issuer’s database credential on the server. Give the resulting scoped token to the application client.

DBL · notes.dbl
export struct SessionClaims {
    display_name: Text,
}
DBL · notes.dbl
@requires_permissions(db::mint_app_tokens)
export fn member_token(name: Text, id: UInt8) -> AuthToken<SessionClaims, reader> {
    return auth::issue_token(SessionClaims {
        display_name: name,
    }, 3600, id);
}

member_token returns a reader credential valid for one hour. The target must already hold notes::reader. If you ran the revoke example, grant the role again before issuing. AppDB checks that exact grant again when the token is used, even if the user holds several roles.

DBL · notes.dbl
@requires_permissions(db::mint_guest_tokens)
export fn guest_token(name: Text) -> AuthToken<SessionClaims, visitor> {
    return auth::issue_token(SessionClaims {
        display_name: name,
    }, 300);
}

guest_token returns a five-minute visitor credential. Its two-argument call creates a new guest every time, even when two visitors supply the same display name. A guest token can authenticate directly to the database.

Set a lifetime and cap a child token

The lifetime is a positive number of seconds. The registered-user form also accepts an absolute expiry in Unix seconds. The token expires at the earlier of that ceiling and the issue time plus the requested lifetime. Choose a ceiling in the future so the credential can be used. Both arguments use UInt8, DBL’s unsigned eight-byte integer.

DBL · notes.dbl
@requires_permissions(db::mint_app_tokens)
export fn browser_token(name: Text, id: UInt8, expires: UInt8) -> AuthToken<SessionClaims, reader> {
    return auth::issue_token(SessionClaims {
        display_name: name,
    }, 300, id, expires);
}

To derive a browser token from a signed-in session, first read auth::session_expires() and the subject in a call authenticated with that session. Give those verified values to the trusted issuer. A call with only a database password has no bearer expiry to read. The AppDB console uses this pattern for a one-hour login and a five-minute browser token capped at the login’s expiry. Tenant applications choose their own lifetimes in DBL.

A credential expires at its signed timestamp. To continue a session, authenticate through the application again or use a still-valid verified login to request a fresh credential under your policy.

Read claims and identify the subject

DBL · notes.dbl
export fn greeting() -> Text {
    match auth::claims<SessionClaims>() {
        null => { return "Hello"; },
        some(visitor) => { return visitor.display_name; },
    }
}

auth::claims<SessionClaims>() returns the signed fields when the token carries this exact claims type. A different claims type or a call with no claims yields null. The database checks the qualified type name and a fingerprint of its definition. A package with an incompatible definition cannot bind the token.

auth::subject() distinguishes DatabaseUser (username), AppUser (durable user ID) and GuestUser (a 16-byte session ID). A display name is suitable for a greeting. Derive account ownership from the verified subject, and verify any email or other claim you intend to trust before issuing it.

Call directly or forward the bearer

A browser uses the generated client for its role and sends the token as its bearer credential. Generate the browser module with dbl generate --lang web-js --role notes::reader --out generated notes.dbl. Use the exact deployed version and provide the scoped token your backend issued after login.

JavaScript · browser client
import { Client } from "./generated/client.mjs";

const reader = new Client({
    url: "https://field-notes-lab.db.appdb.cloud",
    version: deployedVersion,
    token: userToken,
});
const title = await reader.notes_title(7n);

Server-rendered pages can forward that same registered user’s token while the backend connects using its own database credential. In the generated Rust client for the package above, service is connected as the backend. Pass the credential from the authenticated web request to as_token.

Rust · execute one call as the reader
let title = service.as_token(user_token).notes_title(note_id).await?;

Compute retains the backend as the actor and executes the call with the app user’s identity, claims and current permissions under the token’s role. Forwarding requires the valid registered-user bearer and an authenticated database user. No additional impersonation grant or token exchange is needed.

AppDB-As-Token
Forward the complete signed registered-user token. Its original expiry and role still apply. A guest uses its own bearer directly.
AppDB-As-User
Select a registered user by ID. The database user needs db::act_as_user. The call uses the selected user’s current grants. Typed claims return null.
AppDB-Role
Narrow a call to a named role while preserving the actor’s subject and claims. A single role held by the actor must cover the entire requested role.

These are per-invocation selectors. Supply at most one. With none, AppDB uses the authenticated actor directly. Administrative operations use the original database actor.

Understand revocation

AppDB produces an opaque appdb1. bearer protected by the target database’s HMAC-SHA-256 key. The signed payload binds the database, subject, role, expiry, and typed claims. Claims can be read by the bearer, so keep secrets out of them. The entire encoded credential must fit in 4,096 bytes.

Revoke one member
Revoke the exact role that issued their token. New calls and retries using that grant fail, including over existing connections. An attempt admitted before revocation can finish.
Reduce authority for a role
Changing a role’s permissions changes what holders can do on subsequent calls. Dropping and recreating the role under the same spelling creates a new identity. Old grants and tokens cannot authorize the replacement.
Expire a guest
Guest sessions have no per-user grant to revoke. Use short lifetimes when individual sign-out must bound exposure. Changes to the guest role affect all its holders.
Invalidate signed sessions database-wide
Rotate the database signing key to invalidate tokens signed using the old key, including guest tokens. Resetting a named database user’s password changes that database user’s login credential.

All callable schema versions use current role definitions. Each version keeps its own functions and decorators. When tightening an operation’s requirements, retire older versions that still expose the previous operation.