# Create consent by email Source: https://docs.databunker.org/oss/api/consent/create-consent-by-email /oss/api/openapi.yml post /v1/consent/email/{email}/{brief} Stores consent for a user identified by email # Create consent by login Source: https://docs.databunker.org/oss/api/consent/create-consent-by-login /oss/api/openapi.yml post /v1/consent/login/{login}/{brief} Stores consent for a user identified by login # Create consent by phone Source: https://docs.databunker.org/oss/api/consent/create-consent-by-phone /oss/api/openapi.yml post /v1/consent/phone/{phone}/{brief} Stores consent for a user identified by phone # Create consent by user token Source: https://docs.databunker.org/oss/api/consent/create-consent-by-user-token /oss/api/openapi.yml post /v1/consent/token/{token}/{brief} Stores user consent. The `brief` parameter is a unique consent identifier per user. Allowed characters: [a-z0-9-], max 64 characters. # Get consent by email Source: https://docs.databunker.org/oss/api/consent/get-consent-by-email /oss/api/openapi.yml get /v1/consent/email/{email}/{brief} Retrieves consent record for a user identified by email # Get consent by login Source: https://docs.databunker.org/oss/api/consent/get-consent-by-login /oss/api/openapi.yml get /v1/consent/login/{login}/{brief} Retrieves consent record for a user identified by login # Get consent by phone Source: https://docs.databunker.org/oss/api/consent/get-consent-by-phone /oss/api/openapi.yml get /v1/consent/phone/{phone}/{brief} Retrieves consent record for a user identified by phone # Get consent by user token Source: https://docs.databunker.org/oss/api/consent/get-consent-by-user-token /oss/api/openapi.yml get /v1/consent/token/{token}/{brief} Retrieves consent record for a user # List all consents by email Source: https://docs.databunker.org/oss/api/consent/list-all-consents-by-email /oss/api/openapi.yml get /v1/consent/email/{email} Returns all consent records for a user identified by email # List all consents by login Source: https://docs.databunker.org/oss/api/consent/list-all-consents-by-login /oss/api/openapi.yml get /v1/consent/login/{login} Returns all consent records for a user identified by login # List all consents by phone Source: https://docs.databunker.org/oss/api/consent/list-all-consents-by-phone /oss/api/openapi.yml get /v1/consent/phone/{phone} Returns all consent records for a user identified by phone # List all consents by user token Source: https://docs.databunker.org/oss/api/consent/list-all-consents-by-user-token /oss/api/openapi.yml get /v1/consent/token/{token} Returns all consent records for a user # Withdraw consent by email Source: https://docs.databunker.org/oss/api/consent/withdraw-consent-by-email /oss/api/openapi.yml delete /v1/consent/email/{email}/{brief} Withdraws consent for a user identified by email # Withdraw consent by login Source: https://docs.databunker.org/oss/api/consent/withdraw-consent-by-login /oss/api/openapi.yml delete /v1/consent/login/{login}/{brief} Withdraws consent for a user identified by login # Withdraw consent by phone Source: https://docs.databunker.org/oss/api/consent/withdraw-consent-by-phone /oss/api/openapi.yml delete /v1/consent/phone/{phone}/{brief} Withdraws consent for a user identified by phone # Withdraw consent by user token Source: https://docs.databunker.org/oss/api/consent/withdraw-consent-by-user-token /oss/api/openapi.yml delete /v1/consent/token/{token}/{brief} Withdraws user consent (GDPR compliance) # Cancel user expiration Source: https://docs.databunker.org/oss/api/expiration/cancel-user-expiration /oss/api/openapi.yml post /v1/exp/cancel/{token} Cancels user account expiration. Requires admin or user token. # Delete expired user data Source: https://docs.databunker.org/oss/api/expiration/delete-expired-user-data /oss/api/openapi.yml get /v1/exp/delete/{exptoken} Confirms deletion of expired user data. This link works in the browser without authentication. # Get expiration status Source: https://docs.databunker.org/oss/api/expiration/get-expiration-status /oss/api/openapi.yml get /v1/exp/status/{token} Retrieves user expiration status. Requires admin or user token. # Retain user data Source: https://docs.databunker.org/oss/api/expiration/retain-user-data /oss/api/openapi.yml get /v1/exp/retain/{exptoken} Cancels expiration and retains user data. This link works in the browser without authentication. # Start user expiration flow Source: https://docs.databunker.org/oss/api/expiration/start-user-expiration-flow /oss/api/openapi.yml post /v1/exp/start/{token} Triggers the user expiration flow for data minimization compliance. Returns an expiration token that can be used to create retention/deletion links. # API Overview Source: https://docs.databunker.org/oss/api/overview Databunker is a super-fast, open-source vault built with Go for secure storage of sensitive personal records. ## Authentication All API requests require authentication using the `X-Bunker-Token` header. This token is your root access token. ## Content Types The API supports the following content types for POST and PUT requests: * `application/json` * `application/x-www-form-urlencoded` ## User Tokens Keep the user `{token}` generated by Databunker private, as it serves as an additional user identifier. Under GDPR, this user token is referred to as a pseudonymized identity. For more details, visit: [https://databunker.org/](https://databunker.org/) # Create session by email Source: https://docs.databunker.org/oss/api/session/create-session-by-email /oss/api/openapi.yml post /v1/session/email/{email} Creates a new session for a user identified by email # Create session by login Source: https://docs.databunker.org/oss/api/session/create-session-by-login /oss/api/openapi.yml post /v1/session/login/{login} Creates a new session for a user identified by login # Create session by phone Source: https://docs.databunker.org/oss/api/session/create-session-by-phone /oss/api/openapi.yml post /v1/session/phone/{phone} Creates a new session for a user identified by phone # Create session by user token Source: https://docs.databunker.org/oss/api/session/create-session-by-user-token /oss/api/openapi.yml post /v1/session/token/{token} Creates a new user session and returns a session token. Sessions can have an expiration TTL specified in the request. # Delete session Source: https://docs.databunker.org/oss/api/session/delete-session /oss/api/openapi.yml delete /v1/session/session/{session} Deletes a session by session token # Get session data Source: https://docs.databunker.org/oss/api/session/get-session-data /oss/api/openapi.yml get /v1/session/session/{session} Retrieves session data by session token # List sessions by email Source: https://docs.databunker.org/oss/api/session/list-sessions-by-email /oss/api/openapi.yml get /v1/session/email/{email} Returns all session records for a user identified by email # List sessions by login Source: https://docs.databunker.org/oss/api/session/list-sessions-by-login /oss/api/openapi.yml get /v1/session/login/{login} Returns all session records for a user identified by login # List sessions by phone Source: https://docs.databunker.org/oss/api/session/list-sessions-by-phone /oss/api/openapi.yml get /v1/session/phone/{phone} Returns all session records for a user identified by phone # List sessions by user token Source: https://docs.databunker.org/oss/api/session/list-sessions-by-user-token /oss/api/openapi.yml get /v1/session/token/{token} Returns an array of all session records for a user # Backup database Source: https://docs.databunker.org/oss/api/system/backup-database /oss/api/openapi.yml get /v1/sys/backup Dumps the internal database in SQL format (SQLite only). Requires root token authentication. # Create or update user app record by email Source: https://docs.databunker.org/oss/api/user-app/create-or-update-user-app-record-by-email /oss/api/openapi.yml post /v1/userapp/email/{email}/{appname} Stores app-specific data for a user identified by email # Create or update user app record by login Source: https://docs.databunker.org/oss/api/user-app/create-or-update-user-app-record-by-login /oss/api/openapi.yml post /v1/userapp/login/{login}/{appname} Stores app-specific data for a user identified by login # Create or update user app record by phone Source: https://docs.databunker.org/oss/api/user-app/create-or-update-user-app-record-by-phone /oss/api/openapi.yml post /v1/userapp/phone/{phone}/{appname} Stores app-specific data for a user identified by phone # Create or update user app record by token Source: https://docs.databunker.org/oss/api/user-app/create-or-update-user-app-record-by-token /oss/api/openapi.yml post /v1/userapp/token/{token}/{appname} Stores additional information about a user for a specific application. This is useful for storing app-specific data (e.g., shipping info) separately from profile data. Submitting multiple times overwrites the previous value. # Delete user app record by email Source: https://docs.databunker.org/oss/api/user-app/delete-user-app-record-by-email /oss/api/openapi.yml delete /v1/userapp/email/{email}/{appname} Removes app-specific data for a user identified by email # Delete user app record by login Source: https://docs.databunker.org/oss/api/user-app/delete-user-app-record-by-login /oss/api/openapi.yml delete /v1/userapp/login/{login}/{appname} Removes app-specific data for a user identified by login # Delete user app record by phone Source: https://docs.databunker.org/oss/api/user-app/delete-user-app-record-by-phone /oss/api/openapi.yml delete /v1/userapp/phone/{phone}/{appname} Removes app-specific data for a user identified by phone # Delete user app record by token Source: https://docs.databunker.org/oss/api/user-app/delete-user-app-record-by-token /oss/api/openapi.yml delete /v1/userapp/token/{token}/{appname} Removes app-specific data for a user # Get user app record by email Source: https://docs.databunker.org/oss/api/user-app/get-user-app-record-by-email /oss/api/openapi.yml get /v1/userapp/email/{email}/{appname} Retrieves app-specific data for a user identified by email # Get user app record by login Source: https://docs.databunker.org/oss/api/user-app/get-user-app-record-by-login /oss/api/openapi.yml get /v1/userapp/login/{login}/{appname} Retrieves app-specific data for a user identified by login # Get user app record by phone Source: https://docs.databunker.org/oss/api/user-app/get-user-app-record-by-phone /oss/api/openapi.yml get /v1/userapp/phone/{phone}/{appname} Retrieves app-specific data for a user identified by phone # Get user app record by token Source: https://docs.databunker.org/oss/api/user-app/get-user-app-record-by-token /oss/api/openapi.yml get /v1/userapp/token/{token}/{appname} Retrieves app-specific data for a user # Create a new user record Source: https://docs.databunker.org/oss/api/user/create-a-new-user-record /oss/api/openapi.yml post /v1/user Creates a new encrypted user record. Databunker extracts `login`, `phone`, and `email` from the request and builds hashed indexes for lookup. These values must be unique across all users. # Delete user by email Source: https://docs.databunker.org/oss/api/user/delete-user-by-email /oss/api/openapi.yml delete /v1/user/email/{email} Removes all user records, fulfilling GDPR "right to be forgotten" # Delete user by login Source: https://docs.databunker.org/oss/api/user/delete-user-by-login /oss/api/openapi.yml delete /v1/user/login/{login} Removes all user records, fulfilling GDPR "right to be forgotten" # Delete user by phone Source: https://docs.databunker.org/oss/api/user/delete-user-by-phone /oss/api/openapi.yml delete /v1/user/phone/{phone} Removes all user records, fulfilling GDPR "right to be forgotten" # Delete user by token Source: https://docs.databunker.org/oss/api/user/delete-user-by-token /oss/api/openapi.yml delete /v1/user/token/{token} Removes all user records from the database, keeping only the user token for reference. This fulfills the GDPR "right to be forgotten" requirement. In the enterprise version, deletion can be delayed according to company policy. # Get user by email Source: https://docs.databunker.org/oss/api/user/get-user-by-email /oss/api/openapi.yml get /v1/user/email/{email} Retrieves a user record by email address # Get user by login Source: https://docs.databunker.org/oss/api/user/get-user-by-login /oss/api/openapi.yml get /v1/user/login/{login} Retrieves a user record by login name # Get user by phone Source: https://docs.databunker.org/oss/api/user/get-user-by-phone /oss/api/openapi.yml get /v1/user/phone/{phone} Retrieves a user record by phone number # Get user by token Source: https://docs.databunker.org/oss/api/user/get-user-by-token /oss/api/openapi.yml get /v1/user/token/{token} Retrieves a user record by their unique token # Update user by email Source: https://docs.databunker.org/oss/api/user/update-user-by-email /oss/api/openapi.yml put /v1/user/email/{email} Updates a user record identified by email address # Update user by login Source: https://docs.databunker.org/oss/api/user/update-user-by-login /oss/api/openapi.yml put /v1/user/login/{login} Updates a user record identified by login name # Update user by phone Source: https://docs.databunker.org/oss/api/user/update-user-by-phone /oss/api/openapi.yml put /v1/user/phone/{phone} Updates a user record identified by phone number # Update user by token Source: https://docs.databunker.org/oss/api/user/update-user-by-token /oss/api/openapi.yml put /v1/user/token/{token} Updates a user record. When using JSON, you can remove fields by setting their value to null. All changes are logged in the audit trail. # Architecture Source: https://docs.databunker.org/oss/get-started/architecture ![Databunker solution](https://mintcdn.com/databunker-a1572a73/M_EIV9cEsonY2OnW/oss/get-started/databunker-solution.png?fit=max\&auto=format\&n=M_EIV9cEsonY2OnW\&q=85\&s=2df08abfba555833c40d0353ff6a4bbb) **Databunker** is a **vault** for personal records with a twist. **Vault** products are well-known. For example Hashicorp Vault, or cloud-based tools like AWS Secret Manager or GCP Secret Manager. These tools store binary secret values in encrypted form. These secret values can be database passwords, user private keys, or API tokens. The **vault** knows to encrypt the secret value and store it and provide an API for easy access. Databunker has another use-case. It can be used to secretly store the whole user record. This record can include a user name, IP address, password, credit card, blockchain keys, healthcare information, etc... Databunker expects to receive the whole user record in JSON format. Databunker stores encrypted records in the back-end database. Out of the personal record, before encryption, Databunker knows to extract the user's email address, phone number, login value if present, and builds a search index. This search index is also hashed on the database level. So, if the attacker gains access to the Databunker back-end database, everything is encrypted or hashed including the search index. Your code must supply additional user records like first name, last name, user address when calling a Create User API call. These values should be encoded in HTML POST key/value format or JSON format. When a request is made to create a user record, Databunker performs the following operations: 1. Request sanity check and access token check 2. Normalize email address, phone number, login name 3. Optional strict user schema checks if schema is defined in configuration 4. Calculate secure hash values for email address, phone number, login name 5. Duplicate record validation using hashed values of email address, phone number, login name 6. Generate a new record UUID to be used as a user token 7. Encrypt the whole user json and save it in backend database (MySQL, PostgreSQL, SQLite) 8. Return newly generated user token to the caller After creating a new user record, Databunker returns to the caller a user token in UUID format. That token can be saved in existing database instead of storing personal records or PII/PHI. ![Databunker request flow](https://mintcdn.com/databunker-a1572a73/YRObguuJjdAz27bg/oss/get-started/databunker-request-flow.png?fit=max\&auto=format\&n=YRObguuJjdAz27bg\&q=85\&s=71ecc6d5cc8cd2548feb0055060a6876) Databunker provides you an API to lookup user records using the **email address**, **phone number**, **login name** or a **token** received when you create a user record. Databunker was built with privacy in mind and this is where the product really shines. It provides GDPR compliance, i.e. an audit of changes, handling for user requests like forget-me requests, user request change management, optional DPO approval, etc... From a technical perspective, the product has many additional features, like the expiration of records, shareable record identities; additional user records, etc... # Node.js examples Source: https://docs.databunker.org/oss/get-started/examples ## Examples 1. Passwordless Login with Databunker: [GitHub Repository](https://github.com/securitybunker/databunker-nodejs-passwordless-login) 2. Node.js Example with Passport.js, Magic.Link, and Databunker: [GitHub Repository](https://github.com/securitybunker/databunker-nodejs-example) 3. Secure Session Storage for Node.js Apps: [Detailed Guide](https://databunker.org/use-case/secure-session-storage/#databunker-support-for-nodejs) ## Node.JS modules 1. `@databunker/store` from [https://github.com/securitybunker/databunker-store](https://github.com/securitybunker/databunker-store) 2. `@databunker/session-store` from [https://github.com/securitybunker/databunker-session-store](https://github.com/securitybunker/databunker-session-store) # Databunker Source: https://docs.databunker.org/oss/get-started/overview Databunker is an open-source, Go-based tool for secure personal data tokenization and storage. It can be deployed using Docker Compose or a Kubernetes Helm chart and is designed to help developers protect sensitive data such as PII, PHI, and KYC with minimal effort. ### The Big Problem with Traditional Database Encryption Traditional database encryption solutions often provide a false sense of security. While they may encrypt data at rest, they leave critical vulnerabilities: * **Encryption alone isn’t enough:** Most vendors offer disk-block encryption, ignoring API-level encryption * **Vulnerable GraphQL Queries:** Unfiltered queries can expose unencrypted data to attackers * **SQL Injection Risks:** Attackers can retrieve plaintext data through SQL injections Databunker addresses these gaps with a secure, developer-focused solution for personal data tokenization and storage. ### Databunker Features * **Tokenization Engine**: Generates UUID tokens for safe data referencing in applications * **Encrypted Storage**: Secures sensitive records with advanced encryption layer * **Injection Protection**: Blocks SQL and GraphQL injection attacks by design * **Secure Indexing**: Uses hash-based indexing for search queries * **No Plaintext Storage**: Ensures all data is encrypted at rest * **Restricted Bulk Retrieval**: Disabled by default to prevent data leaks * **API-Based Access**: Integrates with your backend via a NoSQL-like API * **Fast Integration**: Set up secure data protection in under 10 minutes For **credit-card tokenization** or **enterprise security features** check out [Databunker Pro](/pro/get-started/overview). ### Why Databunker? Databunker provides a robust, open-source vault that eliminates the false sense of security from traditional encryption methods, offering developers a practical way to protect sensitive data. ### Deployment & Usage * **Self-Hosted**: Run on your cloud or on-premises infrastructure * **Open-Source**: Licensed under MIT for free commercial use * **GDPR Compliant**: Meets modern privacy regulation requirements * **High Performance**: Go-powered API ensures fast tokenization and data access ### How It Works 1. Store sensitive data in Databunker via API calls 2. Receive UUID tokens to reference data securely in your application 3. Query data using secure, hash-based indexing 4. Benefit from built-in protections against injections and bulk data leaks Get started with Databunker to secure your sensitive data efficiently. ![Pseudonymized identity](https://mintcdn.com/databunker-a1572a73/qL-_zKq-_GLjhX3S/pro/get-started/databunker-short-diagram.png?fit=max\&auto=format\&n=qL-_zKq-_GLjhX3S\&q=85\&s=a40c2a15b19cb6f2ed01d864ff238ee9) # Quickstart Source: https://docs.databunker.org/oss/get-started/quickstart ## Step 1: Starting the Databunker container The easiest way to start using Databunker is by running it as a Docker container. Once the container is running, Databunker opens port 3000 and listens for incoming requests. To launch Databunker with a `DEMO` root access key, ideal for local testing and development, use the following command: ```bash theme={null} docker run -p 3000:3000 -d --rm --name databunker securitybunker/databunker demo ``` For detailed installation instructions, please refer to the [full installation guide](/oss/installation/overview). ## Step 2: Creating a User Record Databunker's most popular API request is to store user records. For each new user record, Databunker generates and returns a **user token** in UUID format. GDPR Relevance: * Under **GDPR**, this **user token** is referred to as a **pseudonymized identity**. This token can be safely stored in your regular database or logs, as long as **no** additional personal information is stored with it. * **Pseudonymization** reduces the risk of directly associating personal data with an individual, reinforcing data protection and privacy principles. * For instance, when you receive a **Right to be forgotten (RTBF) request**, you can remove the personal data from Databunker without affecting other systems. Use this command to create the user record: ```bash theme={null} curl -s http://localhost:3000/v1/user \ -X POST -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d '{"first":"John","last":"Doe","login":"john","phone":"4444","email":"user@gmail.com"}' ``` Output: ```json theme={null} { "status": "ok", "token": "eeb04dd7-ecb2-c957-2875-5b98897b21a6" } ``` ## Step 3: Retrieving user record You can retrieve user records using indexed fields, such as **email address**, **login name**, **user token**, or **custom index**. To fetch customer records by user token, use this command: ```bash theme={null} curl -s -H "X-Bunker-Token: DEMO" -X GET http://localhost:3000/v1/user/token/eeb04dd7-ecb2-c957-2875-5b98897b21a6 ``` You can integrate Databunker into your application's sign-in logic and search for customer records using an email address or login name: ```bash theme={null} curl -s -H "X-Bunker-Token: DEMO" -X GET http://localhost:3000/v1/user/email/user@gmail.com curl -s -H "X-Bunker-Token: DEMO" -X GET http://localhost:3000/v1/user/login/john ``` ## Full lists of API requests: For a full list of available requests, please check the [API Reference](/oss/api/overview). ## Step 4: Accessing the Web UI Databunker includes a built-in web UI. For quick access, we’ve pre-installed Databunker, which you can access at: [demo.databunker.org](https://demo.databunker.org/). Use the `DEMO` root token to access the admin panel. If you deploy Databunker using Docker, this interface is available by default at: [localhost:3000](http://localhost:3000/). In the demo version, the root token is set to `DEMO` by default. The **admin** or **Data Protection Officer (DPO)** can use the web interface to: 1. Delete user records to comply with GDPR RTBF "forget me" requests 2. Generate personal data reports and review audit logs 3. Manage personal data processing activities #### End-User Access: Databunker's optional customer portal lets users securely access, manage, and update their personal data, supporting GDPR compliance. Key features include secure login, data review, and audit log access. If you created a sample user with the phone number `4444`, as shown in the **Creating a User Record** section, you can use `4444` as both the phone number and password to access the customer portal. ## Step 5: View Node.js code examples 1. Passwordless Login with Databunker: [GitHub Repository](https://github.com/securitybunker/databunker-nodejs-passwordless-login) 2. Node.js Example with Passport.js, Magic.Link, and Databunker: [GitHub Repository](https://github.com/securitybunker/databunker-nodejs-example) 3. Secure Session Storage for Node.js Apps: [Detailed Guide](https://databunker.org/use-case/secure-session-storage/#databunker-support-for-nodejs) #### Node.js modules 1. `@databunker/store` from [https://github.com/securitybunker/databunker-store](https://github.com/securitybunker/databunker-store) 2. `@databunker/session-store` from [https://github.com/securitybunker/databunker-session-store](https://github.com/securitybunker/databunker-session-store) # Detailed installation guide Source: https://docs.databunker.org/oss/installation/overview ## Method 1: Quick installation * The easiest way to start using Databunker is to deploy it as a standard Docker container with minimal parameters. * In this setup, it uses an internal **SQLite database** to store encrypted records. * You can use `DEMO` as a root token when making [API requests](/oss/api/overview) **Disadvantages:** * Utilizes a local SQLite database for storing encrypted records * Lack of security; using `DEMO` as a root access token * Not recommended for production use **Run the following commands to start Databunker:** ```bash theme={null} DATABUNKER_MASTERKEY=`< /dev/urandom LC_CTYPE=C tr -dc 'a-f0-9' | head -c${1:-48};` echo "DATABUNKER_MASTERKEY value is $DATABUNKER_MASTERKEY" docker run -p 3000:3000 -d -e DATABUNKER_MASTERKEY=$DATABUNKER_MASTERKEY --name databunker securitybunker/databunker demo ``` The first command generates the encryption key for Databunker's internal database. Be sure to save it for future use. Open your browser and navigate to [[http://localhost:3000/](http://localhost:3000/)](http://localhost:3000/) to access the product's user interface. `Note:` * If the **databunker** container stops, you can restart the service by running `docker start databunker`. * For production environments, we recommend using a MySQL or PostgreSQL backend instead. ## Method 2: Start Databunker and backend db with docker compose We prepared a number of scripts and configuration files you can use with Docker Compose. All these files are available in the project's [github repository](https://github.com/securitybunker/databunker#readme). Before starting Docker Compose, you need to generate several secret variables used by the containers. These variables include: * Passwords for MySQL or PostgreSQL databases * A self-signed SSL certificate * Databunker root token, and more For instance, the **DATABUNKER\_ROOTTOKEN** variable will be stored in the `.env/databunker-root.env` file. This value is used as the root token when making Databunker API requests. The required secret files will be saved in the `.env` directory. Use one of the following scripts from the project's GitHub repository to generate configuration secrets: * ./generate-mysql-env-files.sh * ./generate-mysql-demo-env-files.sh * ./generate-pgsql-env-files.sh * ./generate-pgsql-demo-env-files.sh After generating the secrets, you can start Databunker with MySQL using: ```bash theme={null} docker-compose -f docker-compose-mysql.yml up -d ``` Or, start Databunker with PostgreSQL using: ```bash theme={null} docker-compose -f docker-compose-pgsql.yml up -d ``` Once started, you can access Databunker by opening your browser and navigating to [[http://localhost:3000/](http://localhost:3000/)](http://localhost:3000/). ## Method 3: Automatic deployment in AWS cloud We have built Terraform configuration files and Helm charts to deploy Databunker with all required components in AWS. Detailed instructions can be found here: * [https://github.com/securitybunker/databunker/tree/master/terraform/aws](https://github.com/securitybunker/databunker/tree/master/terraform/aws) * [https://github.com/securitybunker/databunker/tree/master/charts/databunker](https://github.com/securitybunker/databunker/tree/master/charts/databunker) ## Method 4: Step-by-step production installation **Start with backend database** For production installation, you can use **MySQL** or **PostgreSQL** backend databases. This databse will be used to store encrypted user records. For example, you can spin MySQL or PostgreSQL as a container or use a cloud RDS version provided by Google Cloud and AWS, etc... For example, use the following command to start MySQL server. It will create a `databunkerdb` database for Databunker and create `bunkeruser` for Databunker access to MySQL. ```bash theme={null} mkdir ~/data chmod 0777 ~/data docker run --restart unless-stopped \ -v ~/data:/var/lib/mysql \ -e MYSQL_ROOT_PASSWORD=SuperAdmin4 \ -e MYSQL_DATABASE=databunkerdb \ -e MYSQL_USER=bunkeruser \ -e MYSQL_PASSWORD=BunkerUserPassword4 \ --name=mysqlsrv -d mysql/mysql-server ``` `Note:` make sure to change the passwords above. **First Databunker initialization step** Before Databunker can serve user requests it needs to create all tables; generate a master encryption key if not provided; generate root access token if not provided. This process is called **Databunker initialization**. You will need to do it just for the first time. Run the following command to initialize Databunker: ```bash theme={null} docker run --rm -it --link mysqlsrv \ -e MYSQL_HOST=mysqlsrv \ -e MYSQL_PORT=3306 \ -e MYSQL_USER_NAME=bunkeruser \ -e MYSQL_USER_PASS=BunkerUserPassword4 \ --entrypoint /bin/sh \ --name dbunker securitybunker/databunker \ -c '/databunker/bin/databunker -init -db databunkerdb -conf /databunker/conf/databunker.yaml' ``` In the command output, you will see the `Master key` and `API Root token` values. **Start the Databunker service** After extracting `DATABUNKER_MASTERKEY` you can start the Databunker service using the following command: ```bash theme={null} docker run --restart unless-stopped -d -p 3000:3000 \ --link mysqlsrv -e MYSQL_HOST=mysqlsrv \ -e DATABUNKER_MASTERKEY=8c9e892a1732881e14960f2b0437a720ad01ae47cd23baa7 \ -e MYSQL_PORT=3306 \ -e MYSQL_USER_NAME=bunkeruser \ -e MYSQL_USER_PASS=BunkerUserPassword4 \ --entrypoint /bin/sh \ --name dbunker securitybunker/databunker \ -c '/databunker/bin/databunker -start -db databunkerdb -conf /databunker/conf/databunker.yaml' ``` ## Advanced configuration Databunker uses the `databunker.yaml` configuration file. You can modify this file to set custom email gateway, SMS gateway, service logo, and more. There are several ways to load a new configuration file in Databunker: * Build a new Docker container based on Databunker's Dockerfile and include your custom configuration file inside it * Create a new configuration file and mount it to the Databunker container Follow these steps to mount an external configuration file: **Step 1. Download the default configuration file** Create a `./conf` directory and download the default configuration file in it: ```bash theme={null} mkdir ~/conf curl https://raw.githubusercontent.com/securitybunker/databunker/master/databunker.yaml \ -o ~/conf/databunker.yaml ``` **Step 2: Modify the Configuration File** Edit the configuration file with your changes: **\~/conf/databunker.yaml** **Step 3: Start the Databunker Container** Use the following command to start the Databunker container with the custom configuration: ```bash theme={null} docker run --restart unless-stopped -d -p 3000:3000 -v ~/conf:/databunker/conf \ --link mysqlsrv -e MYSQL_HOST=mysqlsrv \ -e DATABUNKER_MASTERKEY=8c9e892a1732881e14960f2b0437a720ad01ae47cd23baa7 \ -e MYSQL_PORT=3306 \ -e MYSQL_USER_NAME=bunkeruser \ -e MYSQL_USER_PASS=BunkerUserPassword4 \ --entrypoint /bin/sh \ --name dbunker securitybunker/databunker \ -c '/databunker/bin/databunker -start -db databunkerdb -conf /databunker/conf/databunker.yaml' ``` This command starts Databunker with the custom configuration file located in the \~/conf directory. ## SSL certificates You can generate SSL certificates and place them in the `/databunker/certs` directory in the running container. Use the following command to generate self-signed certificate: ```bash theme={null} cd ~ mkdir -p certs cd certs openssl req -new -newkey rsa:4096 -days 365 -nodes -x509 \ -subj "/e=UK/ST=/L=London/O=Your-company Ltd./CN=databunker.your-company.com" \ -keyout server.key -out server.cer ``` Next, map `/databunker/certs` directory inside container to the **\~/certs/** directory as: ```bash theme={null} cd ~ docker run --restart unless-stopped -d -p 3000:3000 -v ~/conf:/databunker/conf -v ~/certs:/databunker/certs \ --link mysqlsrv -e MYSQL_HOST=mysqlsrv \ -e DATABUNKER_MASTERKEY=8c9e892a1732881e14960f2b0437a720ad01ae47cd23baa7 \ -e MYSQL_PORT=3306 \ -e MYSQL_USER_NAME=bunkeruser \ -e MYSQL_USER_PASS=BunkerUserPassword4 \ --entrypoint /bin/sh \ --name dbunker securitybunker/databunker \ -c '/databunker/bin/databunker -start -db databunkerdb -conf /databunker/conf/databunker.yaml' ``` **Use certificates generated by Letsencrypt** Copy Letsencrypt generated file **privkey.pem** to \~/certs/server.key Copy Letsencrypt generated file **fullchain.pem** file to \~/certs/server.cer ## Create a test record You can download and run a small test script that will create a user record, user app record, user consent, etc... ```bash theme={null} curl https://raw.githubusercontent.com/securitybunker/databunker/master/create-test-user.sh -o test.sh chmod 755 ./test.sh ./test.sh ``` ### Built-in web UI You can now open browser at [http://localhost:3000/](http://localhost:3000/) Use the following account details: Email: [test@securitybunker.io](mailto:test@securitybunker.io) Phone: 4444 Code: 4444 ## Next steps * [Quickstart](/oss/get-started/quickstart) — create and retrieve your first user record * [Online demo](https://demo.databunker.org/) — pre-installed Databunker, use the `DEMO` root token * [Code examples](/oss/get-started/examples) * [Architecture](/oss/get-started/architecture) * [Source code](https://github.com/securitybunker/databunker/) # Conditional Role-Based Access Control (CRBAC) Source: https://docs.databunker.org/pro/administration/access-control **Conditional Role-Based Access Control (CRBAC)** is an advanced access control system that extends traditional Role-Based Access Control (RBAC) by introducing dynamic conditions that determine access rights. For the credential types that policies govern (root, tenant, role, and user tokens), see the [Authentication reference](/pro/api/authentication). CRBAC is particularly useful for businesses that need to comply with various privacy laws, such as: 1. **DPDPA** (India's Digital Personal Data Protection Act) 2. **FERPA** (Family Educational Rights and Privacy Act in the USA), which governs student education records 3. **GDPR** (General Data Protection Regulation in the EU) With Databunker Pro, customers can easily implement solutions that align with these regulations, ensuring secure and compliant PII management. ## Key Features of CRBAC * **Hierarchical Access Control:** Supports parent-child relationships in data access, enabling fine-grained permissions. * **Context-Aware Policies:** Defines access based on specific attributes like user roles, organizational structures, and compliance requirements. * **Dynamic Consent Enforcement:** Incorporates consent management for accessing PII. * **Group-Based Roles:** Databunker supports groups of users, where each member within a group can have distinct roles. For instance, in an educational group, roles like **Teacher** and **Student** can be assigned, or in a family group, roles such as **Parent** and **Child**. * **Similar to AWS IAM Policies:** Uses a declarative approach to grant or deny access based on conditions. ## Policy Structure CRBAC policies resemble AWS IAM policies, defining **who** (principale) can perform **what** (actions) on **which** (resources) under **which conditions**. ### Example Policy: Parent-Child Relationship Enforcement In Databunker Pro, you can create a custom group for family members. Within this group, parents will have read and write access to their child's information. You can use the following policy to grant parents access to their child's PII and consent information. ```json theme={null} { "Effect": "Allow", "Principal": { "Role": "parent" }, "Action": [ "UserGet", "UserUpdate", "BulkListGroupUsers", "AgreementGet", "AgreementAccept", "AgreementCancel", "AgreementListUserAgreements" ], "Resource": [ "${target_group_members:role/child}.profile", "${target_group_members:role/child}.agreement" ], "Condition": { "StringEquals": { "${user_group_id}": "${target_group_id}" } } } ``` ### Example Policy: Teacher-Parent Access This policy will grant to a teacher entity access to the student's parent information. ```json theme={null} { "Effect": "Allow", "Principal": { "Role": "teacher" }, "Action": ["UserGet", "BulkListGroupUsers"], "Resource": [ "${target_group_members:role/parent}.profile.name", "${target_group_members:role/parent}.profile.phone" ], "Condition": { "ForAnyValue:ListIntersect": { "${user_group_members:role/student}": "${target_group_members:role/child}" } } } ``` ## Passing runtime context with `request_metadata` Most Databunker Pro API endpoints accept an optional **`request_metadata`** object on the request body. The caller (application code, an API gateway, or a tokenisation proxy) uses it to pass runtime context — values like the calling environment, the purpose of the request, the originating IP address, a ticket number — that the access-control engine can evaluate at policy time. CRBAC `Condition` blocks can reference `request_metadata` values directly, so the same policy can grant or deny access based on **why** and **where** the request is coming from, not just **who** is making it. This is purpose-of-use enforcement. ### Example: caller-supplied context ```bash theme={null} curl -X POST https://your-databunker-instance/v2/UserGet \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "mode": "email", "identity": "jane@example.com", "request_metadata": { "environment": "production", "purpose": "fraud-investigation", "caller_ip": "10.0.12.34", "ticket_id": "INC-44218" } }' ``` ### Example: policy that evaluates `request_metadata` This policy allows a `security-analyst` role to read full user records **only** when the request is tagged with `purpose: fraud-investigation` and originates from the production environment: ```json theme={null} { "Effect": "Allow", "Principal": { "Role": "security-analyst" }, "Action": ["UserGet"], "Resource": ["users.profile.*"], "Condition": { "StringEquals": { "${request_metadata:purpose}": "fraud-investigation", "${request_metadata:environment}": "production" } } } ``` A request from the same role without those metadata values — or with different ones — is denied. ### What to put in `request_metadata` `request_metadata` is free-form, so the keys are conventions you adopt for your deployment. Typical keys we see in production: | Key | Purpose | | - | - | | `environment` | `production` / `staging` / `dev` — scopes policies per environment. | | `purpose` | A business-domain purpose-of-use code (e.g., `fraud-investigation`). | | `caller_ip` | Client IP — useful for IP-range conditions. | | `ticket_id` | Linking the access to a ticket / case for accountability. | | `app_name` | Calling application — useful when multiple apps share a role. | Every value passed in `request_metadata` is recorded in the audit event for the request, so it doubles as accountability metadata even when no policy references it. ## Field-Level Masking in Responses When a policy grants access to a subset of a user's profile fields, Databunker Pro applies the policy at response time. The original record stays untouched in the vault; the API response is filtered for the calling principal. The masking strategy is **asymmetric by type** so that strongly-typed clients (TypeScript, Python type-hints, Java, generated SDKs) do not encounter silent type mismatches: * **String fields** that the caller is not authorized to read are replaced with the literal `"***"`. The field stays in the response so the client can detect that the field exists. * **All other types** (`number`, `boolean`, array, nested object) are **omitted from the response entirely** when masked. This avoids type-corruption bugs like `profile.age + 1` evaluating to `"***1"` because the engine had substituted a string for a number. ### Example Suppose a `sales` user has a policy allowing only `${target_group_members:role/lead}.profile.email`. A lead's stored profile is: ```json theme={null} { "login": "lead42", "name": "Jane Doe", "email": "jane@example.com", "phone": "+15551234567", "age": 34, "verified": true, "tags": ["enterprise", "warm"], "address": { "city": "Springfield", "zip": "99999" } } ``` Calling `UserGet` with the sales user's token returns: ```json theme={null} { "status": "ok", "profile": { "email": "jane@example.com", "login": "***", "name": "***", "phone": "***" } } ``` Notice: * `email` is visible because the policy granted it. * `login`, `name`, `phone` are strings — present in the response with value `"***"`. * `age` (number), `verified` (boolean), `tags` (array), `address` (object) are absent from the `profile` object entirely. ### TypeScript example ```typescript theme={null} interface UserResponse { status: string; profile: { email?: string; login?: string; name?: string; phone?: string; age?: number; verified?: boolean; tags?: string[]; address?: { city: string; zip: string }; }; } const r: UserResponse = await api.userGet({mode: "login", identity: "lead42"}); // Safe: optional fields handled with the `?` operator. if (r.profile.age !== undefined) { console.log("Age:", r.profile.age + 1); // never executes when age is masked } ``` ## How CRBAC differs from plain RBAC Static RBAC answers "which endpoints may this role call?". CRBAC additionally evaluates the request itself, so the same role can be allowed or refused depending on runtime context passed in `request_metadata`, and the response can be masked field by field rather than allowed or denied whole. That is what makes it usable for regulated data: a support agent can hold one role and still see different fields depending on which record they are looking at, without you minting a role per situation. ## Next steps * [Multi-tenancy](/pro/administration/multi-tenancy) — the database-level boundary policies operate inside * [Sub-accounts](/pro/concepts/sub-accounts) — choosing between tenants and groups * [Bulk export controls](/pro/concepts/select-security) — how policies gate bulk retrieval * [Authentication](/pro/api/authentication) — issuing the scoped tokens a policy applies to # Backup and recovery Source: https://docs.databunker.org/pro/administration/backup-and-recovery What to back up, how to restore, and how to export every record out of the vault — including the three artefacts a backup is useless without. A Databunker Pro backup is only complete if it covers **three** artefacts. Miss any one of them and the restore fails. | Artefact | Where it lives | Without it | | - | - | - | | **Database** | PostgreSQL, MySQL, or Oracle | No records, no indexes, no audit trail | | **Wrapping key** | Your secret manager, and the deployment config | The vault will not start, and the data cannot be decrypted | | **Licence key** | The `config` table, but keep a copy outside it | The restored vault runs in Trial mode until you re-apply it | > [!WARNING] > > A database backup on its own is worthless. Every record in it is encrypted with the master key, which is itself encrypted by the wrapping key — so a restore without the wrapping key produces a vault full of unreadable ciphertext. Back up both, and store them separately. ## What to back up **The database.** Use whatever your provider offers — automated RDS snapshots, Cloud SQL backups, or `pg_dump` on a schedule. Set retention to match your recovery objective. Everything is already encrypted at rest, so the backup carries no plaintext personal data. **The wrapping key.** It does not change unless you [rotate it](/pro/administration/key-rotation), so this is a one-time capture — but it must survive the loss of the environment that holds it. Keep it in a secret manager, and keep the [Shamir key shares](/pro/administration/shamir-keys) somewhere else entirely. **The licence key.** Recorded outside the database, so you can re-apply it during a restore without waiting on the portal. > [!NOTE] > > Redis holds only transient session state and does not need backing up. Sessions are lost on restore; users sign in again. ## Restoring **1. Restore the database** Restore the snapshot or dump into a database of the same engine. Databunker Pro does not need to be running. **2. Point a new instance at it, with the original wrapping key** Set `DATABUNKER_WRAPPINGKEY` to the same value the vault used before. The instance is stateless — nothing else carries over. ```sh theme={null} docker compose up -d ``` **3. Confirm decryption works** A successful start proves the wrapping key unwrapped the master key. Read a known record to prove the master key still decrypts the data: ```bash theme={null} curl -X POST http://localhost:3000/v2/UserGet \ -H "X-Bunker-Token: YOUR-ROOT-TOKEN" \ -H "Content-Type: application/json" \ -d '{"mode":"email","identity":"known@example.com"}' ``` **4. Re-apply the licence if needed** Check `SystemGetSystemStats` — if `licensemaxrecords` reads 1,000 you are in Trial mode. See [update the licence key](/pro/howtos/update-license). ## Recovery objectives Two numbers to decide before you need them: * **RPO — how much data you can afford to lose.** Set by backup frequency. Daily snapshots mean up to a day of records; continuous archiving or point-in-time recovery narrows it to minutes. * **RTO — how long a restore may take.** Dominated by database size, not by Databunker Pro. Restoring 585 GB (roughly 100 M records at \~5.7 KB each — see [storage footprint](/pro/get-started/performance#storage-footprint)) takes far longer than starting the application container. ## Test the restore An untested backup is an assumption. On a schedule, and ideally with someone who did not build the deployment: **1. Restore into a scratch environment** Use a [non-production licence key](/pro/get-started/licensing#non-production-environments) so the drill does not consume production record capacity. **2. Bring it up with the real wrapping key** This is the step that catches the most common failure — a wrapping key nobody can find. **3. Read records back and compare** Spot-check a handful against known values. **4. Record how long it took** That number is your real RTO. ## Exporting every record Databunker Pro [deliberately blocks bulk retrieval](/pro/concepts/select-security) so a stolen token cannot dump the vault. A legitimate full export therefore goes through a specific, audited path rather than a `SELECT *`. `BulkListAllUsers` pages through every record. It requires the `list_users` configuration flag, a main-tenant admin token, and a short-lived unlock UUID obtained immediately beforehand — and every call is written to the audit trail. ```python theme={null} import json, os from databunkerpro import DatabunkerproAPI PAGE = 1000 api = DatabunkerproAPI( os.environ["DATABUNKER_API_URL"], os.environ["DATABUNKER_API_TOKEN"], os.getenv("DATABUNKER_TENANT_NAME", ""), ) with open("vault-export.jsonl", "w") as out: offset, exported = 0, 0 while True: # The unlock UUID is short-lived, so take a fresh one for each page. unlock = api.bulk_list_unlock()["unlockuuid"] result = api.bulk_list_all_users(unlock, offset=offset, limit=PAGE) rows = result.get("rows") or [] if not rows: break for row in rows: out.write(json.dumps(row) + "\n") exported += len(rows) offset += PAGE print(f"exported {exported}/{result.get('total')}", flush=True) print(f"Done. {exported} records written to vault-export.jsonl") ``` > [!WARNING] > > The output is **decrypted personal data in plaintext** — the one artefact in this guide that is not protected by the vault. Write it to encrypted storage, restrict who can read it, and delete it when the migration or portability request it was created for is complete. Format-preserving tokens export separately via `BulkListTokens`, and audit events via `BulkListAllAuditEvents`. ## What is not recoverable Backups protect against losing the database. They do not protect against losing your keys. If the wrapping key is gone **and** fewer than three Shamir shares remain, the data cannot be decrypted — not by you, and not by Databunker. There is no escrow and no vendor copy of your keys, which is the same property that means a breach of our systems cannot expose your data. See [what is recoverable](/pro/administration/key-rotation#what-is-recoverable) for the full matrix. ## Next steps * [Wrapping key rotation](/pro/administration/key-rotation) — the recovery matrix and the rotation runbook * [Shamir key shares](/pro/administration/shamir-keys) — custody and the three-share threshold * [Production checklist](/pro/installation/production-checklist) — the go-live gate that includes these items # Wrapping key rotation Source: https://docs.databunker.org/pro/administration/key-rotation How to rotate the Databunker Pro wrapping key using three Shamir key shares, what to back up before restarting, and what is recoverable if a key is lost. Rotating the wrapping key replaces the key that protects the [master key](/pro/administration/master-key). The master key itself never changes and is never exposed, so **no stored data is re-encrypted** — rotation takes the same amount of time on a vault of 1,000 records as on one of 100 million. ## When to rotate * On a schedule — every 90 days or annually is typical, and several frameworks expect a defined interval. * When someone who had access to the wrapping key leaves, or the key may have been exposed. * As part of a compliance exercise, where you need to evidence that rotation works rather than that it is merely possible. > [!TIP] > > Rotate on a schedule you have actually rehearsed. The procedure below touches the credential your vault needs in order to boot, so the first time you run it should not be during an incident. ## Before you start * **Three of your five [Shamir key shares](/pro/administration/shamir-keys)**, hex-encoded, as issued at setup. * The **root access token** of the main tenant. Only the main-tenant administrator can rotate the wrapping key. * A **running, healthy instance**. Rotation is performed against a live vault — see [What is recoverable](#what-is-recoverable) if yours is already down. * Write access to wherever the wrapping key is configured: your secret manager and your deployment config. * A maintenance window. The vault keeps serving traffic during the API call, but it has to be restarted afterwards. ## Rotate the key **1. Call SystemGenerateWrappingKey** Send any three of the five shares. They are hex-encoded, and the API rejects anything else. ```bash theme={null} curl -X POST http://localhost:3000/v2/SystemGenerateWrappingKey \ -H "X-Bunker-Token: YOUR-ROOT-TOKEN" \ -H "Content-Type: application/json" \ -d '{ "key1": "SHARE-1-HEX", "key2": "SHARE-2-HEX", "key3": "SHARE-3-HEX" }' ``` Databunker Pro reconstructs the recovery key from the shares, uses it to recover the master key, and confirms the result matches the master key the running instance already holds. Only then does it mint a new wrapping key and re-wrap the master key with it. ```json theme={null} { "status": "ok", "wrappingkey": "NEW-WRAPPING-KEY" } ``` > [!WARNING] > > The new wrapping key is returned **once, in the response body**, and is not stored anywhere you can read it back. If you lose it before completing the next step, the vault will not restart. Do not run this call in a way that leaves the response in shell history, CI logs, or terminal scrollback. **2. Store the new key before restarting** Write `wrappingkey` to **both** places it needs to exist: * Your secret manager — AWS Secrets Manager, HashiCorp Vault, Google Secret Manager, or equivalent. * The deployment configuration the container reads at boot: `DATABUNKER_WRAPPINGKEY`, `DATABUNKER_WRAPPINGKEY_FILE`, or the `-wrappingkey` argument. With Docker Compose this is the `.env` file; on Kubernetes it is the secret mounted into the pod. Keep the previous value until the restart has succeeded. Updating one location and not the other is the most common way this procedure goes wrong. **3. Restart Databunker Pro** The running process continues with the key it already holds in memory; the new key only takes effect on restart. ```sh theme={null} docker compose restart databunkerpro ``` On Kubernetes, roll the deployment after updating the secret. **4. Verify** Confirm the service is up: ```sh theme={null} curl http://localhost:3000/status ``` Then read back a known record with `UserGet`. A successful decryption proves the new wrapping key resolves to the same master key. Once verified, discard the old wrapping key. > [!NOTE] > > Your five Shamir shares remain valid after rotation and do **not** need to be reissued or redistributed. They protect a separate recovery wrapping of the master key, which rotation does not modify — see [Two independent wrappings](/pro/administration/master-key#two-independent-wrappings). ## Errors | Response | Meaning | | - | - | | `403 Only the main tenant admin can generate wrapping keys` | The token belongs to a sub-tenant. Use the main-tenant root token. | | `500 Failed to hex decode key1` | A share was not valid hex. Send the shares exactly as issued. | | `403 Master key mismatch` | The shares reconstructed a valid key, but for a different vault. Check you are using this instance's shares. | ## What is recoverable | Situation | Outcome | | - | - | | Three or more shares, wrapping key intact | Routine rotation. No data at risk. | | Wrapping key lost, instance **still running**, three or more shares | Recoverable now. Rotate using the procedure above, store the new key, then restart. Do not restart first. | | Wrapping key lost, instance **already stopped**, three or more shares | The vault cannot start without a wrapping key. [Contact support](mailto:office@databunkertech.com) and have your shares available. | | Wrapping key lost, **fewer than three shares** | **Unrecoverable.** The encrypted data cannot be decrypted — not by you, and not by Databunker support. There is no vendor backdoor. | | Shares lost or reduced below three, wrapping key intact | The vault keeps running normally, but you have lost your recovery margin and can no longer rotate. [Contact support](mailto:office@databunkertech.com) while the wrapping key is still intact — this is fixable, but treat it as an incident rather than a housekeeping task. | | Database lost | The wrapping key alone cannot reconstruct data. Restore from backup — see [backup and recovery](/pro/administration/backup-and-recovery). | > [!WARNING] > > **Three shares is a hard floor.** Below it, a lost wrapping key means permanent loss of every record in the vault. This is a property of the design, not a support limitation: Databunker Pro holds no copy of your keys and no escrow, which is precisely why a breach of our systems cannot expose your data. Audit the location and availability of all five shares on a schedule, and verify you can still reach three of them. > [!NOTE] > > A wrapping key lost while the vault is still **running** is routine to recover; the same loss discovered after it has **stopped** is not. If you find the key is missing, rotate before anything triggers a restart. # Master key Source: https://docs.databunker.org/pro/administration/master-key How Databunker Pro protects the master key with a wrapping key, why the master key is never exposed, and how the two independent wrappings enable rotation and recovery. The master key encrypts every personal-data record in the vault. It is generated automatically during initial setup and, unlike the open-source edition, is **never exposed** — not to users, not to administrators, and not through any API. Instead of handling the master key directly, you handle a **wrapping key**, which encrypts the master key. That indirection is what makes the rest of the key lifecycle practical: * **The master key never leaves the vault.** An attacker who obtains the encrypted master key cannot use it without the wrapping key. * **Rotation is cheap.** Rotating the wrapping key re-wraps the master key; it does not re-encrypt stored records, so the cost is independent of vault size. * **Operational and recovery custody are separate.** The wrapping key lives in your secret manager; recovery is held by [Shamir key shares](/pro/administration/shamir-keys) distributed among trusted parties. ## Two independent wrappings Databunker Pro stores the master key **twice**, wrapped by two different keys. This is the single most useful thing to understand about the key model, because it explains what rotation does and does not affect. | Stored as | Wrapped with | Used for | | - | - | - | | `encryptedkey` | The **operational wrapping key** — the value in `DATABUNKER_WRAPPINGKEY`, your `.env`, or your Kubernetes secret | Normal startup. Read every time the service boots. | | `recoverykey` | The **recovery wrapping key**, reconstructable from any three of the five Shamir shares | Recovery and rotation | Two consequences follow: * **Rotation only replaces `encryptedkey`.** Your five Shamir shares stay valid and never need reissuing or redistributing after a rotation, because `recoverykey` is untouched. * **The shares remain permanently sensitive.** Rotating the wrapping key does not invalidate previously issued shares — three of them still reconstruct the recovery path. Share custody is a standing obligation, not something rotation resets. ## Recovery If the wrapping key is lost while the instance is **still running**, you can recover by rotating: three Shamir shares let Databunker Pro mint a new wrapping key and re-wrap the master key, without the master key ever being exposed. See [Wrapping key rotation](/pro/administration/key-rotation). > [!WARNING] > > This is not a general-purpose disaster-recovery mechanism. The vault cannot start without a wrapping key, and rotation is performed against a live instance. If the wrapping key is lost and the service has already stopped, [contact support](mailto:office@databunkertech.com). If the wrapping key is lost **and** fewer than three shares remain, the data is unrecoverable — Databunker holds no copy of your keys and there is no escrow. See [What is recoverable](/pro/administration/key-rotation#what-is-recoverable). # Monitoring Source: https://docs.databunker.org/pro/administration/monitoring Scrape the Prometheus metrics endpoint, alert on the thresholds that matter, and cover the two things metrics cannot tell you — licence usage and database health. Databunker Pro exposes Prometheus metrics at `GET /metrics`. That covers the application tier. Two things it does not cover — **licence usage** and **database health** — come from elsewhere, and both are ways a healthy-looking instance can still fail. | What to watch | Source | | - | - | | Request rate, errors, latency, saturation | `GET /metrics` (Prometheus) | | Records used against your licence cap | `SystemGetSystemStats` API | | Database CPU, IOPS, index cache-hit ratio | Your database provider (RDS, Cloud SQL, …) | > [!WARNING] > > `/metrics` is served without authentication. It reveals which API methods are in use and at what volume, so bind it to an internal interface, or restrict it at the ingress or load balancer. Do not expose it publicly. ## Scrape configuration ```yaml theme={null} scrape_configs: - job_name: databunkerpro metrics_path: /metrics scrape_interval: 15s static_configs: - targets: ["databunkerpro:3000"] ``` On Kubernetes, target the pods rather than the service so each instance is scraped individually — a single unhealthy replica behind a load balancer is otherwise invisible. ## What is exposed | Metric | Labels | Use | | - | - | - | | `http_requests_total` | `method`, `path`, `status` | Request and error rates, per endpoint | | `http_request_duration_seconds` | `method`, `path` | Latency percentiles (histogram) | | `http_requests_in_flight` | — | Saturation | | `process_resident_memory_bytes` | — | Memory use | | `process_cpu_seconds_total` | — | CPU use | | `process_start_time_seconds` | — | Restart detection | | `go_goroutines` | — | Goroutine leaks | `path` carries the matched route (`/v2/UserCreate`), and anything unmatched is bucketed as `other`, so cardinality stays bounded no matter what scanners send. > [!NOTE] > > The duration histogram is labelled by `method` and `path` but **not** by `status`, so latency cannot be split by response code. Alert on error rate and latency separately. ## Alert rules ```yaml theme={null} groups: - name: databunkerpro rules: - alert: DatabunkerProDown expr: up{job="databunkerpro"} == 0 for: 2m annotations: summary: "Instance is not responding to scrapes" - alert: DatabunkerProRestarted expr: changes(process_start_time_seconds{job="databunkerpro"}[1h]) > 0 annotations: summary: "Instance restarted — confirm it came back up" - alert: DatabunkerProServerErrors expr: | sum(rate(http_requests_total{job="databunkerpro",status=~"5.."}[5m])) / sum(rate(http_requests_total{job="databunkerpro"}[5m])) > 0.01 for: 5m annotations: summary: "Over 1% of requests are returning 5xx" - alert: DatabunkerProAccessDeniedSpike expr: sum(rate(http_requests_total{job="databunkerpro",status="403"}[5m])) > 1 for: 10m annotations: summary: "Sustained 403s — licence limit, expiry, or failing authorisation" - alert: DatabunkerProSlowDetokenisation expr: | histogram_quantile(0.95, sum by (le) (rate(http_request_duration_seconds_bucket{job="databunkerpro",path="/v2/UserGet"}[5m])) ) > 0.05 for: 10m annotations: summary: "UserGet p95 above 50 ms (benchmark is ~15 ms)" ``` **Why these thresholds.** The p95 figure comes from the [benchmarks](/pro/get-started/performance#reads-detokenisation-latency): `UserGet` measured \~15 ms p95 against a fully-loaded 10 M-record vault. Sustained latency several times that usually means the database index no longer fits in RAM — check the cache-hit ratio before adding application instances. > [!WARNING] > > **A 403 spike is ambiguous and worth investigating rather than ignoring.** The same status code covers a failing API token, a policy denial, `Record limit reached` when the [licence cap](/pro/get-started/licensing#when-the-record-cap-is-reached) is hit, and `License expired` when the licence lapses. The metric cannot distinguish them — check the response messages in your application logs. ## Licence usage Nothing in `/metrics` reports how full the vault is. `SystemGetSystemStats` does: ```bash theme={null} curl -X POST http://localhost:3000/v2/SystemGetSystemStats \ -H "X-Bunker-Token: YOUR-ROOT-TOKEN" \ -H "Content-Type: application/json" ``` Alert on two things, both of which fail silently until a write is refused: * `totalnumrecords / licensemaxrecords` crossing **80%** * `licensefinalexpiration` coming within **30 days** A scheduled job that polls this and exports the values to your metrics system closes the gap. See [licensing and limits](/pro/get-started/licensing#checking-your-usage). ## Database health The [benchmarks](/pro/get-started/performance#the-key-insight-the-bottleneck-moves-with-scale) show that beyond tens of millions of records the **database** is the limit, not Databunker Pro. Two figures matter, and both come from your provider rather than from Databunker Pro: * **Database CPU above 70%** — adding application instances will not raise write throughput past this point; size the database up instead. * **Index cache-hit ratio below 97%** — the benchmark held ≥97% at every scale. Below that, lookups start reading from disk and detokenisation latency climbs. ## Audit trail The [audit trail](/pro/get-started/security-overview) is a compliance control, not a debug log. Its failure mode is silence, so treat a gap in audit records as an incident rather than a monitoring nuisance — a period of activity with no corresponding audit entries is the signal to look for. ## Next steps * [Production checklist](/pro/installation/production-checklist) — the go-live gate that includes these alerts * [Performance and sizing](/pro/get-started/performance) — where the thresholds come from * [Licensing and limits](/pro/get-started/licensing) — record caps and expiry behaviour * [Backup and recovery](/pro/administration/backup-and-recovery) — what to do when an alert turns into an incident # Multi-tenancy Source: https://docs.databunker.org/pro/administration/multi-tenancy Databunker Pro supports multi-tenancy, allowing you to manage multiple tenants within a single instance. This document outlines the API endpoints for creating, managing, and interacting with tenants. **Note:** Multi-tenancy is supported on PostgreSQL, MySQL, and Oracle. On PostgreSQL it is enforced with native row-level security (RLS) — see [Database-level tenant isolation](#database-level-tenant-isolation). > [!TIP] > > **Multi-tenancy is per-instance.** All tenants live inside the same Databunker Pro deployment and share the same physical region. If you need to keep PII inside different *legal jurisdictions* — for example because of GDPR cross-border rules, India's DPDPA, Russia's 152-FZ, or similar — multi-tenancy is not the right tool. Instead, run one Databunker Pro instance per jurisdiction and unify operations via Databunker DPO. See [Multi-jurisdiction deployment](/pro/concepts/global-deployment). ## Create Tenant Creates a new tenant in the Databunker Pro system. ```bash theme={null} curl -H 'X-Bunker-Token: ROOT-ACCESS-TOKEN' -X POST /v2/TenantCreate \ --data '{"tenantorg":"testorg","tenantname":"testname"}' ``` ### Request Body | Field | Type | Description | | - | - | - | | tenantname | string | The name of the tenant. Must match the format: \[a-z0-9]+ | | tenantorg | string | The organization slug associated with the tenant | ### Response | Field | Type | Description | | - | - | - | | status | string | Operation status ("ok" if successful) | | xtoken | string | Tenant access token in UUID format | ### Example Response ```json theme={null} { "status": "ok", "xtoken": "TENANT-ACCESS-TOKEN" } ``` ### Notes * The `TENANT-ACCESS-TOKEN` is a special token to authenticate all tenant related commands. For example create user records. ## Create a Tenant User Account You have two methods to specify the tenant name: you can either use the `X-Bunker-Tenant` HTTP header or include the tenant name in the hostname. If the `X-Bunker-Tenant` header is missing, Databunker Pro will attempt to retrieve the tenant name from the subdomain in the hostname. If neither option is available, a **default** tenant is used. Example commands: ```bash theme={null} curl -H 'X-Bunker-Token: XXXXXXX' \ -H 'X-Bunker-Tenant: TENANT-NAME' \ -H 'Content-Type: application/json' \ -X POST 'http://localhost:3000/v2/UserCreate' \ --data '{"profile":{"firstname":"John","lastname":"Doe","email":"user@email.com","login":"john"}}' ``` ```bash theme={null} curl -H 'X-Bunker-Token: XXXXXXX' \ -X POST https://TENANT-NAME.databunker-domain.com/v2/UserCreate \ --data '{"profile":{"firstname":"John","lastname":"Doe","email":"user@email.com","login":"john"}}' ``` ### Notes * Replace `TENANT-NAME` in the URL with the actual name of the tenant. * The request body and response format are identical to the standard `UserCreate` call — see the [API Reference](/pro/api/overview). The only difference is the tenant context supplied via the `X-Bunker-Tenant` header or the subdomain. ## Rename Tenant Renames an existing tenant. ```bash theme={null} curl -H 'X-Bunker-Token: TENANT-ACCESS-TOKEN' \ -X POST https://old-tenant.databunker-domain.com/v2/TenantUpdate \ --data '{"tenantname":"new-name"}' ``` ### Request Body | Field | Type | Description | | - | - | - | | tenantname | string | The new name for the tenant. Must match the format: \[a-z0-9]+ | ### Example Request ```json theme={null} { "tenantname": "new-name" } ``` ### Response | Field | Type | Description | | - | - | - | | status | string | Operation status ("ok" if successful) | ### Example Response ```json theme={null} { "status": "ok" } ``` ### Other commands: For a full list of API requests, check out the [API Reference](/pro/api/overview). ## General Notes 1. **Tenant Name Format**: Tenant names must follow the format `[a-z0-9]+`. This means they can only contain lowercase letters and numbers. 2. **Tenant-Specific URLs**: After creating a tenant, you'll interact with tenant-specific endpoints using URLs in the format `https://tenant-name.databunker-domain.com/...`. 3. **Authentication**: Most endpoints will require the `TENANT-ACCESS-TOKEN` for authentication. Include this token in the `X-Bunker-Token` header or as specified in the Databunker Pro documentation. 4. **SSL/TLS**: Always use HTTPS for secure communication with the API endpoints. For more detailed information on request/response formats, additional endpoints, or error handling, please refer to the complete Databunker Pro API documentation. ## Database-level tenant isolation On PostgreSQL, tenant isolation is enforced by the database itself rather than by the correctness of the queries Databunker Pro issues. Two dedicated roles are created during setup, both `NOSUPERUSER NOLOGIN` — neither can log into the database directly, and both are reachable only through `SET ROLE` inside Databunker Pro's own session. | Role | Privileges | Used for | | - | - | - | | `mtenant` | No `BYPASSRLS` — bound by row-level security on every tenant-scoped table | All ordinary traffic | | `madmin` | `BYPASSRLS`, granted `SELECT` on the `users` table only | The cross-tenant System Operations below | ### How mtenant scoping works Every tenant-scoped table has row-level security enabled, with a policy tying each row to the tenant set on the current session: ```sql theme={null} ALTER TABLE users ENABLE ROW LEVEL SECURITY; CREATE POLICY users_policy ON users FOR ALL TO mtenant USING (current_setting('my.tenantid')::int = tenantid); ``` Each request selects the role and the tenant before touching any data: ```sql theme={null} SET ROLE mtenant; SET my.tenantid=42; ``` From that point the database filters rows itself, so a query that omits its tenant condition — or gets it wrong — still cannot return another tenant's records. This is defence in depth: isolation does not depend on every query being written correctly. Roughly two dozen tables are covered, including `users`, `userapps`, `audit`, `sessions`, `agreements`, `files`, `tokens`, and the versioning tables. The connection default is `mtenant` with `my.tenantid=1`, so a session gets the restricted role unless something explicitly changes it. > [!NOTE] > > The `xtokens` table is intentionally **not** under RLS. An incoming API token must be resolved to a tenant before the tenant is known, so that lookup cannot itself be tenant-scoped. Tokens carry their tenant binding, which is then applied to every subsequent query in the request. ### How madmin is constrained The cross-tenant System Operations below necessarily bypass RLS, so two grants keep that bypass narrow: `madmin` holds **`SELECT` only**, and **only on the `users` table**. Even on the bypass path it cannot write anything, and cannot read audit records, sessions, files, or any other table. ### MySQL and Oracle Multi-tenancy is supported on both, but neither uses a database-enforced equivalent of RLS: there, tenant scoping is applied in the queries Databunker Pro issues. The isolation model is identical from the API's point of view, without this second, database-level line of defence. ## Cross-tenant System Operations Databunker Pro provides a dedicated **System Operations** API for cross-tenant queries. These endpoints are used for compliance workflows that span the entire deployment — DSAR fulfillment, regulator queries, right-to-erasure, and forensic investigations — where the answer to *"find every record about this person across all our tenants"* must come from one call rather than N tenant-by-tenant queries. ### Access control All System Operations endpoints are: * **Restricted to the main tenant admin (`tenantID = 1`)** — the highest-privilege principal of the deployment. Tenant-level admins cannot invoke these endpoints. * **Gated by a `bulkListUnlock` UUID** — short-lived, must be obtained via `/v2/BulkListUnlock` immediately before the call. This is the same default-deny mechanism used for bulk operations: an admin token alone is not enough. * **Audited on every call.** ### Endpoints | Endpoint | Purpose | | - | - | | `POST /v2/SystemGetUserProfiles` | Retrieve all profiles for a user (identified by `email` / `phone` / `login` / `custom`) across every tenant. | | `POST /v2/SystemSearchUserProfiles` | Fuzzy-search for user profiles across every tenant. Mode is auto-detected from the identity value. | | `POST /v2/SystemDeleteUserProfiles` | Delete all profiles for a user across every tenant — or restrict to a single tenant via `tenantid` / `tenantname`. | | `POST /v2/SystemRestoreUserProfile` | Restore a previously-deleted user profile for a specific tenant from version history. | Every response includes the originating `tenantid` and `tenantname` for each profile, so the caller can see exactly which tenants the person appeared in. ### Example: find a user across every tenant ```bash theme={null} # Step 1: obtain a short-lived unlock UUID UNLOCK=$(curl -s -X POST https://your-databunker-instance/v2/BulkListUnlock \ -H "X-Bunker-Token: MAIN_ADMIN_TOKEN" | jq -r .unlockuuid) # Step 2: cross-tenant lookup curl -X POST https://your-databunker-instance/v2/SystemGetUserProfiles \ -H "X-Bunker-Token: MAIN_ADMIN_TOKEN" \ -H "Content-Type: application/json" \ -d "{ \"mode\": \"email\", \"identity\": \"john.doe@example.com\", \"unlockuuid\": \"$UNLOCK\" }" ``` ### Example response ```json theme={null} { "status": "ok", "total": 3, "rows": [ { "tenantid": 7, "tenantname": "student-services", "token": "abc-...", "profile": { "...": "..." } }, { "tenantid": 9, "tenantname": "analytics", "token": "def-...", "profile": { "...": "..." } }, { "tenantid": 12,"tenantname": "alumni", "token": "ghi-...", "profile": { "...": "..." } } ] } ``` The same person appears under three different tokens — one per tenant — which is the expected outcome of the per-tenant uniqueness model. The System Operations response is the only place these tokens are correlated, and the correlation is audited. ## Next steps * [Access control](/pro/administration/access-control) — policies and roles within a tenant * [Sub-accounts](/pro/concepts/sub-accounts) — choosing between tenants and groups * [Multi-jurisdiction deployment](/pro/concepts/global-deployment) — when a separate instance beats a separate tenant # Shamir key shares Source: https://docs.databunker.org/pro/administration/shamir-keys How Databunker Pro splits the recovery key into five shares under a 3-of-5 threshold, and how to store, distribute, and audit them. At setup, Databunker Pro splits the recovery wrapping key into **five shares** using Shamir's Secret Sharing, under a **3-of-5 threshold**: any three shares reconstruct the key, and any two reveal nothing about it. These shares are your recovery path. They are used to [rotate the wrapping key](/pro/administration/key-rotation), and they are what stands between a lost wrapping key and permanent loss of the vault. ## What you receive * **Five shares**, issued once during [initial setup](/pro/installation/generate-admin-credentials) alongside the root access token and the wrapping key. * Each share is **hex-encoded**. The rotation API hex-decodes them and rejects anything else, so store them exactly as issued — no re-encoding, no trimming. * The shares reconstruct the **recovery** wrapping key, which is separate from the operational wrapping key you keep in your secret manager. See [Two independent wrappings](/pro/administration/master-key#two-independent-wrappings). > [!WARNING] > > The five shares are displayed once at setup and cannot be retrieved from the running system afterwards. Capture all five before leaving the setup screen. ## Storing and distributing shares The threshold only buys you something if the shares are genuinely separated. Five shares in one password vault is a 1-of-1 scheme wearing a costume. * **Separate custodians.** Give each share to a different person, or place it in a different system — ideally both. Three should never be reachable by one individual acting alone. * **Separate systems.** Avoid putting shares in the same store as the operational wrapping key. An attacker who reaches that store should not also obtain the recovery path. * **Document custody, not content.** Record who holds which share and how to reach them. Never record the share values in that document. * **Plan for staff turnover.** Reassign a custodian's share when they leave. This is the most common way an organisation quietly drops below three. ## Audit them on a schedule Because a shortfall is invisible until you need the shares, verify availability rather than assuming it: * Confirm each custodian can still produce their share, at least annually. * Confirm at least three are reachable within your target recovery time. * Rehearse a [wrapping key rotation](/pro/administration/key-rotation) — it exercises the same three-share path as recovery, on a running vault, with no risk to data. > [!NOTE] > > Rotation does **not** reissue or invalidate shares. The same five remain valid for the life of the deployment, which is why their custody needs periodic review rather than a one-time setup step. ## If you drop below three | Situation | What to do | | - | - | | Fewer than three shares reachable, wrapping key intact | [Contact support](mailto:office@databunkertech.com) while the wrapping key is still available. This is fixable, but treat it as an incident. | | Fewer than three shares reachable, wrapping key lost | Unrecoverable. Databunker holds no copy of your keys and there is no escrow. | For the full matrix, see [What is recoverable](/pro/administration/key-rotation#what-is-recoverable). # Accept agreement Source: https://docs.databunker.org/pro/api/agreement-management/accept-agreement /pro/api/openapi.yml post /v2/AgreementAccept Records user's acceptance of a legal basis/agreement # Cancel agreement Source: https://docs.databunker.org/pro/api/agreement-management/cancel-agreement /pro/api/openapi.yml post /v2/AgreementCancel Cancels a user's agreement # Get user agreement Source: https://docs.databunker.org/pro/api/agreement-management/get-user-agreement /pro/api/openapi.yml post /v2/AgreementGet Retrieves a specific agreement for a user # List user agreements Source: https://docs.databunker.org/pro/api/agreement-management/list-user-agreements /pro/api/openapi.yml post /v2/AgreementListUserAgreements Lists all agreements for a specific user # Request agreement cancellation Source: https://docs.databunker.org/pro/api/agreement-management/request-agreement-cancellation /pro/api/openapi.yml post /v2/AgreementCancelRequest Creates a cancellation request for an agreement (requires approval) # Revoke all agreements Source: https://docs.databunker.org/pro/api/agreement-management/revoke-all-agreements /pro/api/openapi.yml post /v2/AgreementRevokeAll Revokes all agreements for a specific legal basis # Create application data for user Source: https://docs.databunker.org/pro/api/app-data-management/create-application-data-for-user /pro/api/openapi.yml post /v2/AppdataCreate Stores application-specific data for a user # Delete application data for user Source: https://docs.databunker.org/pro/api/app-data-management/delete-application-data-for-user /pro/api/openapi.yml post /v2/AppdataDelete Deletes application-specific data for a user # Get application data for user Source: https://docs.databunker.org/pro/api/app-data-management/get-application-data-for-user /pro/api/openapi.yml post /v2/AppdataGet Retrieves application-specific data for a user # List all application names Source: https://docs.databunker.org/pro/api/app-data-management/list-all-application-names /pro/api/openapi.yml post /v2/AppdataListAppNames Retrieves a list of all application names in the system # List app data versions Source: https://docs.databunker.org/pro/api/app-data-management/list-app-data-versions /pro/api/openapi.yml post /v2/AppdataListVersions Lists all versions of application data for a user # List user application names Source: https://docs.databunker.org/pro/api/app-data-management/list-user-application-names /pro/api/openapi.yml post /v2/AppdataListUserAppNames Retrieves a list of application names for a specific user # Request app data update Source: https://docs.databunker.org/pro/api/app-data-management/request-app-data-update /pro/api/openapi.yml post /v2/AppdataUpdateRequest Creates an update request for app data (requires approval) # Update application data for user Source: https://docs.databunker.org/pro/api/app-data-management/update-application-data-for-user /pro/api/openapi.yml post /v2/AppdataUpdate Updates application-specific data for a user # Get specific audit event Source: https://docs.databunker.org/pro/api/audit-management/get-specific-audit-event /pro/api/openapi.yml post /v2/AuditGetEvent Retrieves detailed information about a specific audit event # List user audit events Source: https://docs.databunker.org/pro/api/audit-management/list-user-audit-events /pro/api/openapi.yml post /v2/AuditListUserEvents Retrieves audit events for a specific user # Authentication Source: https://docs.databunker.org/pro/api/authentication Every credential type in Databunker Pro — root tokens, tenant tokens, role and user xtokens, and the bulk-unlock UUID — and how to obtain and use each one. Every authenticated API call carries a credential in the `X-Bunker-Token` header. Databunker Pro has a small hierarchy of credential types, each scoped to a different level of access. This page is the single reference for all of them. ## Request headers | Header | Required | Purpose | | - | - | - | | `X-Bunker-Token` | Yes (for authenticated endpoints) | The access credential — any of the token types below | | `X-Bunker-Tenant` | No | Selects the tenant by name in [multi-tenant](/pro/administration/multi-tenancy) deployments | If `X-Bunker-Tenant` is omitted, Databunker Pro derives the tenant from the **subdomain** of the request host (`acme.databunker.example.com` → tenant `acme`). Requests to `localhost` or a bare host resolve to the **default** tenant. ## Credential hierarchy | Credential | Token type | Obtained via | Expiry | | - | - | - | - | | Root token | `root` | Interactive setup or unattended install | Never | | Tenant access token | `root` (tenant-scoped) | `TenantCreate` | Never | | Role xtoken | `role` | `XTokenCreateForRole` | Default 10 minutes; capped by `max_xtoken_retention_period` | | User login xtoken | `login` | `XTokenCreateForUser` | Default 10 minutes; capped by `max_xtoken_retention_period` | | Bulk-unlock UUID | request gate | `BulkListUnlock` | 60 seconds | All tokens are stored **hashed** on the server — a token value is shown exactly once at creation time and cannot be recovered later. ### Root token The highest-privilege credential of the deployment, created once at installation: * **Interactive setup** — shown once on the setup completion screen. See [Generate admin credentials](/pro/installation/generate-admin-credentials). * **Unattended install** — returned by the `/autoinstall` endpoint, which is enabled only while the `DATABUNKER_SETUPKEY` environment variable is set. See [Unattended installation](/pro/installation/unattended-installation). Root tokens never expire. Use them for administration and automation, and prefer scoped role xtokens for application traffic. ### Tenant access token In multi-tenant deployments, `TenantCreate` returns an `xtoken` — the tenant administrator's credential. It behaves like a root token scoped to that tenant: ```bash theme={null} curl -X POST https://your-databunker/v2/TenantCreate \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" \ -d '{"tenantname":"acme","tenantorg":"Acme Corp"}' ``` ```json theme={null} { "status": "ok", "xtoken": "TENANT-ACCESS-TOKEN" } ``` The tenant admin passes this token in `X-Bunker-Token`, together with `X-Bunker-Tenant: acme` (or the tenant subdomain). See [Multi-tenancy](/pro/administration/multi-tenancy). ### Role xtoken Scoped service credentials governed by [access-control policies](/pro/administration/access-control). Setup is three calls: ```bash theme={null} # 1. Create a role curl -X POST https://your-databunker/v2/RoleCreate \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" \ -d '{"rolename":"support-desk"}' # 2. Attach a policy to the role curl -X POST https://your-databunker/v2/RoleLinkPolicy \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" \ -d '{"roleid":1,"policyid":1}' # 3. Issue an xtoken for the role curl -X POST https://your-databunker/v2/XTokenCreateForRole \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" \ -d '{"roleid":1,"finaltime":"7d"}' ``` ```json theme={null} { "status": "ok", "xtoken": "ROLE-XTOKEN" } ``` Without `finaltime` the xtoken expires after **10 minutes**. A supplied `finaltime` is capped by the `max_xtoken_retention_period` configuration policy. ### User login xtoken A short-lived credential that lets an end user act on **their own record only** (e.g. from the user privacy portal): ```bash theme={null} curl -X POST https://your-databunker/v2/XTokenCreateForUser \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" \ -d '{"mode":"email","identity":"user@example.com"}' ``` ```json theme={null} { "status": "ok", "xtoken": "USER-LOGIN-XTOKEN", "token": "USER-TOKEN-UUID" } ``` Same expiry rules as role xtokens: 10 minutes by default, capped by `max_xtoken_retention_period`. > [!NOTE] > > For safety, a login xtoken **cannot** invoke `UserDelete`, `UserUpdate`, `UserPatch`, `AppdataUpdate`, or `AgreementCancel` on its own record — these self-service operations must go through an admin or a [user request workflow](/pro/api/overview) with approval. ### Bulk-unlock UUID Bulk read and delete operations are **denied by default** — an admin token alone is not enough. You must first obtain a short-lived unlock UUID, then pass it with the bulk call: ```bash theme={null} # Step 1: obtain the unlock UUID (valid for 60 seconds) curl -X POST https://your-databunker/v2/BulkListUnlock \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" # → { "status": "ok", "unlockuuid": "..." } # Step 2: use it in the bulk request curl -X POST https://your-databunker/v2/BulkListAllUsers \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" \ -d '{"unlockuuid":"...","offset":0,"limit":100}' ``` The unlock UUID lives for **60 seconds** and may be reused within that window. It applies to `BulkList*`, `BulkDeleteTokens`, `UserSearch`, and the cross-tenant `System*` lookups. See [Select security](/pro/concepts/select-security) for the design rationale. ## Endpoint permission levels * **Public endpoints** — no token required: `UserPrelogin`, `UserLogin`, `CaptchaCreate`, `SharedRecordGet`, `TenantGetUIConf`. Calls to these are not written to the audit trail. * **Authenticated endpoints** — everything else requires `X-Bunker-Token` and passes policy evaluation: root tokens bypass policy checks, role xtokens are evaluated against their linked policies, and login xtokens are restricted to the user's own record. * **Main-tenant-only endpoints** — denied to sub-tenant admins even with a valid tenant token: `RoleCreate`, `RoleUpdate`, `PolicyCreate`, `PolicyUpdate`, `TenantListTenants`, `SystemGenerateWrappingKey`, and all cross-tenant `System*` operations. Failed authentication returns HTTP `403` with `{"status":"error","message":"Access denied"}` — see [Errors](/pro/api/errors). # Create access token for role Source: https://docs.databunker.org/pro/api/authentication/create-access-token-for-role /pro/api/openapi.yml post /v2/XTokenCreateForRole Creates an access token for a specific role # Create access token for user Source: https://docs.databunker.org/pro/api/authentication/create-access-token-for-user /pro/api/openapi.yml post /v2/XTokenCreateForUser Creates an access token for a specific user # Create bulk list unlock Source: https://docs.databunker.org/pro/api/bulk-operations/create-bulk-list-unlock /pro/api/openapi.yml post /v2/BulkListUnlock Creates an unlock mechanism for bulk list operations # Delete tokens in bulk Source: https://docs.databunker.org/pro/api/bulk-operations/delete-tokens-in-bulk /pro/api/openapi.yml post /v2/BulkDeleteTokens Deletes multiple tokens using the bulk unlock mechanism # List all audit events in bulk Source: https://docs.databunker.org/pro/api/bulk-operations/list-all-audit-events-in-bulk /pro/api/openapi.yml post /v2/BulkListAllAuditEvents Lists all audit events using the bulk unlock mechanism # List all user requests in bulk Source: https://docs.databunker.org/pro/api/bulk-operations/list-all-user-requests-in-bulk /pro/api/openapi.yml post /v2/BulkListAllUserRequests Lists all user requests using the bulk unlock mechanism with pagination # List all users in bulk Source: https://docs.databunker.org/pro/api/bulk-operations/list-all-users-in-bulk /pro/api/openapi.yml post /v2/BulkListAllUsers Lists all users using the bulk unlock mechanism with pagination # List files by tag across users Source: https://docs.databunker.org/pro/api/bulk-operations/list-files-by-tag-across-users /pro/api/openapi.yml post /v2/BulkListFilesByTag Lists file metadata for every file carrying the given tag, across all users in the tenant. Requires an `unlockuuid` from `BulkListUnlock`. Results are limited to the tags the caller's policy permits. File content is not returned. # List specific users in bulk Source: https://docs.databunker.org/pro/api/bulk-operations/list-specific-users-in-bulk /pro/api/openapi.yml post /v2/BulkListUsers Looks up a batch of users by indexed field (`email`, `phone`, `login`, or `custom`) in a single call, returning the token and profile for each match. Requires a `unlockuuid` from `BulkListUnlock`. Every supplied criterion is evaluated — this endpoint is not paginated, so all matches are returned regardless of how many criteria you send. Identities with no stored record are simply absent from `rows` rather than reported as errors. Disabled unless the `list_users` configuration flag is on; otherwise returns `403 BulkListUsers is disabled`. # List tokens in bulk Source: https://docs.databunker.org/pro/api/bulk-operations/list-tokens-in-bulk /pro/api/openapi.yml post /v2/BulkListTokens Lists tokens using the bulk unlock mechanism # List users in group in bulk Source: https://docs.databunker.org/pro/api/bulk-operations/list-users-in-group-in-bulk /pro/api/openapi.yml post /v2/BulkListGroupUsers Lists users in a specific group using the bulk unlock mechanism # Errors Source: https://docs.databunker.org/pro/api/errors Error response format, HTTP status codes, and a catalog of common error messages returned by the Databunker Pro API. Every error is returned as a JSON body with a fixed shape: ```json theme={null} { "status": "error", "message": "The user record was not found" } ``` Successful responses always include `"status": "ok"`. As a defensive pattern, check the JSON `status` field in addition to the HTTP status code. ## HTTP status codes | Code | Meaning | | - | - | | 400 | Bad request — malformed body, missing or invalid parameters, schema validation failure | | 403 | Access denied — missing/invalid API token, insufficient permissions, disabled feature, or license limit | | 404 | The referenced record was not found | | 409 | Conflict — duplicate record, name already in use, or operation conflicts with the record's current state | | 500 | Internal server error | > [!NOTE] > > Databunker Pro releases prior to the 2026-07 update returned HTTP `405` for most error conditions. If you run an older release, treat any non-2xx response as an error and rely on the JSON `status`/`message` fields. ## Common error messages The `message` field is human-readable. Representative messages per status code: ### 400 — Bad request | Message | Cause | | - | - | | `Missing API request parameters: profile` | A required request field was omitted (lists the fields) | | `Failed to decode the request body` | The body is not valid JSON | | `Bad UUID` | An identifier is not a valid UUID | | `The mode parameter has an incorrect format` | An enum-style parameter has an unexpected value | | `Failed to validate user schema: ...` | The profile fails the configured user record schema | | `The filedata parameter is not valid base64` | File upload payload is not base64-encoded | ### 403 — Access denied | Message | Cause | | - | - | | `Access denied` | Missing/invalid `X-Bunker-Token`, or the token's policy denies the operation | | `API access denied` | Policy evaluation rejected the request | | `Record limit reached` | The [license record cap](/pro/get-started/licensing#when-the-record-cap-is-reached) was hit — new records cannot be created, while reads, updates and deletes keep working | | `License expired` | The installation license has expired and the vault is [read-only](/pro/get-started/licensing#when-the-license-expires) — reads, exports and deletions still work | | `BulkListUsers is disabled` | The `list_users` configuration flag is off | | `The unlockuuid value was not found or is not valid` | The [bulk-unlock UUID](/pro/api/authentication#bulk-unlock-uuid) is missing, wrong, or past its 60-second lifetime | | `Only the main tenant admin can ...` | A main-tenant-only endpoint was called with a sub-tenant token | ### 404 — Not found | Message | Cause | | - | - | | `The user record was not found` | No user matches the given `mode`/`identity` | | `Token not found` | The token UUID does not exist or has expired | | `The group record was not found` | Unknown group ID | | `The legal basis record was not found` | Unknown legal-basis `brief` | | `The API request was not found` | The `/v2/` endpoint name does not exist | ### 409 — Conflict | Message | Cause | | - | - | | `Duplicate index: email` | Another user already holds this unique index value (email/phone/login/custom) | | `The role record already exists` | Create called with a name that is already taken | | `Duplicate tenant name` | Tenant name already in use | | `This user request is closed` | Approve/cancel called on a request that is no longer open | ### 500 — Internal server error | Message | Cause | | - | - | | `Internal error` / `Database error` | Unexpected server-side failure — check the server logs | | `Failed to decrypt the user record` | Storage-level failure (e.g. key mismatch) — check the server logs | Server-side error details (database errors, stack context) are **never** included in API responses — they are written to the server log and the audit trail only. ## Special cases * **`UserPrelogin` captcha failure** returns HTTP `200` with `{"status":"error","message":"captcha-error"}` — the user portal login flow consumes this in-body. Always check the `status` field on prelogin responses. * **Public endpoints** (`UserPrelogin`, `UserLogin`, `CaptchaCreate`, `SharedRecordGet`, `TenantGetUIConf`) require no token; all other endpoints return `403` without a valid one — see [Authentication](/pro/api/authentication). * **Unknown endpoint names** under `/v2/` return `404` with `The API request was not found`; unknown URL paths outside `/v2/` return `404` with `endpoint is missing`. # Delete a user file Source: https://docs.databunker.org/pro/api/file-storage/delete-a-user-file /pro/api/openapi.yml post /v2/FileDelete Removes a user file, deleting both the stored object and its metadata. # Get a user file Source: https://docs.databunker.org/pro/api/file-storage/get-a-user-file /pro/api/openapi.yml post /v2/FileGet Returns the decrypted content of a user file. The file is selected by `fileuuid` (preferred) or by `filename`. When selecting by `filename`, the most recently created file with that name is returned. At least one of `fileuuid` or `filename` is required. By default the content is returned as a base64-encoded `filedata` field inside a JSON response. Set `raw` to `true` to receive the decrypted bytes directly with the appropriate `Content-Type` and `Content-Disposition` headers (useful for direct downloads). # List user files Source: https://docs.databunker.org/pro/api/file-storage/list-user-files /pro/api/openapi.yml post /v2/FileListUserFiles Retrieves the metadata of all files owned by a user. File content is not returned. # Replace the tags on a file Source: https://docs.databunker.org/pro/api/file-storage/replace-the-tags-on-a-file /pro/api/openapi.yml post /v2/FileReplaceTags Replaces the complete tag set on a file. The supplied list is authoritative — tags not included are removed. Tags are lowercased, trimmed and de-duplicated, must match `^[a-z0-9][a-z0-9._-]{0,49}$`, and at most 16 are kept. The caller must be authorised for both the file's current tags and the tags being applied. # Store a file for a user Source: https://docs.databunker.org/pro/api/file-storage/store-a-file-for-a-user /pro/api/openapi.yml post /v2/FileCreate Stores an encrypted file for a user. The file content is supplied as a base64-encoded `filedata` field. Each file is encrypted with a per-file key (wrapped by the user's record key) and stored in the configured object-storage backend (local disk, Amazon S3, Google Cloud Storage, or Azure Blob Storage). If the same content is uploaded again for the same user, the response sets `duplicate` to `true` and no new object is written. # Create multiple tokens in bulk Source: https://docs.databunker.org/pro/api/format-preserving-tokenization/create-multiple-tokens-in-bulk /pro/api/openapi.yml post /v2/TokenCreateBulk Creates multiple tokens for sensitive data # Create token for sensitive data Source: https://docs.databunker.org/pro/api/format-preserving-tokenization/create-token-for-sensitive-data /pro/api/openapi.yml post /v2/TokenCreate Creates a token for sensitive data like credit card numbers # Delete token Source: https://docs.databunker.org/pro/api/format-preserving-tokenization/delete-token /pro/api/openapi.yml post /v2/TokenDelete Deletes a token and its associated data # Get token data Source: https://docs.databunker.org/pro/api/format-preserving-tokenization/get-token-data /pro/api/openapi.yml post /v2/TokenGet Retrieves the original data for a given token # Add user to group Source: https://docs.databunker.org/pro/api/group-management/add-user-to-group /pro/api/openapi.yml post /v2/GroupAddUser Adds a user to a specific group with optional role assignment # Create a new group Source: https://docs.databunker.org/pro/api/group-management/create-a-new-group /pro/api/openapi.yml post /v2/GroupCreate Creates a new group for organizing users # Delete group Source: https://docs.databunker.org/pro/api/group-management/delete-group /pro/api/openapi.yml post /v2/GroupDelete Deletes a group # Get group information Source: https://docs.databunker.org/pro/api/group-management/get-group-information /pro/api/openapi.yml post /v2/GroupGet Retrieves information about a specific group # List all groups Source: https://docs.databunker.org/pro/api/group-management/list-all-groups /pro/api/openapi.yml post /v2/GroupListAllGroups Retrieves a list of all groups in the system # List user groups Source: https://docs.databunker.org/pro/api/group-management/list-user-groups /pro/api/openapi.yml post /v2/GroupListUserGroups Lists all groups for a specific user # Remove user from group Source: https://docs.databunker.org/pro/api/group-management/remove-user-from-group /pro/api/openapi.yml post /v2/GroupDeleteUser Removes a user from a specific group # Update group Source: https://docs.databunker.org/pro/api/group-management/update-group /pro/api/openapi.yml post /v2/GroupUpdate Updates an existing group # Create legal basis Source: https://docs.databunker.org/pro/api/legal-basis-management/create-legal-basis /pro/api/openapi.yml post /v2/LegalBasisCreate Creates a new legal basis for data processing # Delete legal basis Source: https://docs.databunker.org/pro/api/legal-basis-management/delete-legal-basis /pro/api/openapi.yml post /v2/LegalBasisDelete Deletes a legal basis # List legal basis agreements Source: https://docs.databunker.org/pro/api/legal-basis-management/list-legal-basis-agreements /pro/api/openapi.yml post /v2/LegalBasisListAgreements Lists all legal basis agreements in the system # Update legal basis Source: https://docs.databunker.org/pro/api/legal-basis-management/update-legal-basis /pro/api/openapi.yml post /v2/LegalBasisUpdate Updates an existing legal basis # API Overview Source: https://docs.databunker.org/pro/api/overview Databunker Pro is a privacy-compliant user data vault and tokenization engine that provides secure storage and management of user data with built-in privacy controls, consent management, and audit capabilities. To try these endpoints against a live instance, start one with [demo mode](/pro/get-started/quickstart) — one `docker run`, root token `DEMO`. ## API Documents for AI Assistants Feed these directly into your LLM or AI coding assistant for accurate, context-aware help when building integrations: * [OpenAPI Specification](https://github.com/securitybunker/databunkerpro-docs/blob/main/pro/api/openapi.yml) * [Full documentation (LLM-friendly)](https://docs.databunker.org/llms-full.txt) * [Documentation index (LLM-friendly)](https://docs.databunker.org/llms.txt) * [MCP server](https://docs.databunker.org/mcp) ## Key Features * **User Tokenization**: Create, update, and manage user profiles with privacy controls * **Consent Management**: Handle legal basis and user agreements for GDPR/DPDP compliance * **Format Preserving Tokenization**: Secure tokenization of sensitive data like credit cards * **File Storage**: Encrypted per-user file storage backed by local disk, Amazon S3, Google Cloud Storage, or Azure Blob Storage * **Audit Trail**: Complete audit logging of all data access and modifications * **Multi-tenant**: Support for multiple tenants with isolated data * **Role-based Access**: Fine-grained access control with policies and roles * **Bulk Operations**: Efficient bulk data operations with unlock mechanisms ## Authentication All API calls require authentication via the `X-Bunker-Token` header. For multi-tenant setups, use the `X-Bunker-Tenant` header to specify the tenant context. For the full credential hierarchy — root tokens, tenant tokens, role and user xtokens, and the bulk-unlock UUID — see the [Authentication reference](/pro/api/authentication). ### Multi-Tenant Usage Multi-tenancy is supported on PostgreSQL, MySQL (Percona), and Oracle backend databases. On PostgreSQL it is enforced with the database's native row-level security (RLS). When using Databunker Pro in a multi-tenant environment: * **Single Tenant**: Omit the `X-Bunker-Tenant` header (default behavior) * **Multi-Tenant**: Include `X-Bunker-Tenant: your-tenant-name` header **Example:** ```bash theme={null} # Single tenant curl -X POST http://localhost:3000/v2/UserCreate \ -H "X-Bunker-Token: your-token" \ -d '{"profile":{"login":"user1"}}' # Multi-tenant curl -X POST http://localhost:3000/v2/UserCreate \ -H "X-Bunker-Token: your-token" \ -H "X-Bunker-Tenant: acme-corp" \ -d '{"profile":{"login":"user1"}}' ``` ## Base URL The API is available at `/v2/` endpoint with all requests using POST method. ## Error Handling Every error is returned as `{"status":"error","message":"..."}` with a conventional HTTP status code (400/403/404/409/500). See the full [Errors reference](/pro/api/errors) for the status-code table and a catalog of common messages. ## Pagination List endpoints accept `offset`/`limit` in the request body and return a `{status, total, rows}` envelope. See the [Pagination reference](/pro/api/pagination). # Pagination Source: https://docs.databunker.org/pro/api/pagination How list endpoints paginate results in Databunker Pro — offset/limit parameters, the response envelope, and a worked example. List endpoints use **offset/limit pagination**. Parameters are passed in the JSON request body: | Parameter | Type | Default | Notes | | - | - | - | - | | `offset` | integer | `0` | Number of records to skip | | `limit` | integer | `10` | Page size. Values below `1` or above `100` are treated as `100` | > [!WARNING] > > The `limit` cap is silent: requesting `limit: 500` (or an invalid value) returns up to **100** rows without an error. Always read `total` from the response instead of assuming your requested page size was honored. ## Response envelope All list endpoints share the same envelope: ```json theme={null} { "status": "ok", "total": 1543, "rows": [ { "...": "..." } ] } ``` `total` is the **complete record count**, not the number of rows in the current page — use it to compute how many pages to fetch. ## Paginated endpoints | Endpoint | Notes | | - | - | | `BulkListUsers` | Requires an [unlock UUID](/pro/api/authentication#bulk-unlock-uuid) | | `BulkListAllUsers` | Requires an unlock UUID; needs the `list_users` config flag | | `BulkListGroupUsers` | Requires an unlock UUID | | `BulkListAllUserRequests` | Requires an unlock UUID | | `BulkListAllAuditEvents` | Requires an unlock UUID | | `UserRequestListUserRequests` | Per-user request list | | `AuditListUserEvents` | Per-user audit trail | | `TenantListTenants` | Main-tenant admin only | Other `List*` endpoints (`GroupListAllGroups`, `PolicyListAllPolicies`, `AppdataListUserAppNames`, `FileListUserFiles`, `SessionListUserSessions`, etc.) return the **full result set** in one response — their collections are expected to stay small. > [!NOTE] > > Cursor-based pagination is not available — offset/limit is the only mechanism. ## Example: paging through all users Bulk listing is gated by a short-lived unlock UUID (see [Authentication](/pro/api/authentication#bulk-unlock-uuid)). Fetch the unlock, then iterate: ```bash theme={null} # Obtain an unlock UUID (valid for 60 seconds) UNLOCK=$(curl -s -X POST https://your-databunker/v2/BulkListUnlock \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" | jq -r .unlockuuid) # Page 1 (records 0-99) curl -X POST https://your-databunker/v2/BulkListAllUsers \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" \ -d "{\"unlockuuid\":\"$UNLOCK\",\"offset\":0,\"limit\":100}" # Page 2 (records 100-199) curl -X POST https://your-databunker/v2/BulkListAllUsers \ -H "X-Bunker-Token: ROOT-ACCESS-TOKEN" \ -d "{\"unlockuuid\":\"$UNLOCK\",\"offset\":100,\"limit\":100}" ``` If a long export outlives the 60-second unlock window, request a fresh `unlockuuid` and continue from the same `offset`. # Create a new policy Source: https://docs.databunker.org/pro/api/policy-management/create-a-new-policy /pro/api/openapi.yml post /v2/PolicyCreate Creates a new access control policy # Get policy information Source: https://docs.databunker.org/pro/api/policy-management/get-policy-information /pro/api/openapi.yml post /v2/PolicyGet Retrieves information about a specific policy # List all policies Source: https://docs.databunker.org/pro/api/policy-management/list-all-policies /pro/api/openapi.yml post /v2/PolicyListAllPolicies Retrieves a list of all policies in the system # Update a policy Source: https://docs.databunker.org/pro/api/policy-management/update-a-policy /pro/api/openapi.yml post /v2/PolicyUpdate Updates an existing access control policy # Create processing activity Source: https://docs.databunker.org/pro/api/processing-activity-management/create-processing-activity /pro/api/openapi.yml post /v2/ProcessingActivityCreate Creates a new processing activity # Delete processing activity Source: https://docs.databunker.org/pro/api/processing-activity-management/delete-processing-activity /pro/api/openapi.yml post /v2/ProcessingActivityDelete Deletes a processing activity # Link processing activity to legal basis Source: https://docs.databunker.org/pro/api/processing-activity-management/link-processing-activity-to-legal-basis /pro/api/openapi.yml post /v2/ProcessingActivityLinkLegalBasis Links a processing activity to a legal basis # List processing activities Source: https://docs.databunker.org/pro/api/processing-activity-management/list-processing-activities /pro/api/openapi.yml post /v2/ProcessingActivityListActivities Lists all processing activities in the system # Unlink processing activity from legal basis Source: https://docs.databunker.org/pro/api/processing-activity-management/unlink-processing-activity-from-legal-basis /pro/api/openapi.yml post /v2/ProcessingActivityUnlinkLegalBasis Unlinks a processing activity from a legal basis # Update processing activity Source: https://docs.databunker.org/pro/api/processing-activity-management/update-processing-activity /pro/api/openapi.yml post /v2/ProcessingActivityUpdate Updates an existing processing activity # Create a new role Source: https://docs.databunker.org/pro/api/role-management/create-a-new-role /pro/api/openapi.yml post /v2/RoleCreate Creates a new role for access control # Link policy to role Source: https://docs.databunker.org/pro/api/role-management/link-policy-to-role /pro/api/openapi.yml post /v2/RoleLinkPolicy Links a policy to a role for access control # Update role Source: https://docs.databunker.org/pro/api/role-management/update-role /pro/api/openapi.yml post /v2/RoleUpdate Updates an existing role # Delete session Source: https://docs.databunker.org/pro/api/session-management/delete-session /pro/api/openapi.yml post /v2/SessionDelete Deletes a user session # Get session Source: https://docs.databunker.org/pro/api/session-management/get-session /pro/api/openapi.yml post /v2/SessionGet Retrieves information about a specific session # List user sessions Source: https://docs.databunker.org/pro/api/session-management/list-user-sessions /pro/api/openapi.yml post /v2/SessionListUserSessions Lists all sessions for a specific user # Upsert session Source: https://docs.databunker.org/pro/api/session-management/upsert-session /pro/api/openapi.yml post /v2/SessionUpsert Creates or updates a user session # Create shared record Source: https://docs.databunker.org/pro/api/shared-records/create-shared-record /pro/api/openapi.yml post /v2/SharedRecordCreate Creates a shared record for a user with specific fields # Get shared record Source: https://docs.databunker.org/pro/api/shared-records/get-shared-record /pro/api/openapi.yml post /v2/SharedRecordGet Retrieves a shared record by its UUID # Delete user profiles across all tenants Source: https://docs.databunker.org/pro/api/system-operations/delete-user-profiles-across-all-tenants /pro/api/openapi.yml post /v2/SystemDeleteUserProfiles Deletes all profiles for a user identified by email, phone, login, custom field, or token across all tenants. An optional `tenantid` or `tenantname` parameter can restrict deletion to a single tenant. The `token` mode is only allowed when `tenantid` or `tenantname` is specified. Only accessible by the main tenant admin (tenantID=1). Requires a bulk list unlock UUID obtained from `BulkListUnlock`. Deleted records are preserved in version history and can be restored with `SystemRestoreUserProfile`. # Generate wrapping key from Shamir's Secret Sharing keys Source: https://docs.databunker.org/pro/api/system-operations/generate-wrapping-key-from-shamirs-secret-sharing-keys /pro/api/openapi.yml post /v2/SystemGenerateWrappingKey Generates a wrapping key from three Shamir's Secret Sharing keys # Get system statistics Source: https://docs.databunker.org/pro/api/system-operations/get-system-statistics /pro/api/openapi.yml post /v2/SystemGetSystemStats Retrieves system statistics including user counts, tenant counts, and other metrics # Get user HTML report Source: https://docs.databunker.org/pro/api/system-operations/get-user-html-report /pro/api/openapi.yml post /v2/SystemGetUserHTMLReport Generates an HTML report for a specific user # Get user profiles across all tenants Source: https://docs.databunker.org/pro/api/system-operations/get-user-profiles-across-all-tenants /pro/api/openapi.yml post /v2/SystemGetUserProfiles Retrieves all profiles for a user identified by email, phone, login, or custom field across all tenants. Only accessible by the main tenant admin (tenantID=1). The `token` mode is not supported. Requires a bulk list unlock UUID obtained from `BulkListUnlock`. # Get user report Source: https://docs.databunker.org/pro/api/system-operations/get-user-report /pro/api/openapi.yml post /v2/SystemGetUserReport Generates a detailed report for a specific user # Restore a deleted user profile Source: https://docs.databunker.org/pro/api/system-operations/restore-a-deleted-user-profile /pro/api/openapi.yml post /v2/SystemRestoreUserProfile Restores a previously deleted user profile for a specific tenant from version history. The caller must provide the user `token` and either `tenantid` or `tenantname`. Only accessible by the main tenant admin (tenantID=1). Requires a bulk list unlock UUID obtained from `BulkListUnlock`. # Search user profiles across all tenants Source: https://docs.databunker.org/pro/api/system-operations/search-user-profiles-across-all-tenants /pro/api/openapi.yml post /v2/SystemSearchUserProfiles Fuzzy-searches for user profiles across all tenants by identity. The search mode is auto-detected from the `identity` value: - If `identity` contains `@`, it is treated as an email search - Otherwise it searches across login, phone, and custom fields Only accessible by the main tenant admin (tenantID=1). Requires a bulk list unlock UUID obtained from `BulkListUnlock`. # Set the license key Source: https://docs.databunker.org/pro/api/system-operations/set-the-license-key /pro/api/openapi.yml post /v2/SystemSetLicenseKey Applies a new license key to a running instance. Only the main tenant administrator (tenant id `1`) may call this. The key is validated before it is saved — an invalid or expired key is rejected and the existing license is left in place. # Create a new tenant Source: https://docs.databunker.org/pro/api/tenant-management/create-a-new-tenant /pro/api/openapi.yml post /v2/TenantCreate Creates a new tenant for multi-tenant setups # Delete a tenant Source: https://docs.databunker.org/pro/api/tenant-management/delete-a-tenant /pro/api/openapi.yml post /v2/TenantDelete Deletes a tenant and its records. The system tenant (id `1`) cannot be deleted. # Get tenant information Source: https://docs.databunker.org/pro/api/tenant-management/get-tenant-information /pro/api/openapi.yml post /v2/TenantGet Retrieves information about a specific tenant # List all tenants Source: https://docs.databunker.org/pro/api/tenant-management/list-all-tenants /pro/api/openapi.yml post /v2/TenantListTenants Retrieves a list of all tenants in the system # Update tenant information Source: https://docs.databunker.org/pro/api/tenant-management/update-tenant-information /pro/api/openapi.yml post /v2/TenantUpdate Updates information about a specific tenant # Approve user request Source: https://docs.databunker.org/pro/api/user-tokenization/approve-user-request /pro/api/openapi.yml post /v2/UserRequestApprove Approves a pending user request # Cancel user request Source: https://docs.databunker.org/pro/api/user-tokenization/cancel-user-request /pro/api/openapi.yml post /v2/UserRequestCancel Cancels a pending user request # Create a new user token Source: https://docs.databunker.org/pro/api/user-tokenization/create-a-new-user-token /pro/api/openapi.yml post /v2/UserCreate Creates a new user token with profile information and optional group/role assignment # Create multiple users in bulk Source: https://docs.databunker.org/pro/api/user-tokenization/create-multiple-users-in-bulk /pro/api/openapi.yml post /v2/UserCreateBulk Creates multiple users with their profiles and group information # Delete multiple users Source: https://docs.databunker.org/pro/api/user-tokenization/delete-multiple-users /pro/api/openapi.yml post /v2/UserDeleteBulk Deletes several user records in one request. Each entry identifies a user by an indexed field. Entries that match no record are skipped, so `deleted` can be lower than `total`. # Delete user Source: https://docs.databunker.org/pro/api/user-tokenization/delete-user /pro/api/openapi.yml post /v2/UserDelete Deletes a user and their associated data # Get user information Source: https://docs.databunker.org/pro/api/user-tokenization/get-user-information /pro/api/openapi.yml post /v2/UserGet Retrieves user information by login, token, or other identifiers # Get user request Source: https://docs.databunker.org/pro/api/user-tokenization/get-user-request /pro/api/openapi.yml post /v2/UserRequestGet Retrieves information about a specific user request # List user requests Source: https://docs.databunker.org/pro/api/user-tokenization/list-user-requests /pro/api/openapi.yml post /v2/UserRequestListUserRequests Lists all requests for a specific user # List user versions Source: https://docs.databunker.org/pro/api/user-tokenization/list-user-versions /pro/api/openapi.yml post /v2/UserListVersions Lists all versions of a user's profile # Patch user profile using JSON Patch Source: https://docs.databunker.org/pro/api/user-tokenization/patch-user-profile-using-json-patch /pro/api/openapi.yml post /v2/UserPatch Updates user profile using JSON Patch operations (RFC 6902) # Request user deletion Source: https://docs.databunker.org/pro/api/user-tokenization/request-user-deletion /pro/api/openapi.yml post /v2/UserDeleteRequest Creates a deletion request for a user (requires approval) # Request user patch Source: https://docs.databunker.org/pro/api/user-tokenization/request-user-patch /pro/api/openapi.yml post /v2/UserPatchRequest Creates a patch request for a user (requires approval) # Request user update Source: https://docs.databunker.org/pro/api/user-tokenization/request-user-update /pro/api/openapi.yml post /v2/UserUpdateRequest Creates an update request for a user (requires approval) # Search users Source: https://docs.databunker.org/pro/api/user-tokenization/search-users /pro/api/openapi.yml post /v2/UserSearch Searches for users using fuzzy matching. The search mode is auto-detected from the `identity` value: - If `identity` contains `@`, it is treated as an email search - Otherwise it searches across login, phone, and custom fields # Update user profile Source: https://docs.databunker.org/pro/api/user-tokenization/update-user-profile /pro/api/openapi.yml post /v2/UserUpdate Updates user profile information # AWS Cognito vs Databunker Pro — PII Vault & Tokenization Source: https://docs.databunker.org/pro/comparisons/aws-cognito-alternative LLM-built auth plus Databunker Pro — the modern replacement for AWS Cognito, with self-hosted PII vaulting and compliance built in. AWS Cognito was built in 2014, when standing up authentication — sign-in, password reset, OAuth, SSO federation, JWT issuance — was genuinely a multi-month project. That world is gone. With LLM-assisted development and modern auth libraries, the auth layer is now an afternoon's work. What's actually hard in 2026 is the part Cognito doesn't solve: **encrypting PII at rest, tokenising sensitive fields, tracking consent, handling DSARs, proving compliance to an auditor, and meeting cross-border data-localisation laws.** **Databunker Pro + LLM-built auth** is the modern replacement for Cognito. You build the auth glue once, in your own codebase, with full control. Databunker Pro handles everything Cognito can't: the PII vault, format-preserving tokenization, consent management, audit, and compliance — self-hosted in any cloud, on-premises, or across jurisdictions. ## Authentication is now an afternoon, not a project LLMs (Claude, Cursor, Copilot, GitHub Codespaces) scaffold a complete auth system from a single prompt: email/password sign-up, Google / Microsoft / Apple SSO, JWT sessions with refresh, password reset, MFA via TOTP or magic links, account recovery. Pair that with a well-maintained library and you have a production-ready auth layer in hours, not months. A non-exhaustive list of mature, well-documented auth libraries that pair cleanly with LLM-driven implementation: | Stack | Library | | - | - | | Node / Next.js | [NextAuth.js / Auth.js](https://authjs.dev/), [Lucia](https://lucia-auth.com/), [Passport.js](https://www.passportjs.org/) | | Python | [Authlib](https://authlib.org/), [FastAPI Users](https://fastapi-users.github.io/fastapi-users/) | | Go | [Ory Kratos](https://www.ory.sh/kratos/), [GoTrue](https://github.com/supabase/gotrue) | | Multi-language | [Keycloak](https://www.keycloak.org/), [Ory](https://www.ory.sh/), [Authelia](https://www.authelia.com/) | Any of these, combined with an LLM that knows your codebase, produces a working auth system the same day you start. The deliverable is yours — no per-MAU bill, no vendor lock-in, no AWS dependency. ## What auth doesn't solve — and Databunker Pro does The auth layer issues identity tokens. It does **not** answer: * **Where do you store your users' PII so it isn't exposed in logs, backups, or a SQL injection?** * **How do you tokenise credit-card numbers to shrink PCI scope?** * **How do you fulfil a GDPR / DPDPA right-to-erasure request across every system that holds the user's data?** * **How do you prove to an auditor that every PII access was authorised and logged?** * **How do you keep Indian users' PII in India, Russian users' PII in Russia, and EU users' PII in the EU — all simultaneously?** These are the hard problems. Databunker Pro is built for them: * **[PII Vault](/pro/get-started/pii-vault)** — AES-256 per-record encryption; the application stores only UUID tokens, never PII. * **[Format-preserving tokenization](/pro/concepts/tokenization)** — Luhn-valid credit-card tokens, integer tokens, timestamp tokens. Real PCI-scope reduction. * **Consent management** — legal-basis tracking, user agreements, processing-activity records aligned with GDPR / DPDPA. * **DPO operations** — DSAR fulfilment, right-to-erasure, data-portability via the separate [Databunker DPO product](https://databunker.org/use-case/dpo-management-portal/). * **Audit trail** — per-record, per-field, with encrypted PII context. See [Access control](/pro/administration/access-control). * **[Multi-tenancy](/pro/administration/multi-tenancy)** — PostgreSQL row-level security; cryptographic per-domain isolation. * **[Record versioning](/pro/concepts/record-versioning)** — immutable history for every user record. * **[Fuzzy search](/pro/concepts/fuzzy-search)** — typo-tolerant search on encrypted data. * **[Shared records](/pro/concepts/shared-records)** — time-limited UUID references for safe cross-system sharing. * **[Shamir secret sharing](/pro/administration/shamir-keys)** — master-key recovery split across multiple custodians. * **BYOK / HYOK** — wrapping key in Kubernetes secret, AWS KMS, HashiCorp Vault, or hardware HSM. * **[Multi-jurisdiction deployment](/pro/concepts/global-deployment)** — one vault per jurisdiction (India, Russia, Turkey, EU, etc.) — a topology Cognito cannot match because Cognito is AWS-bound. * **Self-hosted** — deploy on any cloud, on-premises, in a sovereign region, or inside a customer's tenant. * **[Predictable pricing](/pro/get-started/performance)** — per-instance license, flat regardless of user count. No per-MAU bill. ## Reference architecture ```text theme={null} [ User ] ─── sign-in ───► [ Your auth layer (NextAuth / Lucia / Ory / Keycloak / ...) ] │ Built once with LLM assistance. Issues JWT / session. │ ▼ [ Your application ] │ ▼ [ Databunker Pro ] AES-256 encrypted vault Tokenization · CRBAC · audit Self-hosted, any region ``` The application database only ever stores: a user identifier, a Databunker `user_token`, and any non-PII business data. PII lives in the vault. Auth lives in your own code. ## Comparison table | Capability | AWS Cognito | Databunker Pro + your auth | | - | - | - | | **Primary purpose** | Auth + user directory | PII vault, tokenization, consent, compliance | | **Where auth lives** | Managed AWS service | In your codebase (LLM-built, mature library) | | **Where PII lives** | Cognito user attributes (AWS) | Databunker Pro vault (your infra, any cloud) | | **PII encryption** | AWS-managed KMS at the user-pool level | AES-256 per record, FIPS 140-2, customer-controlled keys | | **Tokenization (UUID + format-preserving)** | ❌ | ✅ Native; shrinks PCI scope | | **Consent management & legal basis** | ❌ | ✅ Native (GDPR / DPDPA aligned) | | **Right-to-erasure** | `AdminDeleteUser` (PII in logs/backups still your problem) | Single API call; audit-bounded; record-versioning aware | | **Audit trail** | CloudTrail (API-level) | Per-record, per-field, with encrypted PII context | | **Fuzzy search on encrypted data** | ❌ | ✅ | | **Record versioning** | ❌ | ✅ | | **Customer-held keys (BYOK / HYOK)** | KMS CMK option, AWS-bound | K8s secret, AWS KMS, HashiCorp Vault, or hardware HSM | | **Multi-tenancy** | Separate user pools | Native PostgreSQL RLS | | **Deployment** | AWS only | Any cloud, on-prem, sovereign region, customer tenant | | **Data residency** | AWS regions | Any region; [multi-jurisdiction topology](/pro/concepts/global-deployment) supported | | **Vendor lock-in** | AWS | None — Docker / Helm artifacts | | **Pricing model** | Per MAU above the free tier | Per-instance license, flat | | **Future flexibility** | Constrained by what AWS adds to Cognito | Your codebase — change auth library, add MFA mode, swap SSO provider any time | ## Migration from Cognito For the full procedure — export script, attribute mapping, verification, and rollback — see [Migrate from AWS Cognito](/pro/migrations/aws-cognito). The honest practical answer: **Cognito does not allow exporting password hashes**, so a migration is necessarily a forced-reset event. The standard playbook: 1. **Stand up Databunker Pro** in your target environment (Docker / Helm). 2. **Build the replacement auth layer** in your codebase using an LLM and the library of your choice (NextAuth, Lucia, Ory, Keycloak, etc.). Wire it to Databunker Pro for the user record. 3. **Export the Cognito user list** — emails, attributes, group memberships — via `ListUsers`. 4. **Bulk-import into Databunker Pro** using [`UserCreateBulk`](/pro/get-started/performance) — at \~1,700 records/sec on a single instance, a typical Cognito directory imports in minutes. 5. **Migration window**: switch the auth layer to your replacement and force a one-time password reset email to every user (unavoidable — Cognito does not expose hashes). 6. **Decommission the Cognito user pool** once the population has migrated. For organisations with strict downtime / UX constraints, a **dual-running window** (Cognito for existing users, new auth + Databunker for new ones, slow migration over weeks) is preferred. Databunker Pro's bulk import and multi-tenancy support this naturally. ## Code examples ### Sign-up: auth in your codebase, PII in Databunker ```javascript theme={null} // 1. User signs up via your auth layer (NextAuth / Lucia / Ory / etc.) // Your auth issues a session and gives you the verified email. // 2. Store PII in Databunker — get back a safe UUID token const response = await axios.post('https://your-databunker/v2/UserCreate', { profile: { email: form.email, first: form.firstName, last: form.lastName, phone: form.phone, address: form.address, dob: form.dateOfBirth, } }, { headers: { 'X-Bunker-Token': process.env.DATABUNKER_API_KEY } }); const userToken = response.data.token; // 3. Store only (userId, userToken) in your app DB — zero PII anywhere outside the vault await db.query( 'INSERT INTO users (id, databunker_token) VALUES ($1, $2)', [authUser.id, userToken] ); ``` If your application database gets breached, attackers see only opaque UUIDs — no PII, no contact data, no addresses. ### Format-preserving credit-card tokenization Cognito has no concept of this. Databunker Pro tokenises a real card number into a Luhn-valid token that passes format validation in downstream systems — so legacy fraud / payment / risk systems keep working without ever seeing the real card. ```bash theme={null} curl -X POST https://your-databunker/v2/TokenCreate \ -H "X-Bunker-Token: YOUR_API_KEY" \ -d '{ "record": "4532015112830366", "tokentype": "creditcard", "slidingtime": "30d", "unique": true }' ``` ```json theme={null} { "status": "ok", "tokenuuid": "550e8400-e29b-41d4-a716-446655440000", "tokenbase": "4024007186539112" } ``` `tokenbase` passes Luhn checks and 16-digit format validation, but maps to no real card. PCI audit scope shrinks to the systems that genuinely need detokenisation. ## The bottom line Cognito was the right answer when authentication was a hard build. With LLM-assisted development, auth is an afternoon's work in your own codebase — and **you keep the code, the keys, the deployment, and the data**. Pair that with Databunker Pro and you get the secure user storage, tokenization, consent management, audit, and cross-jurisdiction sovereignty that Cognito was never designed to provide. The result: no per-MAU bill, no AWS lock-in, full control over your users' PII, and a compliance posture that holds up in a regulator review. ## Next steps * [Migrate from AWS Cognito](/pro/migrations/aws-cognito) — export the pool, import into the vault, cut over authentication * [Quickstart](/pro/get-started/quickstart) — a running vault and a first API call from one `docker run` * [Licensing and limits](/pro/get-started/licensing) — what a record is, and what the licence caps # Custom PII Vault vs Databunker Pro — Build or Buy? Source: https://docs.databunker.org/pro/comparisons/custom-solution-alternative What it actually takes to build a PII vault from scratch — and why most teams underestimate the effort by 10x. When teams first encounter the PII storage problem, the instinct is often: "We'll build it ourselves. It's just encryption and a database." That's how it starts. Then come the edge cases, the compliance requirements, and the features you didn't know you needed until an auditor asked for them. **Databunker Pro gives you a production-ready PII vault in a day.** Building the equivalent yourself takes months of engineering — and the ongoing maintenance never stops. ## What looks simple at first A basic encrypted user store seems straightforward: ```python theme={null} import json from cryptography.fernet import Fernet key = Fernet.generate_key() cipher = Fernet(key) def store_user(db, user_data): encrypted = cipher.encrypt(json.dumps(user_data).encode()) token = str(uuid.uuid4()) db.execute("INSERT INTO users (token, data) VALUES (%s, %s)", (token, encrypted)) return token def get_user(db, token): row = db.execute("SELECT data FROM users WHERE token = %s", (token,)).fetchone() return json.loads(cipher.decrypt(row[0])) ``` That's maybe 20 lines. Ship it. Done. Except it's not done. Here's what you'll need to build next. ## What you'll actually need to build ### 1. Key management Your encryption key is a single point of failure. You need: * A wrapping key to protect the master key * Key rotation without re-encrypting every record * A recovery mechanism if the key is lost (Shamir's secret sharing or similar) * Secure key storage that isn't just an environment variable Databunker Pro handles this with a master key, wrapping key rotation via API, and Shamir key sharing for recovery — built in from day one. ### 2. Searchable encrypted records Your first implementation can look up users by token. But then someone needs to find a user by email. Or phone number. Now you need: * A secure hash-based search index * Indexes that don't leak plaintext but still allow lookups * Support for multiple lookup fields (email, phone, login, custom fields) ```bash theme={null} # Databunker Pro — look up by email, phone, or token curl -X POST https://your-databunker/v2/UserGet \ -H "X-Bunker-Token: YOUR_API_KEY" \ -d '{"mode": "email", "identity": "john@example.com"}' curl -X POST https://your-databunker/v2/UserGet \ -H "X-Bunker-Token: YOUR_API_KEY" \ -d '{"mode": "phone", "identity": "+1-555-123-4567"}' ``` Building a secure search index that doesn't leak data is a research-level problem. Databunker Pro uses hash-based lookups that enable search without exposing plaintext. ### 3. Tokenization engine Beyond user profiles, you need to tokenize individual fields — credit card numbers, SSNs, health identifiers. And the tokens need to: * Preserve format for downstream systems (Luhn-valid card numbers, same-length strings) * Support deduplication (same input produces same token) * Have configurable expiration * Handle bulk operations at scale ```bash theme={null} # Databunker Pro — format-preserving credit card tokenization curl -X POST https://your-databunker/v2/TokenCreate \ -H "X-Bunker-Token: YOUR_API_KEY" \ -d '{ "record": "4532015112830366", "tokentype": "creditcard", "slidingtime": "30d", "unique": true }' ``` ```json theme={null} { "status": "ok", "tokenuuid": "550e8400-e29b-41d4-a716-446655440000", "tokenbase": "4024007186539112" } ``` Building a format-preserving tokenization engine that passes Luhn validation and handles millions of records is a significant engineering effort on its own. ### 4. Consent management GDPR Article 6 and the DPDP Act require you to record the legal basis for processing each person's data. You need: * A consent store linked to each user record * Support for multiple consent types (marketing, analytics, data sharing) * Consent withdrawal tracking * Timestamped audit trail of consent changes Most custom implementations skip this entirely — until the first compliance audit. ### 5. Audit trail Every access, modification, and deletion of PII needs to be logged. Not application logs — a tamper-resistant audit trail that: * Records who accessed what data, when, and why * Encrypts PII within the audit events themselves * Is queryable by a DPO or auditor * Can't be modified or deleted by application code ### 6. Data subject requests GDPR and DPDP Act give users the right to access, correct, and delete their data. You need: * **Right to access** — return all data you hold for a specific person * **Right to erasure** — delete everything for one user across all stores * **Right to portability** — export a user's data in a machine-readable format * **Right to rectification** — update a user's data across all linked records ```javascript theme={null} // Databunker Pro — full erasure in one call await axios.post('https://your-databunker/v2/UserDelete', { mode: 'token', identity: userToken }, { headers: { 'X-Bunker-Token': process.env.DATABUNKER_API_KEY } }); ``` In a custom solution, you need to track every table, every cache, every log file, and every downstream system that might contain a copy of a user's PII. ### 7. Record versioning and expiration Regulators may ask: "What data did you hold for this user six months ago?" You need: * Version history for every user record * Ability to retrieve a specific version * Automatic expiration (sliding and absolute TTLs) for data minimization * Proof that expired records were actually deleted ### 8. Multi-tenancy If you serve multiple customers or operate in multiple regions, you need tenant isolation: * Data from tenant A must never be visible to tenant B * Queries must be scoped by tenant at the database level (not just application logic) * Each tenant may need separate encryption keys Databunker Pro implements this with PostgreSQL row-level security — true database-level isolation, not application-layer filtering that a bug can bypass. ### 9. Access control Different services and team members need different levels of access: * Role-based policies (admin, read-only, tokenize-only) * API token management with scoped permissions * Rate limiting and abuse prevention ### 10. DPO portal Your Data Protection Officer needs a UI to handle data subject requests, review audit logs, and demonstrate compliance. Building an admin portal is another project entirely. ## The real cost comparison | | Custom solution | Databunker Pro | | - | - | - | | **Initial build** | 3-6 months of senior engineering | Deploy in a day | | **Encryption + key management** | Build from scratch | Built-in (AES-256, Shamir, key rotation) | | **Searchable encrypted records** | Research-level problem | Built-in hash-based indexes | | **Format-preserving tokenization** | Significant engineering effort | One API call | | **Consent management** | Usually skipped, then rushed before audit | Built-in | | **Audit trail** | Custom implementation | Built-in, compliance-ready | | **Data subject requests** | Manual process across all data stores | Single API calls | | **Record versioning** | Custom implementation | Built-in | | **Auto-expiration** | Custom cron jobs and cleanup logic | Built-in TTLs | | **Multi-tenancy** | Application-layer filtering (bug-prone) | PostgreSQL row-level security | | **DPO portal** | Separate project | Built-in | | **Ongoing maintenance** | Your team, indefinitely | Managed upgrades | | **Compliance confidence** | Hope it holds up in an audit | Designed for GDPR, DPDP Act, HIPAA, SOC 2 | ## The hidden costs of building your own Beyond the initial build, a custom PII vault creates ongoing costs that teams rarely budget for: * **Security reviews** — every change to the encryption layer needs a security review * **Penetration testing** — custom crypto implementations are high-value targets * **Compliance updates** — new regulations (DPDP Act, state privacy laws) require new features * **Key rotation incidents** — when something goes wrong with key management at 2 AM * **Staff turnover** — the engineer who built the vault leaves, and nobody fully understands the code * **Audit preparation** — weeks of work assembling evidence for each compliance audit ## When a custom solution makes sense Building your own PII vault might be justified if: * You have unique requirements that no existing solution can meet * You have a dedicated security engineering team with cryptography expertise * You're willing to maintain the solution for years, including compliance updates * Your scale requires a fundamentally different architecture For most teams, those conditions don't apply. The PII vault is not where you want to differentiate — it's plumbing that needs to work correctly and compliantly so you can focus on your actual product. ## The bottom line The gap between a basic encrypted database and a production-ready PII vault is enormous. It includes key management, searchable encryption, tokenization, consent tracking, audit trails, data subject request handling, record versioning, multi-tenancy, access control, and a DPO portal. Teams that start building their own typically discover this gap six months in — after the first compliance audit, or the first data subject request they can't fulfill. Databunker Pro gives you all of this out of the box. Deploy it in a day, and spend your engineering time on the product your customers actually pay for. ## Next steps * [Quickstart](/pro/get-started/quickstart) — deploy and store a record in a few minutes * [Migrate a SQL users table](/pro/migrations/sql-users-table) — the path from your existing schema * [Performance and sizing](/pro/get-started/performance) — measured throughput, and how to size for your record count # HashiCorp Vault vs Databunker Pro — PII Storage & Compliance Source: https://docs.databunker.org/pro/comparisons/hashicorp-vault-alternative HashiCorp Vault manages infrastructure secrets. Databunker Pro is a PII vault purpose-built for personal data protection, tokenization, and privacy compliance. HashiCorp Vault is an infrastructure secrets manager — it stores API keys, database credentials, TLS certificates, and encryption keys. It's excellent at that job. But when teams try to use it as a PII vault for personal data, they quickly hit its limits. **Databunker Pro is purpose-built for PII.** It stores, encrypts, and tokenizes user records — names, emails, SSNs, credit cards, health data — with built-in consent management, audit trails, a DPO portal, and regulatory compliance out of the box. Vault was never designed for any of that. ## Vault is for infrastructure secrets, not personal data HashiCorp Vault solves a specific problem well: managing machine-to-machine secrets. It rotates database passwords, issues short-lived TLS certificates, and encrypts application data via its Transit engine. DevOps and platform teams rely on it for good reason. But PII is not an infrastructure secret. Personal data has regulatory requirements that Vault doesn't address: * **Data subject access requests** — a user asks "what data do you have on me?" Vault has no concept of a user profile or a way to retrieve all data belonging to one person. * **Right to erasure** — deleting all PII for one user across your system. In Vault, you'd have to track every secret path where you stored each user's data and delete them individually. * **Consent and legal basis tracking** — GDPR and DPDP Act require you to record why you're processing each person's data. Vault has no consent model. * **Data minimization** — storing only what's necessary, with automatic expiration. Vault secrets can have TTLs, but there's no concept of user record lifecycle management. * **Audit for compliance** — Vault logs access events, but not in a format an auditor or DPO can use to demonstrate privacy compliance. ## What Databunker Pro gives you that Vault doesn't Databunker Pro is a **complete PII protection platform**, not a generic secrets store adapted for personal data: * **User-centric data model** — store complete user profiles as JSON, look them up by email, phone, login, or token * **Format-preserving tokenization** — Luhn-valid credit card tokens, integer tokens, timestamp tokens — not just opaque UUIDs * **Consent management** — track legal basis, user agreements, and processing operations for GDPR/DPDP Act * **DPO portal** — built-in interface for Data Protection Officers to handle access, erasure, and portability requests * **Record versioning** — full version history for every user record, not just current state * **Auto-expiration** — sliding and absolute TTLs for automatic data deletion (data minimization by design) * **Fuzzy search** — search encrypted PII records without decrypting the database * **Multi-tenancy** — native row-level isolation in PostgreSQL, not namespace-based separation * **Simple API** — one call to store a user, one call to retrieve, one call to delete. No policy authoring, no mount configuration, no unseal ceremony * **Audit trail** — every API call logged with encrypted PII context, ready for compliance review ## Comparison table | Capability | Databunker Pro | HashiCorp Vault | | - | - | - | | **Primary purpose** | PII vault, tokenization & compliance | Infrastructure secrets management | | **Data model** | User profiles (JSON), searchable by email/phone/token | Key-value secrets, no user concept | | **Tokenization** | UUID + format-preserving (credit cards, integers, timestamps) | Transform engine (Enterprise only) | | **Format-preserving tokenization** | Built-in, Luhn-valid credit card tokens | Enterprise license required, limited formats | | **Consent management** | Built-in legal basis & agreement tracking | None | | **DPO portal** | Built-in | None | | **Right to erasure** | Single API call deletes all user data | Manual — find and delete each secret path | | **Data subject access requests** | Single API call returns full user profile | No user concept — manual aggregation | | **Record versioning** | Built-in version history per user | KV v2 has versioning, but no user-level grouping | | **Audit trail** | Field-level, compliance-ready | API-level, designed for security ops | | **Auto-expiration (data minimization)** | Sliding and absolute TTLs per user record | Secret TTLs, but no user lifecycle management | | **Fuzzy search on encrypted data** | Supported | Not available | | **PII encryption** | AES-256 per-record, FIPS 140-2 compliant | Transit engine encrypts data, but stores ciphertext externally | | **Multi-tenancy** | Native row-level isolation (PostgreSQL) | Namespaces (Enterprise only) | | **Operational complexity** | Docker/Kubernetes deploy, no unseal process | Unseal ceremony, policy authoring, mount configuration | | **DPDP Act / GDPR / HIPAA** | Built-in compliance controls | No privacy-specific compliance features | | **Shamir key sharing** | Master key split for recovery | Unseal keys via Shamir | | **Bulk operations** | Bulk tokenization & export via API | No bulk PII operations | | **Deployment** | Self-hosted, any infrastructure | Self-hosted or HCP Vault (HashiCorp Cloud) | | **License** | Commercial | BSL 1.1 (source-available, not open source) | ## Code examples ### Storing a user profile in Vault (the workaround) Vault has no user profile concept, so teams end up storing PII as KV secrets — manually building paths, with no search, no consent tracking, and no way to retrieve "all data for user X" without knowing every path: ```bash theme={null} # Store user PII as a KV secret — you manage the path structure vault kv put secret/users/john@example.com \ first="John" \ last="Doe" \ phone="+1-555-123-4567" \ ssn="123-45-6789" \ address="123 Main St" # Retrieve — you need to know the exact path vault kv get secret/users/john@example.com # Delete for GDPR erasure — hope you tracked every path vault kv delete secret/users/john@example.com # But what about secret/cards/john@example.com? # And secret/consents/john@example.com? # And secret/sessions/john@example.com? ``` No search by phone number. No consent tracking. No audit trail that a DPO can use. No auto-expiration for data minimization. You're building a PII vault from scratch on top of a secrets manager. ### Storing a user profile in Databunker Pro (purpose-built) ```javascript theme={null} const axios = require('axios'); // 1. Store a complete user profile — one API call const response = await axios.post('https://your-databunker/v2/UserCreate', { profile: { email: 'john@example.com', first: 'John', last: 'Doe', phone: '+1-555-123-4567', ssn: '123-45-6789', address: '123 Main St' } }, { headers: { 'X-Bunker-Token': process.env.DATABUNKER_API_KEY } }); const userToken = response.data.token; // "a21fa1d3-5e47-11ef-a729-32e05c6f6c16" // 2. Look up by email, phone, or token — built-in search const user = await axios.post('https://your-databunker/v2/UserGet', { mode: 'email', identity: 'john@example.com' }, { headers: { 'X-Bunker-Token': process.env.DATABUNKER_API_KEY } }); // 3. GDPR erasure — one call deletes everything for this user await axios.post('https://your-databunker/v2/UserDelete', { mode: 'token', identity: userToken }, { headers: { 'X-Bunker-Token': process.env.DATABUNKER_API_KEY } }); ``` Every operation is audited. Consent is tracked. The DPO can see it all in the portal. No path management, no policy authoring, no unseal ceremony. ### Tokenizing credit cards Vault's Transform engine (Enterprise only) can do format-preserving encryption, but it requires configuring roles, transformations, and templates. In Databunker Pro, it's one API call: ```bash theme={null} curl -X POST https://your-databunker/v2/TokenCreate \ -H "X-Bunker-Token: YOUR_API_KEY" \ -d '{ "record": "4532015112830366", "tokentype": "creditcard", "slidingtime": "30d", "unique": true }' ``` ```json theme={null} { "status": "ok", "tokenuuid": "550e8400-e29b-41d4-a716-446655440000", "tokenbase": "4024007186539112" } ``` A Luhn-valid token that passes format validation in downstream systems. Built-in expiration. Built-in deduplication. No Enterprise license required. ## When to use each **Use HashiCorp Vault** for infrastructure secrets: API keys, database credentials, TLS certificates, encryption-as-a-service via the Transit engine. That's what it was built for, and it does it well. **Use Databunker Pro** for personal data: user profiles, credit card numbers, health records, any PII that has regulatory requirements around storage, access, consent, and deletion. They can coexist in the same stack — Vault for machine secrets, Databunker Pro for human data. But don't try to make Vault do a PII vault's job. You'll end up building half of Databunker Pro yourself on top of Vault's KV engine, without the compliance features, without the DPO portal, and without the audit trail that regulators actually need. ## The bottom line HashiCorp Vault is a great secrets manager. It's not a PII vault. If you need to store personal data with encryption, tokenization, consent tracking, data subject request handling, and regulatory compliance, you need a tool that was designed for that from the ground up. That's Databunker Pro. ## Next steps * [Quickstart](/pro/get-started/quickstart) — try the API against a throwaway instance * [Master key](/pro/administration/master-key) — the key model, and how it differs from Vault's * [Migrate a SQL users table](/pro/migrations/sql-users-table) — moving existing records in # File Vault Source: https://docs.databunker.org/pro/concepts/file-vault Store per-user files encrypted at rest, backed by local disk, Amazon S3, Google Cloud Storage, or Azure Blob Storage — with the same key management, multi-tenancy, and access control as the rest of Databunker Pro. Databunker Pro can store files, not just structured records. Each file is attached to a user, encrypted at rest, and served back only through the API. This lets you keep documents such as ID scans, KYC paperwork, medical attachments, or exported reports under the same vault, audit trail, and access-control policies that protect the rest of a user's data. ## How encryption works Every file is encrypted with its own **per-file key**, which is in turn **wrapped by the user's record key**. Nothing is written to storage in the clear, and a file can only be decrypted through the vault. Because the file key is chained to the user's record key, file storage inherits two properties of the PII vault: * **Crypto-shredding on erasure** — deleting the user destroys the record key, which renders all of that user's files permanently unrecoverable. This is the mechanism behind GDPR "right to erasure" for attached documents. * **Shared key management** — the same key rotation, Shamir's secret sharing, multi-tenancy, and access control apply to files as to any other record. Encrypted objects are stored in a configurable backend: | Backend | Typical use | | - | - | | Local disk | Single-node or on-prem deployments | | Amazon S3 | AWS deployments | | Google Cloud Storage | GCP deployments | | Azure Blob Storage | Azure deployments | The storage backend only ever holds ciphertext — the keys live in the vault, not with the objects. ## API operations | Endpoint | Purpose | | - | - | | `FileCreate` | Store an encrypted file for a user | | `FileGet` | Retrieve and decrypt a file | | `FileListUserFiles` | List a user's files (metadata only) | | `FileDelete` | Remove a file's object and metadata | Every call identifies the owning user with a `mode` (`login`, `token`, `email`, `phone`, or `custom`) and the matching `identity`. ## Store a file File content is supplied as a base64-encoded `filedata` field. The MIME type is auto-detected when `mimetype` is omitted. ```bash theme={null} curl -X POST https://databunker.pro/v2/FileCreate \ -H "X-Bunker-Token: " \ -H "X-Bunker-Tenant: " \ -H "Content-Type: application/json" \ -d '{ "mode": "email", "identity": "user@example.com", "filename": "passport.pdf", "filedata": "JVBERi0xLjQKJ...", "slidingtime": "1y" }' ``` Output: ```json theme={null} { "status": "ok", "token": "550e8400-e29b-41d4-a716-446655440000", "fileuuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "duplicate": false } ``` If the same content is uploaded again for the same user, no new object is written and the response sets `"duplicate": true`. ## Retrieve a file Select a file by `fileuuid` (preferred) or by `filename` — when selecting by name, the most recently created file with that name is returned. By default the content comes back as a base64-encoded `filedata` field: ```bash theme={null} curl -X POST https://databunker.pro/v2/FileGet \ -H "X-Bunker-Token: " \ -H "X-Bunker-Tenant: " \ -H "Content-Type: application/json" \ -d '{ "mode": "email", "identity": "user@example.com", "fileuuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" }' ``` ```json theme={null} { "status": "ok", "fileuuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "filename": "passport.pdf", "mimetype": "application/pdf", "size": 20481, "filedata": "JVBERi0xLjQKJ..." } ``` For direct downloads, set `"raw": true` to receive the decrypted bytes with the appropriate `Content-Type` and `Content-Disposition` headers instead of a JSON envelope. ## List a user's files `FileListUserFiles` returns metadata only — never file content: ```bash theme={null} curl -X POST https://databunker.pro/v2/FileListUserFiles \ -H "X-Bunker-Token: " \ -H "X-Bunker-Tenant: " \ -H "Content-Type: application/json" \ -d '{ "mode": "email", "identity": "user@example.com" }' ``` ```json theme={null} { "status": "ok", "files": [ { "fileuuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890", "filename": "passport.pdf", "mimetype": "application/pdf", "size": 20481, "creationtime": 1751980800 } ] } ``` ## Delete a file `FileDelete` removes both the stored object and its metadata: ```bash theme={null} curl -X POST https://databunker.pro/v2/FileDelete \ -H "X-Bunker-Token: " \ -H "X-Bunker-Tenant: " \ -H "Content-Type: application/json" \ -d '{ "mode": "email", "identity": "user@example.com", "fileuuid": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" }' ``` ## Retention and expiration Files support the same expiration model as tokens. Set `slidingtime` for a relative retention window (e.g. `30d`, `1y`) or `finaltime` for an absolute cutoff (e.g. `90d`, `2026-01-01`). This lets you enforce document retention policies automatically instead of tracking expiry in your own application. ## Next steps * [PII vault](/pro/get-started/pii-vault) — the user record a file is attached to * [Access control](/pro/administration/access-control) — who may upload, list, and download * [Backup and recovery](/pro/administration/backup-and-recovery) — files are covered by the same key model # Fuzzy search Source: https://docs.databunker.org/pro/concepts/fuzzy-search Fuzzy search finds user records when the search term does not match exactly — a misspelled name, a partial email, a phone number in a different format. It is used where a human is doing the searching: support desks, admin consoles, and deduplication during a migration. ## What Problems Does Fuzzy Search Solve? ### 1. **User Experience Enhancement** * ✅ Handles typos and misspellings in search queries * ✅ Enables partial matching for incomplete user data * ✅ Provides intelligent suggestions for user lookup * ✅ Reduces failed searches due to exact-match requirements ### 2. **Data Quality Challenges** * ✅ Works with inconsistent data entry formats * ✅ Handles variations in user-provided information * ✅ Accommodates different naming conventions * ✅ Supports legacy data with formatting inconsistencies ### 3. **Administrative Efficiency** * ✅ Enables quick user discovery in large datasets * ✅ Reduces support tickets from failed user lookups * ✅ Improves admin interface usability * ✅ Supports bulk operations with approximate matching ## How Fuzzy Search Works Databunker Pro's fuzzy search implementation uses advanced algorithms to find users based on similarity rather than exact matches. The system analyzes multiple user attributes and returns results ranked by relevance. ### Supported Search Modes | Search Mode | Description | Use Case | | - | - | - | | `login` | Searches user login names | Finding users by username variations | | `email` | Searches email addresses | Locating users with email typos | | `phone` | Searches phone numbers | Finding users with phone variations | | `custom` | Searches by custom index | Funding users with custom variations | ## API Usage ### Prerequisites Before performing fuzzy searches, you need to: 1. **Create a Bulk List Unlock**: Required for security and audit purposes — see the [bulk-unlock UUID reference](/pro/api/authentication#bulk-unlock-uuid) 2. **Obtain proper permissions**: Ensure your token has search capabilities 3. **Prepare search parameters**: Define search mode and criteria ### Basic Fuzzy Search Request ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/UserSearch" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "mode": "login", "identity": "user0", "unlockuuid": "your-unlock-uuid" }' ``` ### JavaScript/TypeScript Example (Using Official SDK) ```javascript theme={null} // ES Modules import DatabunkerproAPI from "databunkerpro-js"; // CommonJS // const { DatabunkerproAPI } = require('databunkerpro-js'); // Initialize the client const client = new DatabunkerproAPI( "https://your-databunker-instance.com", "your-token" ); // Step 1: Create bulk list unlock const unlockResponse = await client.bulkListUnlock(); const unlockUUID = unlockResponse.unlockuuid; // Step 2: Perform fuzzy search const searchResponse = await client.userSearch({ mode: "login", identity: "user0", unlockuuid: unlockUUID, }); // Process results if (searchResponse.status === "ok") { const users = searchResponse.rows; console.log(`Found ${users.length} matching users`); users.forEach((user) => { const profile = user.profile; console.log(`User: ${profile.login} - ${profile.email}`); }); } ``` ### Python Example (Using Official SDK) ```python theme={null} from databunkerpro import DatabunkerproAPI # Initialize the client api = DatabunkerproAPI( base_url="https://your-databunker-instance", x_bunker_token="YOUR_ACCESS_TOKEN", x_bunker_tenant="your-tenant-name" # Optional for multi-tenant setups ) # Step 1: Create bulk list unlock unlock_response = api.bulk_list_unlock() unlock_uuid = unlock_response["unlockuuid"] # Step 2: Perform fuzzy search search_response = api.user_search( mode="login", identity="user0", unlockuuid=unlock_uuid ) if search_response["status"] == "ok": users = search_response["rows"] print(f"Found {len(users)} matching users") for user in users: profile = user["profile"] print(f"User: {profile['login']} - {profile['email']}") ``` ## Real-World Use Cases ### 1. **Customer Support** When customers contact support with partial or misspelled information, fuzzy search helps quickly locate their accounts: ### 2. **User Administration** Administrators can find users even with incomplete information: ### 3. **Data Migration** During system migrations, fuzzy search helps match records with slight variations: ## Security Considerations ### Access Control Fuzzy search respects Databunker Pro's Conditional Role-Based Access Control (CRBAC): * **Policy Enforcement**: Search results are filtered based on user permissions * **Audit Logging**: All search operations are logged for compliance * **Data Minimization**: Only authorized fields are returned in results ### Privacy Protection * **Encrypted Storage**: All user data remains encrypted during search operations * **Secure Transmission**: Search requests use HTTPS encryption * **Access Logging**: Complete audit trail of all search activities ## Error Handling ### Common Error Scenarios ```javascript theme={null} try { const searchResponse = await api.makeRequest("UserSearch", { mode: "login", identity: "nonexistent", unlockuuid: unlockUUID, }); if (searchResponse.status === "error") { console.log("Search failed:", searchResponse.message); } else if (searchResponse.rows.length === 0) { console.log("No matching users found"); } } catch (error) { console.error("Search request failed:", error); } ``` ## Official JavaScript/TypeScript SDK For JavaScript and TypeScript developers, we provide an official SDK that simplifies integration with Databunker Pro's fuzzy search capabilities. ### Installation ```bash theme={null} npm install databunkerpro-js ``` ### SDK Features The [Databunker Pro JavaScript client](https://github.com/securitybunker/databunkerpro-js) provides: * **TypeScript support** with full type definitions * **ES Modules and CommonJS** compatibility * **Comprehensive API coverage** for all Databunker Pro features * **Built-in error handling** and validation * **User Management** (create, read, update, delete) * **Token Management** * **Fuzzy Search capabilities** * **System Operations** ### Advanced JavaScript/TypeScript Example ```typescript theme={null} import DatabunkerproAPI from "databunkerpro-js"; class UserSearchService { private client: DatabunkerproAPI; private unlockUUID?: string; constructor(baseUrl: string, token: string) { this.client = new DatabunkerproAPI(baseUrl, token); } private async ensureUnlock(): Promise { if (!this.unlockUUID) { const response = await this.client.bulkListUnlock(); this.unlockUUID = response.unlockuuid; } return this.unlockUUID; } async searchUsers(mode: string, identity: string) { const unlockUUID = await this.ensureUnlock(); const response = await this.client.userSearch({ mode, identity, unlockuuid: unlockUUID, }); if (response.status !== "ok") { throw new Error(`Search failed: ${response.message || "Unknown error"}`); } return response.rows; } async findUserByEmail(email: string) { return this.searchUsers("email", email); } async findUserByLogin(login: string) { return this.searchUsers("login", login); } async findUserByPhone(phone: string) { return this.searchUsers("phone", phone); } } // Usage example const searchService = new UserSearchService( "https://your-databunker-instance.com", "your-token" ); // Search for users with error handling try { const users = await searchService.findUserByLogin("john"); console.log(`Found ${users.length} matching users`); users.forEach((user) => { const profile = user.profile; console.log(`Found: ${profile.login} - ${profile.email}`); }); } catch (error) { console.error("Search failed:", error.message); } ``` ## Official Python SDK For Python developers, we provide an official SDK that simplifies integration with Databunker Pro's fuzzy search capabilities. ### Installation ```bash theme={null} pip install databunkerpro ``` Or install directly from GitHub: ```bash theme={null} pip install git+https://github.com/securitybunker/databunkerpro-python.git ``` ### SDK Features The [Databunker Pro Python client](https://github.com/securitybunker/databunkerpro-python) provides: * **Type hints and comprehensive documentation** * **Error handling and validation** * **User Management** (create, read, update, delete) * **Token Management** * **Fuzzy Search capabilities** * **System Statistics** ### Advanced Python Example ```python theme={null} from databunkerpro import DatabunkerproAPI from typing import List, Dict, Optional class UserSearchService: def __init__(self, base_url: str, token: str, tenant: Optional[str] = None): self.api = DatabunkerproAPI( base_url=base_url, x_bunker_token=token, x_bunker_tenant=tenant ) self._unlock_uuid: Optional[str] = None def _ensure_unlock(self) -> str: """Ensure we have a valid unlock UUID""" if not self._unlock_uuid: response = self.api.bulk_list_unlock() self._unlock_uuid = response["unlockuuid"] return self._unlock_uuid def search_users(self, mode: str, identity: str) -> List[Dict]: """Search for users using fuzzy matching""" unlock_uuid = self._ensure_unlock() response = self.api.user_search( mode=mode, identity=identity, unlockuuid=unlock_uuid ) if response["status"] == "ok": return response["rows"] else: raise Exception(f"Search failed: {response.get('message', 'Unknown error')}") def find_user_by_email(self, email: str) -> List[Dict]: """Find users by email with fuzzy matching""" return self.search_users("email", email) def find_user_by_login(self, login: str) -> List[Dict]: """Find users by login with fuzzy matching""" return self.search_users("login", login) # Usage example search_service = UserSearchService( base_url="https://your-databunker-instance", token="YOUR_ACCESS_TOKEN", tenant="your-tenant-name" ) # Search for users users = search_service.find_user_by_login("john") for user in users: profile = user["profile"] print(f"Found: {profile['login']} - {profile['email']}") ``` ## Integration Examples The JavaScript/TypeScript examples above can be easily adapted for any frontend framework (React, Vue, Angular) or backend environment (Node.js, Deno, Bun). The core API integration pattern remains the same across all environments. ## Performance Fuzzy search is **not covered by the published [benchmarks](/pro/get-started/performance)**, which measure the exact-match write and detokenisation paths only. Unlike a lookup by token or email — a hashed-index point read at \~14 ms — approximate matching cannot use those indexes, so cost grows with the number of records examined. Restrict it to administrative interfaces and measure it against your own data before putting it on a user-facing path. ## Next steps * [Partial search](/pro/concepts/partial-search) — prefix and substring matching on indexed fields * [Access control](/pro/administration/access-control) — restrict who may run a search and which fields come back * [Bulk export controls](/pro/concepts/select-security) — why enumeration is default-deny * [SDKs](/pro/developer-tools/overview) — JavaScript and Python clients # Multi-jurisdiction deployment Source: https://docs.databunker.org/pro/concepts/global-deployment For global organisations subject to **data-localisation** obligations in multiple countries, the right architecture is to run **one Databunker Pro instance per jurisdiction**. Each instance keeps the PII for that jurisdiction inside the jurisdiction, with its own keys, audit trail, and operators if local law requires. This page covers the pattern, the reasons behind it, and how the privacy office runs operations across N deployments without violating data-localisation rules. ## The problem this pattern solves A growing number of jurisdictions explicitly prohibit transferring personal data out of the country — or impose burdensome conditions that make centralising PII in one cloud region commercially impractical. Examples: | Jurisdiction | Law / framework | Localisation stance | | - | - | - | | EU / EEA | GDPR (Chapter V transfers) | Cross-border transfers require an Article 45 adequacy decision, Article 46 safeguards, or SCCs. | | India | DPDPA | Cross-border transfers permitted only to whitelisted countries; sensitive data subject to stricter rules. | | Russia | Federal Law 152-FZ | Personal data of Russian citizens must be **stored and primarily processed** inside Russia. | | Turkey | KVKK | Cross-border transfer requires explicit consent or KVKK Board approval. | | Saudi Arabia | PDPL | Restrictions on cross-border transfer of personal data of residents. | | Brazil | LGPD | Cross-border transfer permitted under specific legal bases, with ANPD oversight. | | China | PIPL | Strict cross-border transfer requirements, including CAC security assessment for large processors. | A single-region deployment that holds PII for all these jurisdictions in, say, AWS Frankfurt, is non-compliant the moment a Russian, Indian, or Chinese resident's record lands in the vault. ## The pattern Deploy a separate Databunker Pro instance in each jurisdiction where you hold PII. Each instance is: * **Independent** — its own database, its own master key, its own wrapping key, its own audit log. * **In-region** — deployed on local cloud infrastructure (AWS Mumbai, Azure Russia, etc.) or local on-prem hardware. * **Operated locally** if local law requires (operator citizenship, residency, or licensing constraints). The application chooses which regional vault to call based on user domicile, data classification, or originating system. ```text theme={null} [ Application ] | +-------------------+-------------------+-------------------+-------------------+ | | | | | v v v v v [ Pro — EU ] [ Pro — India ] [ Pro — Russia ] [ Pro — Turkey ] [ Pro — Brazil ] GDPR boundary DPDPA boundary 152-FZ boundary KVKK boundary LGPD boundary keys local keys local keys local keys local keys local audit local audit local audit local audit local audit local ``` Each regional vault holds **only** the records of users domiciled in that jurisdiction. Cross-vault correlation is not possible at the SQL or token layer — that is the point of the pattern. ## The next-order problem: operating privacy across N vaults Once an organisation has five, ten, or fifteen regional Pro deployments, the privacy office faces a new problem: * A data subject in India submits a DSAR through the company's global website. How does the DPO team find their data without logging into the Indian Pro instance separately? * A consent withdrawal in Brazil needs to propagate to every system that holds the user's data — but the regional vaults are intentionally air-gapped at the PII level. * A compliance report for the EU board needs aggregated metrics (number of records, DSAR counts, consent rates) across every region. Running a separate DPO seat per vault is impractical at scale. ## The unifier: Databunker DPO [**Databunker DPO**](https://databunker.org/use-case/dpo-management-portal/) is the operational layer designed for exactly this scenario. DPO connects to each regional Pro deployment over an authenticated channel and gives the privacy office a **single UI** spanning the full estate, with the critical property that: * **Minimises the chance of PII leaving its home jurisdiction.** By design, only **operational signals** flow through DPO — DSAR tickets, consent state transitions, audit summaries, processing-activity metadata, aggregated metrics. Raw PII is never required for these operations, so under normal operation it stays inside the regional vault. Customers remain responsible for configuring DPO and any custom workflows to honour their local data-localisation constraints. * Each regional Pro deployment continues to enforce its own access control, audit, and key custody locally. This lets a small privacy team operate at global scale without violating any localisation rule, because the data that crosses borders in the DPO operational plane is not personal data — it is metadata about the privacy operations themselves. ### DPO deployment options | Option | When to use | | - | - | | **SaaS (default)** | DPO hosted in the Databunker Portal. The privacy team logs in via the web. Best for most customers. | | **Self-hosted** | Enterprise customers who require the operational layer to also run inside their own perimeter (e.g., highly regulated industries, sovereign clouds) can self-host DPO. | ## When NOT to use this pattern This pattern is for organisations operating in **multiple jurisdictions with localisation constraints**. If you operate in a single jurisdiction, or in multiple jurisdictions without conflicting localisation rules, the right tool is [**multi-tenancy inside a single Pro instance**](/pro/administration/multi-tenancy) — it gives cryptographic per-domain isolation without the operational overhead of running N deployments. | Use one Pro + multi-tenancy when | Use multi-jurisdiction Pro deployments when | | - | - | | Single jurisdiction. | Multiple jurisdictions with localisation laws. | | Multiple security domains, one legal home. | Each region's PII is legally required to stay in-region. | | One operations team. | Local operations possibly required by law. | The two patterns can be combined: each regional Pro deployment can itself use multi-tenancy internally to separate its security domains (Student Services vs Analytics vs External Integrations), so the architecture remains consistent regardless of scale. ## Related * [Multi-tenancy](/pro/administration/multi-tenancy) — per-instance tenant isolation (different concern). * [Architecture](/pro/get-started/architecture) — core single-instance architecture. * [Security overview](/pro/get-started/security-overview) — sovereignty and key custody guarantees that make this pattern work. * [Databunker DPO](https://databunker.org/use-case/dpo-management-portal/) — the operational unifier across regional Pro deployments. # Partial search Source: https://docs.databunker.org/pro/concepts/partial-search Databunker Pro stores every user record **encrypted or hashed**. This is what keeps your PII safe at rest, but it also means the vault cannot run a classic `LIKE '%john%'` substring query the way a plaintext SQL database can — there is no readable text to scan. As a result, partial and free-text search is intentionally limited. Databunker Pro offers two complementary approaches to work around this constraint: 1. **Fuzzy search** — for approximate, single-field matching (typos, misspellings, accent characters). 2. **Group-based partial search** — for pre-indexing users by attributes such as first name or family name so they can be listed later. ## Why partial search is hard Because records are encrypted or hashed, Databunker Pro can only match on values it can deterministically compute or index. It cannot: * Scan arbitrary substrings inside an encrypted field * Run wildcard (`%...%`) queries across the whole dataset * Rank results by arbitrary free text against ciphertext The two mechanisms below give you practical partial-search behavior while keeping the data encrypted. ## Option 1: Fuzzy search Fuzzy search is the right tool when you need **approximate matching on a single field** — for example, a support agent typing a login or email with a typo, or a name written with different accent characters (`José` vs `Jose`). It is well suited for: * ✅ Spelling mistakes and typos * ✅ Accent and diacritic variations * ✅ Minor formatting differences Fuzzy search runs through the `/v2/UserSearch` endpoint and requires a bulk-unlock UUID. See the dedicated [Fuzzy search](/pro/concepts/fuzzy-search) page for the full API and SDK examples. ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/UserSearch" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "mode": "login", "identity": "jon", "unlockuuid": "your-unlock-uuid" }' ``` > [!NOTE] > > Fuzzy search matches variations of a value you already roughly know. It is not designed to enumerate every user whose name contains a given substring — for that, use the group-based approach below. ## Option 2: Group-based partial search Databunker Pro includes a **user group API**. By linking each user to one or more groups at creation (or update) time, you effectively build your own search index without ever exposing the underlying encrypted values. The idea: when you store a user, also add them to a group named after the attribute you want to search on later. For a user **John Doe**, link them to two groups: * A group for the first name — e.g. `name:john` * A group for the family name — e.g. `family:doe` Later, "searching" for everyone named *John* becomes listing the members of the `name:john` group — a fast, exact lookup that never decrypts data to scan it. ### Step 1: Create the groups Create a group once per attribute value. You can create groups up front or lazily the first time a value appears. `GroupCreate` accepts an optional **`grouptype`** field — a short label (up to 30 characters) that classifies the group. Use it to tag each index group by the attribute it represents, e.g. `firstname` or `familyname`. This makes your index self-describing: `GroupGet` and `GroupListAllGroups` return `grouptype`, so you can list all your groups and filter them by type on the client side. If you omit `grouptype`, it defaults to `users`. ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/GroupCreate" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "groupname": "name:john", "grouptype": "firstname", "groupdesc": "Users with first name John" }' ``` ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/GroupCreate" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "groupname": "family:doe", "grouptype": "familyname", "groupdesc": "Users with family name Doe" }' ``` > [!NOTE] > > `grouptype` is a classifying label, not a namespace. Group **names** must be unique across your whole tenant regardless of their type, so keep the attribute value in the group name (`name:john`, `family:doe`) to avoid collisions — for example when a first name and a family name are the same word. ### Step 2: Link the user to the groups When you create or update a user, add them to the relevant groups with `/v2/GroupAddUser`. The user is identified by any supported `mode` (`login`, `token`, `email`, `phone`, `custom`). ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/GroupAddUser" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "mode": "email", "identity": "john.doe@example.com", "groupname": "name:john" }' ``` ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/GroupAddUser" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "mode": "email", "identity": "john.doe@example.com", "groupname": "family:doe" }' ``` John Doe now belongs to both `name:john` and `family:doe`. ### Step 3: List users by attribute To find everyone whose first name is *John*, list the members of the `name:john` group. Group listing uses the bulk-unlock mechanism, so first request a short-lived unlock UUID, then call `/v2/BulkListGroupUsers`. ```bash theme={null} # Step 1: request a bulk-unlock UUID (valid for 60 seconds) curl -X POST "https://your-databunker-instance/v2/BulkListUnlock" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" # Step 2: list the members of the group curl -X POST "https://your-databunker-instance/v2/BulkListGroupUsers" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "groupname": "name:john", "unlockuuid": "your-unlock-uuid", "offset": 0, "limit": 10 }' ``` To narrow to **John Doe** specifically, list both groups and intersect the results by user `token` on the client side. ### JavaScript/TypeScript example (Official SDK) ```javascript theme={null} import DatabunkerproAPI from "databunkerpro-js"; const client = new DatabunkerproAPI( "https://your-databunker-instance.com", "your-token" ); // Index a user under first-name and family-name groups async function indexUser(email, firstName, familyName) { await client.makeRequest("GroupCreate", { groupname: `name:${firstName}`, grouptype: "firstname", }); await client.makeRequest("GroupCreate", { groupname: `family:${familyName}`, grouptype: "familyname", }); await client.makeRequest("GroupAddUser", { mode: "email", identity: email, groupname: `name:${firstName}`, }); await client.makeRequest("GroupAddUser", { mode: "email", identity: email, groupname: `family:${familyName}`, }); } // List everyone with a given first name async function findByFirstName(firstName) { const unlock = await client.bulkListUnlock(); const response = await client.makeRequest("BulkListGroupUsers", { groupname: `name:${firstName}`, unlockuuid: unlock.unlockuuid, limit: 100, }); return response.rows || []; } await indexUser("john.doe@example.com", "john", "doe"); const johns = await findByFirstName("john"); console.log(`Found ${johns.length} users named John`); ``` ## Choosing an approach | Need | Use | | - | - | | Handle typos / misspellings on a known value | Fuzzy search | | Match accent / diacritic variations | Fuzzy search | | List all users sharing an attribute value | Group-based partial search | | Combine two attributes (e.g. first + family) | Group-based, intersect | The two approaches are complementary: fuzzy search is best for *"I roughly know this value"*, while group indexing is best for *"list everyone who matches this attribute exactly."* ## Considerations * **Normalize before indexing.** Lowercase and trim values (`name:john`, not `Name: John`) so lookups are consistent. Decide up front how to handle accents — either strip them for the group key or keep them and rely on fuzzy search for variants. * **Exact keys, not substrings.** Group lookups match the full attribute value. If you need prefix matching (`joh` → `john`), index additional keys (for example n-grams or prefixes) as separate groups. * **Tag groups with `grouptype`.** Set a `grouptype` (max 30 characters, defaults to `users`) when creating each index group so you can tell your index groups apart from ordinary application groups and filter them by category via `GroupListAllGroups`. Remember it is a label only — group names must still be unique. * **Group cardinality.** Every distinct value becomes a group. For high-cardinality fields this can create many groups — index only the attributes you actually search on. * **Security is preserved.** Group listing still goes through the [bulk-unlock](/pro/concepts/select-security) mechanism and is subject to your access-control policies, so this pattern does not weaken Databunker Pro's security model. Records remain encrypted throughout. * **Keep the index in sync.** Remove a user from a group with `/v2/GroupDeleteUser` when the underlying attribute changes, and add them to the new group. ## Next steps Because records are encrypted and indexes are hashed, true substring search is not possible. [Fuzzy search](/pro/concepts/fuzzy-search) covers approximate matching on values you already know, and the user group API lets you build exact-match indexes for the attributes you care about. * [Fuzzy search](/pro/concepts/fuzzy-search) — approximate matching * [Access control](/pro/administration/access-control) — who may search, and which fields are returned * [Security overview](/pro/get-started/security-overview) — why the indexes are hashed # Record versioning Source: https://docs.databunker.org/pro/concepts/record-versioning **Record Versioning** in Databunker Pro provides automatic version history tracking for user profiles and application data. Every time a record is created or updated, Databunker Pro automatically creates a new version, allowing you to track changes over time, audit data modifications, and restore previous states when needed. ## Configuration Record versioning is **not enabled by default**. To enable versioning, you need to configure it in your `databunker.yaml` configuration file: ```yaml theme={null} versioning: enabled: true max_versions: 10 max_version_retention_period: "1m" ``` After enabling versioning in the configuration file, restart your Databunker Pro instance for the changes to take effect. > [!NOTE] > > Versions are included in the record they belong to and do not count separately against your license. Enabling versioning never multiplies your record count — see [Licensing and limits](/pro/get-started/licensing#what-counts-as-a-record). ## What Problems Does Record Versioning Solve? ### 1. **Change History & Data Integrity** * ✅ Complete history of all data changes over time * ✅ Track what changed and when it changed * ✅ Verify data integrity with cryptographic hashes * ✅ Maintain immutable record of data evolution ### 2. **Data Recovery & Rollback** * ✅ Restore previous versions of user data * ✅ Recover from accidental data modifications * ✅ Undo unwanted changes quickly * ✅ Maintain data consistency across systems ### 3. **Change Tracking & Analysis** * ✅ Understand how user data evolves over time * ✅ Analyze patterns in data modifications * ✅ Identify data quality issues * ✅ Support forensic investigations ## How Record Versioning Works Databunker Pro automatically creates a new version every time you: * Create a new user record * Update a user profile * Create application data * Update application data Each version includes: * **Version number**: Sequential integer starting from 1 * **Operation time**: Unix timestamp of when the version was created * **MD5 hash**: Cryptographic hash for integrity verification * **Full record data**: Complete snapshot of the record at that point in time ## Supported Record Types Record versioning is available for: | Record Type | API Endpoints | Use Case | | - | - | - | | **User Profiles** | `UserListVersions`, `UserGet` (with version) | Track user profile changes, email updates, phone number changes | | **Application Data** | `AppdataListVersions`, `AppdataGet` (with version) | Track application-specific data changes, configuration updates | ## User Profile Versioning ### Listing User Versions To see all versions of a user's profile: ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/UserListVersions" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "mode": "token", "identity": "user-token-here" }' ``` **Response:** ```json theme={null} { "status": "ok", "versions": [ { "version": 1, "optime": 1699123456, "md5": "a1b2c3d4e5f6..." }, { "version": 2, "optime": 1699123500, "md5": "b2c3d4e5f6a1..." }, { "version": 3, "optime": 1699123600, "md5": "c3d4e5f6a1b2..." } ] } ``` ### Retrieving a Specific User Version To retrieve a specific version of a user's profile: ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/UserGet" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "mode": "token", "identity": "user-token-here", "version": 1 }' ``` **Response:** ```json theme={null} { "status": "ok", "token": "user-token-here", "profile": { "login": "versionuser", "email": "versionuser@email.com" }, "version": 1 } ``` ### JavaScript/TypeScript Example ```javascript theme={null} import DatabunkerproAPI from "databunkerpro-js"; const client = new DatabunkerproAPI( "https://your-databunker-instance.com", "your-token" ); // Step 1: Create a user const createResponse = await client.userCreate({ profile: { login: "versionuser", email: "versionuser@email.com" } }); const userToken = createResponse.token; // Step 2: Update the user profile await client.userUpdate({ mode: "token", identity: userToken, profile: { login: "versionuser", email: "versionuser2@email.com" } }); // Step 3: Update again await client.userUpdate({ mode: "token", identity: userToken, profile: { login: "versionuser", email: "versionuser3@email.com" } }); // Step 4: List all versions const versionsResponse = await client.userListVersions({ mode: "token", identity: userToken }); console.log("User versions:", versionsResponse.versions); // Output: [ // { version: 1, optime: 1699123456, md5: "..." }, // { version: 2, optime: 1699123500, md5: "..." }, // { version: 3, optime: 1699123600, md5: "..." } // ] // Step 5: Retrieve a specific version const version1 = await client.userGet({ mode: "token", identity: userToken, version: 1 }); console.log("Version 1 email:", version1.profile.email); // Output: "versionuser@email.com" const version2 = await client.userGet({ mode: "token", identity: userToken, version: 2 }); console.log("Version 2 email:", version2.profile.email); // Output: "versionuser2@email.com" ``` ### Python Example ```python theme={null} from databunkerpro import DatabunkerproAPI api = DatabunkerproAPI( base_url="https://your-databunker-instance", x_bunker_token="YOUR_ACCESS_TOKEN" ) # Step 1: Create a user create_response = api.user_create({ "profile": { "login": "versionuser", "email": "versionuser@email.com" } }) user_token = create_response["token"] # Step 2: Update the user profile api.user_update({ "mode": "token", "identity": user_token, "profile": { "login": "versionuser", "email": "versionuser2@email.com" } }) # Step 3: Update again api.user_update({ "mode": "token", "identity": user_token, "profile": { "login": "versionuser", "email": "versionuser3@email.com" } }) # Step 4: List all versions versions_response = api.user_list_versions({ "mode": "token", "identity": user_token }) print("User versions:", versions_response["versions"]) # Output: [ # {"version": 1, "optime": 1699123456, "md5": "..."}, # {"version": 2, "optime": 1699123500, "md5": "..."}, # {"version": 3, "optime": 1699123600, "md5": "..."} # ] # Step 5: Retrieve a specific version version1 = api.user_get({ "mode": "token", "identity": user_token, "version": 1 }) print("Version 1 email:", version1["profile"]["email"]) # Output: "versionuser@email.com" version2 = api.user_get({ "mode": "token", "identity": user_token, "version": 2 }) print("Version 2 email:", version2["profile"]["email"]) # Output: "versionuser2@email.com" ``` ## Application Data Versioning Application data versioning works similarly to user profile versioning, but tracks changes to application-specific data associated with users. ### Listing Appdata Versions ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/AppdataListVersions" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "mode": "token", "identity": "user-token-here", "appname": "mytestapp" }' ``` **Response:** ```json theme={null} { "status": "ok", "versions": [ { "version": 1, "optime": 1699123456, "md5": "a1b2c3d4e5f6..." }, { "version": 2, "optime": 1699123500, "md5": "b2c3d4e5f6a1..." }, { "version": 3, "optime": 1699123600, "md5": "c3d4e5f6a1b2..." } ] } ``` ### Retrieving a Specific Appdata Version ```bash theme={null} curl -X POST "https://your-databunker-instance/v2/AppdataGet" \ -H "Content-Type: application/json" \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -d '{ "mode": "token", "identity": "user-token-here", "appname": "mytestapp", "version": 1 }' ``` ### JavaScript/TypeScript Example ```javascript theme={null} import DatabunkerproAPI from "databunkerpro-js"; const client = new DatabunkerproAPI( "https://your-databunker-instance.com", "your-token" ); // Step 1: Create user const userResponse = await client.userCreate({ profile: { login: "appuser0", email: "appuser0@email.com" } }); const userToken = userResponse.token; // Step 2: Create appdata await client.appdataCreate({ appname: "mytestapp", mode: "token", identity: userToken, appdata: { score: 0, note: "init" } }); // Step 3: Update appdata multiple times for (let v = 1; v <= 3; v++) { await client.appdataUpdate({ appname: "mytestapp", mode: "token", identity: userToken, appdata: { score: v, note: `update${v}` } }); } // Step 4: List all appdata versions const versionsResponse = await client.appdataListVersions({ appname: "mytestapp", mode: "token", identity: userToken }); console.log("Appdata versions:", versionsResponse.versions); // Output: [ // { version: 1, optime: 1699123456, md5: "..." }, // { version: 2, optime: 1699123500, md5: "..." }, // { version: 3, optime: 1699123600, md5: "..." }, // { version: 4, optime: 1699123700, md5: "..." } // ] // Step 5: Retrieve a specific version const version1 = await client.appdataGet({ appname: "mytestapp", mode: "token", identity: userToken, version: 1 }); console.log("Version 1 appdata:", version1.appdata); // Output: { score: 0, note: "init" } const version2 = await client.appdataGet({ appname: "mytestapp", mode: "token", identity: userToken, version: 2 }); console.log("Version 2 appdata:", version2.appdata); // Output: { score: 1, note: "update1" } ``` ### Python Example ```python theme={null} from databunkerpro import DatabunkerproAPI api = DatabunkerproAPI( base_url="https://your-databunker-instance", x_bunker_token="YOUR_ACCESS_TOKEN" ) # Step 1: Create user user_response = api.user_create({ "profile": { "login": "appuser0", "email": "appuser0@email.com" } }) user_token = user_response["token"] # Step 2: Create appdata api.appdata_create({ "appname": "mytestapp", "mode": "token", "identity": user_token, "appdata": { "score": 0, "note": "init" } }) # Step 3: Update appdata multiple times for v in range(1, 4): api.appdata_update({ "appname": "mytestapp", "mode": "token", "identity": user_token, "appdata": { "score": v, "note": f"update{v}" } }) # Step 4: List all appdata versions versions_response = api.appdata_list_versions({ "appname": "mytestapp", "mode": "token", "identity": user_token }) print("Appdata versions:", versions_response["versions"]) # Step 5: Retrieve a specific version version1 = api.appdata_get({ "appname": "mytestapp", "mode": "token", "identity": user_token, "version": 1 }) print("Version 1 appdata:", version1["appdata"]) # Output: {"score": 0, "note": "init"} version2 = api.appdata_get({ "appname": "mytestapp", "mode": "token", "identity": user_token, "version": 2 }) print("Version 2 appdata:", version2["appdata"]) # Output: {"score": 1, "note": "update1"} ``` ## Real-World Use Cases ### 1. **Compliance & Audit Requirements** Many regulations require maintaining a complete history of data changes: ```javascript theme={null} // Track all changes to user email for GDPR compliance const versions = await client.userListVersions({ mode: "token", identity: userToken }); // Generate audit report const auditReport = versions.versions.map(v => ({ version: v.version, timestamp: new Date(v.optime * 1000), hash: v.md5 })); ``` ### 2. **Data Recovery** Restore previous versions when data is accidentally modified: ```javascript theme={null} // User's email was accidentally changed // Restore from version 2 const previousVersion = await client.userGet({ mode: "token", identity: userToken, version: 2 }); // Restore the email await client.userUpdate({ mode: "token", identity: userToken, profile: { email: previousVersion.profile.email } }); ``` ### 3. **Change Analysis** Analyze how user data changes over time: ```javascript theme={null} // Get all versions and compare changes const versions = await client.userListVersions({ mode: "token", identity: userToken }); for (const v of versions.versions) { const record = await client.userGet({ mode: "token", identity: userToken, version: v.version }); console.log(`Version ${v.version}:`, { timestamp: new Date(v.optime * 1000), email: record.profile.email }); } ``` ### 4. **Application State Management** Track changes to application-specific data: ```javascript theme={null} // Track score changes in a game application const versions = await client.appdataListVersions({ appname: "gameapp", mode: "token", identity: userToken }); // Find when score reached certain milestones for (const v of versions.versions) { const appdata = await client.appdataGet({ appname: "gameapp", mode: "token", identity: userToken, version: v.version }); if (appdata.appdata.score >= 1000) { console.log(`Score milestone reached at version ${v.version}`); } } ``` ## Security Considerations ### Access Control Record versioning respects Databunker Pro's Conditional Role-Based Access Control (CRBAC): * **Policy Enforcement**: Access to version history is controlled by policies * **Audit Logging**: All version access operations are logged ### Privacy Protection * **Encrypted Storage**: All version data remains encrypted at rest * **Secure Transmission**: Version requests use HTTPS encryption * **Access Logging**: Complete audit trail of all version access activities ## Version Metadata Each version includes important metadata: | Field | Type | Description | | - | - | - | | `version` | integer | Sequential version number (starts at 1) | | `optime` | integer | Unix timestamp when the version was created | | `md5` | string | MD5 hash of the version data for integrity verification | ## Next steps * [Licensing and limits](/pro/get-started/licensing#what-counts-as-a-record) — versions travel with the record and do not count separately * [Backup and recovery](/pro/administration/backup-and-recovery) — versioning is not a backup * [Access control](/pro/administration/access-control) — restricting who can read or restore a version # Select security Source: https://docs.databunker.org/pro/concepts/select-security ## Secure bulk retrieval challenge The primary security challenge with both SQL and NoSQL databases is the risk of secure bulk retrieval (or record-dumping) queries, such as a "SELECT \*" request. When combined with SQL injection or GraphQL injection vulnerabilities, attackers can exploit these queries to dump entire database in a matter of seconds. A malicious actor can access your sensitive records even if a database encryption solution is implemented. To address this threat, the original version of Databunker Pro was designed to retrieve user records only when specific user details were provided. This approach significantly limited attackers' ability to enumerate users stored in Databunker. Even if an attacker managed to obtain a Databunker Pro access token, they would still need to provide specific details like the user's email, phone number, or UUID to access any information. From a security perspective, this design was robust and highly effective. ## The Usability Dilemma Despite the strong security model, we began losing business. Companies provided feedback that they needed a way to list all users as part of their application's admin interface. Initially, we firmly opposed introducing any API that allowed bulk user retrieval, as it conflicted with our strict security principles. However, this resistance came at a cost. While our security model remained robust, our product's usability suffered, which negatively impacted our business. We realized we needed a solution that could balance these conflicting requirements: maintaining high security while providing admins with essential functionality. ## Iteration 1: Adding Basic Controls for Bulk Access Our initial attempt to balance usability and security introduced a two-step approach: 1. **Configuration Setting:** Admins could enable or disable the ability to dump user records entirely. 2. **POST Request Requirement:** A bulk data dump required a POST request, ensuring the action couldn't be triggered by a simple GET request. This solution addressed some concerns but still left room for improvement. ## Iteration 2: Secure Unlock Mechanism Over time, we developed a more secure solution: 1. **Unlock Request:** A special API unlock request must be submited, specifying whether they want to unlock all users or a specific group of users. 2. **Temporary Token:** The unlock request generates a temporary token with a short expiration window (60 seconds). 3. **Token Validation:** During the token's validity period, user records can only be dumped if the token is included in the API request. **This solution ensured that bulk data access required explicit admin intent, was time-restricted, and could not be abused by malicious actors.** The bulk unlock UUID is designed with strict time constraints for enhanced security: * It expires automatically after 60 seconds * It must be included when retrieving records for any group of users * A new UUID must be requested for subsequent bulk operations ## Iteration 3: Fine-Grained Access Control with Policy Engine Our latest iteration introduces a powerful policy engine that provides granular control over bulk operations and user listing capabilities. This enhancement allows organizations to: 1. **Control Bulk Operations Access:** Define exactly who has the right to perform bulk unlock API requests 2. **Group-Specific Access:** Restrict user listing to specific groups or departments 3. **Field-Level Security:** Control which user fields are visible in bulk operations 4. **Role-Based Controls:** Implement role-based access patterns for different admin types Here's an example policy that demonstrates these capabilities: ```json theme={null} { "policyname": "ManagerAccess", "policy": { "Effect": "Allow", "Principal": { "Role": "manager" }, "Action": ["UserGet", "BulkListGroupUsers"], "Resource": [ "${target_group_members:role/team-member}.profile.name", "${target_group_members:role/team-member}.profile.phone", "${target_group_members:role/team-member}.group" ], "Condition": { "StringEquals": { "${user_group_id}": "${target_group_id}" } } } } ``` This policy demonstrates several key security features: 1. **Limited Actions:** The manager role can only perform specific actions (`UserGet` and `BulkListGroupUsers`) 2. **Field Restrictions:** Access is limited to specific fields (name, phone, group) 3. **Group Isolation:** Managers can only access members of their own group 4. **Automatic Data Masking:** Other sensitive fields are automatically masked By implementing these policies, organizations can: * Allow HR managers to list only their department members * Restrict sensitive field access in bulk operations * Implement hierarchical access patterns * Maintain audit trails of all bulk access operations This policy-based approach provides the flexibility needed for complex organizational structures while maintaining strict security controls. It represents a significant evolution from our previous iterations, offering both the security we're known for and the granular control our customers need. ## Next steps * [Access control](/pro/administration/access-control) — the policy engine that governs bulk operations * [Authentication](/pro/api/authentication#bulk-unlock-uuid) — how the unlock UUID is issued and its 60-second lifetime * [Backup and recovery](/pro/administration/backup-and-recovery#exporting-every-record) — the sanctioned full-export path # Shared records Source: https://docs.databunker.org/pro/concepts/shared-records **Shared records** in Databunker Pro let you create a short-lived, UUID-addressable view of a specific user's record, optionally scoped to a subset of fields and tagged with a partner reference. They are the safe way to share a user reference across systems or with an external partner — instead of handing out a long-lived token that becomes a correlation key, you hand out a time-limited UUID that resolves to exactly the fields you authorise, and expires on its own. In conversation this pattern is sometimes called **shareable identities**; in the API it is **Shared Records**. ## When to use shared records Use a shared record when: * An external partner or downstream system needs to retrieve some fields from a specific user record, but should not be granted a long-lived token. * A cross-system reference is genuinely needed (e.g., sharing a customer between two business systems for a specific workflow), and you want the reference to expire automatically. * You want to avoid creating a deterministic, long-lived token that could become a correlation key across security domains. For day-to-day intra-tenant lookups, use `UserGet` directly — shared records are for the *cross-boundary* or *time-limited* case. ## How they work 1. The caller invokes `SharedRecordCreate`, identifying the user by `email` / `phone` / `login` / `token` / `custom` and specifying which fields to share, an expiration (`finaltime`), and optionally a `partner` tag for the audit trail. 2. Databunker Pro returns a `recorduuid` — a fresh UUID that addresses this specific shared view. 3. The caller distributes the `recorduuid` to the consumer (downstream system, partner, etc.). 4. The consumer calls `SharedRecordGet` with the `recorduuid` to retrieve the data, until expiration. 5. After expiration, the `recorduuid` no longer resolves — the share ends automatically with no clean-up step required. Every create and every retrieval generates an audit event. ## API: Create a shared record ```bash theme={null} curl -X POST https://your-databunker-instance/v2/SharedRecordCreate \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "mode": "email", "identity": "john.doe@example.com", "fields": "first,last,email", "partner": "partner-acme-billing", "finaltime": "7d" }' ``` ### Request fields | Field | Required | Description | | - | - | - | | `mode` | yes | How the user is identified: one of `login`, `token`, `email`, `phone`, `custom`. | | `identity` | yes | The identifier value matching `mode` (e.g., the email address when `mode=email`). | | `fields` | no | Comma-separated list of profile fields to include in the share. Omit to share the full profile. | | `partner` | no | A partner / consumer reference name. Recorded in the audit event for accountability. | | `appname` | no | Application name when sharing app-specific data attached to the user. | | `finaltime` | no | Expiration time for the share (e.g., `30m`, `24h`, `7d`). After expiration the `recorduuid` no longer resolves. | | `request_metadata` | no | Runtime context for CRBAC policy evaluation (see [Access control](/pro/administration/access-control)). | ### Response ```json theme={null} { "status": "ok", "recorduuid": "550e8400-e29b-41d4-a716-446655440000" } ``` ## API: Retrieve a shared record ```bash theme={null} curl -X POST https://your-databunker-instance/v2/SharedRecordGet \ -H "X-Bunker-Token: PARTNER_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "recorduuid": "550e8400-e29b-41d4-a716-446655440000" }' ``` ### Request fields | Field | Required | Description | | - | - | - | | `recorduuid` | yes | The UUID returned by `SharedRecordCreate`. | | `request_metadata` | no | Runtime context for CRBAC policy evaluation. | ### Response ```json theme={null} { "status": "ok", "data": { "first": "John", "last": "Doe", "email": "john.doe@example.com" } } ``` Only fields explicitly listed in the `fields` parameter at creation time are returned. The consumer never sees the full record. ## Why shared records, not long-lived tokens? Reusing the same deterministic token across multiple systems and partners turns the token into a universal correlation key — if it leaks once, an attacker can correlate everything. Shared records avoid this in three ways: * **Time-limited.** A `finaltime` is mandatory in practice; expired shares cannot be reused. * **Field-limited.** The `fields` parameter is data-minimisation by construction — partners receive only what they need. * **Audit-attributable.** The `partner` tag plus the audit trail attribute every retrieval to a named consumer. ## Related * [PII Vault](/pro/get-started/pii-vault) — how regular user tokens work. * [Sub-accounts](/pro/concepts/sub-accounts) — multi-tenant patterns that limit deterministic-token reuse across security domains. * [Access control](/pro/administration/access-control) — CRBAC policies and `request_metadata`. # Sub-accounts Source: https://docs.databunker.org/pro/concepts/sub-accounts **Sub-accounts** (also referred to as **hierarchical accounts**) in Databunker Pro enable organizations to create isolated account structures within their Databunker Pro instance. This feature is essential for businesses that need to manage multiple independent accounts, departments, or organizational units while maintaining data isolation and administrative control. ## What Problems Do Sub-accounts Solve? ### 1. **Organizational Structure Management** * ✅ Create isolated account spaces for different departments or business units * ✅ Maintain separate administrative control for each sub-account * ✅ Enable independent data management per sub-account * ✅ Support hierarchical organizational structures ### 2. **Multi-tenant SaaS Applications** * ✅ Provide isolated data storage for each customer * ✅ Enable customer-specific administrative access * ✅ Maintain complete data separation between accounts * ✅ Support white-label or reseller scenarios ### 3. **Compliance and Data Isolation** * ✅ Ensure complete data isolation between sub-accounts * ✅ Meet regulatory requirements for data separation * ✅ Enable independent audit trails per sub-account * ✅ Support compliance with data residency requirements ## Implementation Approaches Databunker Pro provides two primary approaches for implementing sub-accounts: 1. **Multi-tenancy Support** - Creates isolated tenants with dedicated admin tokens 2. **Groups with Roles and Policies** - Uses Databunker Pro's CRBAC system for group-based management These approaches can also be combined together to create an even more flexible solution that leverages both database-level isolation from multi-tenancy and fine-grained access control from groups. ## Approach 1: Multi-tenancy Support Multi-tenancy is the recommended approach when you need complete data isolation and independent administrative control for each sub-account. After creating a tenant, you receive a tenant admin token that allows full management of all records within that tenant. ### How It Works When you create a new tenant using the multi-tenancy feature: 1. A new isolated tenant is created with its own data namespace 2. A **tenant admin token** is generated that provides full administrative access 3. All records created within this tenant are completely isolated from other tenants at the database level. **Note:** Multi-tenancy is supported on PostgreSQL, MySQL, and Oracle; on PostgreSQL it is enforced with native row-level security (RLS). 4. The tenant admin token can manage all user records, application data, and configurations within the tenant Records are separated from one tenant to another at the database level, ensuring that queries executed by specific tenants are restricted to their own records and providing complete data isolation. ### Creating a Sub-account with Multi-tenancy ```bash theme={null} curl -H 'X-Bunker-Token: ROOT-ACCESS-TOKEN' \ -X POST https://your-databunker-instance/v2/TenantCreate \ -H 'Content-Type: application/json' \ --data '{ "tenantorg": "acme-corp", "tenantname": "subaccount-001" }' ``` **Response:** ```json theme={null} { "status": "ok", "xtoken": "TENANT-ADMIN-TOKEN-001" } ``` ### Using the Tenant Admin Token The tenant admin token is one of several credential types — see the [Authentication reference](/pro/api/authentication) for the full hierarchy. Once you have the tenant admin token, you can use it to manage all records within that tenant: ```bash theme={null} # Create a user in the sub-account curl -H 'X-Bunker-Token: TENANT-ADMIN-TOKEN-001' \ -H 'X-Bunker-Tenant: subaccount-001' \ -H 'Content-Type: application/json' \ -X POST https://your-databunker-instance/v2/UserCreate \ --data '{ "profile": { "login": "user1", "email": "user1@subaccount-001.com", "firstname": "John", "lastname": "Doe" } }' ``` ### JavaScript/TypeScript Example ```javascript theme={null} import DatabunkerproAPI from "databunkerpro-js"; // Initialize root admin client const rootClient = new DatabunkerproAPI( "https://your-databunker-instance.com", "ROOT-ACCESS-TOKEN" ); // Step 1: Create a new sub-account (tenant) const tenantResponse = await rootClient.tenantCreate({ tenantorg: "acme-corp", tenantname: "subaccount-001" }); const tenantAdminToken = tenantResponse.xtoken; const tenantName = "subaccount-001"; // Step 2: Initialize client with tenant admin token const tenantClient = new DatabunkerproAPI( "https://your-databunker-instance.com", tenantAdminToken ); // Step 3: Create users in the sub-account const userResponse = await tenantClient.userCreate({ profile: { login: "user1", email: "user1@subaccount-001.com", firstname: "John", lastname: "Doe" } }); console.log("Sub-account created with tenant admin token:", tenantAdminToken); console.log("User created in sub-account:", userResponse.token); ``` ### Python Example ```python theme={null} from databunkerpro import DatabunkerproAPI # Initialize root admin client root_api = DatabunkerproAPI( base_url="https://your-databunker-instance", x_bunker_token="ROOT-ACCESS-TOKEN" ) # Step 1: Create a new sub-account (tenant) tenant_response = root_api.tenant_create({ "tenantorg": "acme-corp", "tenantname": "subaccount-001" }) tenant_admin_token = tenant_response["xtoken"] tenant_name = "subaccount-001" # Step 2: Initialize client with tenant admin token tenant_api = DatabunkerproAPI( base_url="https://your-databunker-instance", x_bunker_token=tenant_admin_token, x_bunker_tenant=tenant_name ) # Step 3: Create users in the sub-account user_response = tenant_api.user_create({ "profile": { "login": "user1", "email": "user1@subaccount-001.com", "firstname": "John", "lastname": "Doe" } }) print(f"Sub-account created with tenant admin token: {tenant_admin_token}") print(f"User created in sub-account: {user_response['token']}") ``` ### Benefits of Multi-tenancy Approach * **Complete Data Isolation**: Each tenant has its own isolated data namespace * **Independent Administration**: Tenant admin tokens provide full control within the tenant * **Scalability**: Supports unlimited tenants with database-level isolation * **Security**: Built-in tenant separation at the database level * **Compliance**: Meets data residency and isolation requirements ## Approach 2: Groups with Roles and Policies The groups approach leverages Databunker Pro's Conditional Role-Based Access Control (CRBAC) system. Each group can store sub-accounts, and a group admin user manages all users within that group. This approach is implemented using roles and policies. ### How It Works With the groups approach: 1. Create a group to represent the sub-account 2. Assign a **group admin** role to a user who will manage the sub-account 3. Create policies that grant the group admin access to manage users within the group 4. Add users to the group as needed 5. The group admin can manage all users within their assigned group ### Creating a Sub-account with Groups ```bash theme={null} # Step 1: Create a group admin user curl -H 'X-Bunker-Token: YOUR-ACCESS-TOKEN' \ -H 'Content-Type: application/json' \ -X POST https://your-databunker-instance/v2/UserCreate \ --data '{ "profile": { "login": "group-admin-001", "email": "admin@subaccount-001.com", "firstname": "Admin", "lastname": "User" } }' # Step 2: Create a group for the sub-account curl -H 'X-Bunker-Token: YOUR-ACCESS-TOKEN' \ -H 'Content-Type: application/json' \ -X POST https://your-databunker-instance/v2/GroupCreate \ --data '{ "groupname": "subaccount-001", "description": "Sub-account group 001" }' # Step 3: Add the group admin to the group with admin role curl -H 'X-Bunker-Token: YOUR-ACCESS-TOKEN' \ -H 'Content-Type: application/json' \ -X POST https://your-databunker-instance/v2/GroupAddUser \ --data '{ "groupname": "subaccount-001", "mode": "token", "identity": "USER-TOKEN-FROM-STEP-1", "role": "group-admin" }' ``` ### Creating Policies for Group Admin Create a policy that allows the group admin to manage all users within their group: ```bash theme={null} curl -H 'X-Bunker-Token: YOUR-ACCESS-TOKEN' \ -H 'Content-Type: application/json' \ -X POST https://your-databunker-instance/v2/PolicyCreate \ --data '{ "policyname": "subaccount-admin-policy", "policy": { "Effect": "Allow", "Principal": { "Role": "group-admin" }, "Action": [ "UserGet", "UserCreate", "UserUpdate", "UserDelete", "BulkListGroupUsers", "BulkListUnlock", "GroupListUserGroups" ], "Resource": [ "${target_group_members}.profile", "${target_group_members}.consent", "${target_group_members}.appdata" ], "Condition": { "StringEquals": { "${principal_group_id}": "${target_group_id}" } } } }' ``` ### JavaScript/TypeScript Example ```javascript theme={null} import DatabunkerproAPI from "databunkerpro-js"; const client = new DatabunkerproAPI( "https://your-databunker-instance.com", "YOUR-ACCESS-TOKEN" ); // Step 1: Create a group admin user const adminResponse = await client.userCreate({ profile: { login: "group-admin-001", email: "admin@subaccount-001.com", firstname: "Admin", lastname: "User" } }); const adminToken = adminResponse.token; // Step 2: Create a group for the sub-account await client.groupCreate({ groupname: "subaccount-001", description: "Sub-account group 001" }); // Step 3: Add the group admin to the group with admin role await client.groupAddUser({ groupname: "subaccount-001", mode: "token", identity: adminToken, role: "group-admin" }); // Step 4: Create policy for group admin await client.policyCreate({ policyname: "subaccount-admin-policy", policy: { Effect: "Allow", Principal: { Role: "group-admin" }, Action: [ "UserGet", "UserCreate", "UserUpdate", "UserDelete", "BulkListGroupUsers", "BulkListUnlock", "GroupListUserGroups" ], Resource: [ "${target_group_members}.profile", "${target_group_members}.consent", "${target_group_members}.appdata" ], Condition: { StringEquals: { "${principal_group_id}": "${target_group_id}" } } } }); // Step 5: Group admin can now create users in their group const groupAdminClient = new DatabunkerproAPI( "https://your-databunker-instance.com", adminToken ); // Create a user in the sub-account const userResponse = await groupAdminClient.userCreate({ profile: { login: "user1", email: "user1@subaccount-001.com", firstname: "John", lastname: "Doe" } }); // Add user to the group await groupAdminClient.groupAddUser({ groupname: "subaccount-001", mode: "token", identity: userResponse.token, role: "member" }); console.log("Sub-account created using groups approach"); console.log("Group admin token:", adminToken); ``` ### Benefits of Groups Approach * **Flexible Access Control**: Fine-grained permissions using CRBAC policies * **Role-Based Management**: Different roles can be assigned within groups * **Conditional Access**: Policies can include complex conditions for access control * **Compliance Support**: Supports FERPA, GDPR, and DPDPA compliance scenarios * **Hierarchical Structures**: Supports parent-child relationships within groups ## Choosing the Right Approach ### Use Multi-tenancy When: * You need **complete data isolation** between sub-accounts * Each sub-account requires **independent administrative control** * You're building a **multi-tenant SaaS application** * You need to meet **strict data residency requirements** * You want **database-level isolation** for security ### Use Groups Approach When: * You need **flexible, role-based access control** within sub-accounts * You want to implement **hierarchical organizational structures** * You need **conditional access policies** (e.g., parent-child relationships) * You're building **compliance-focused applications** (FERPA, GDPR, DPDPA) * You want **fine-grained permissions** for different user roles ## Real-World Use Cases ### 1. **SaaS Multi-tenant Application** Create isolated sub-accounts for each customer: ```javascript theme={null} // Create a tenant for each customer const customerTenant = await rootClient.tenantCreate({ tenantorg: "saas-provider", tenantname: `customer-${customerId}` }); // Provide customer with their tenant admin token // Customer can now manage their own data independently ``` ### 2. **Departmental Sub-accounts** Organize departments within an organization: ```javascript theme={null} // Create a group for each department await client.groupCreate({ groupname: "engineering-department", description: "Engineering team sub-account" }); // Assign department admin await client.groupAddUser({ groupname: "engineering-department", mode: "token", identity: deptAdminToken, role: "group-admin" }); ``` ### 3. **Reseller/Partner Program** Enable partners to manage their own customer data: ```javascript theme={null} // Create tenant for each reseller const resellerTenant = await rootClient.tenantCreate({ tenantorg: "partner-program", tenantname: `reseller-${resellerId}` }); // Reseller gets tenant admin token to manage their customers ``` ## Security Considerations ### Multi-tenancy Security * **Database-level isolation**: Tenant data isolation is supported on PostgreSQL, MySQL, and Oracle; on PostgreSQL it is enforced with native row-level security (RLS) * **Token-Based Access**: Tenant admin tokens are scoped to their tenant * **Audit Logging**: All tenant operations are logged separately * **Encryption**: Each tenant's data is encrypted independently ### Groups Security * **Policy Enforcement**: CRBAC policies control all access * **Role Validation**: Roles are verified before granting access * **Condition Checks**: Policies include conditions for additional security * **Audit Trail**: All group operations are logged with role information ## Best Practices 1. **Token Management**: Securely store and rotate tenant admin tokens 2. **Policy Design**: Design policies carefully to ensure proper access control 3. **Regular Audits**: Review sub-account access and permissions regularly 4. **Monitoring**: Monitor sub-account activity for security and compliance 5. **Documentation**: Document which approach is used for each sub-account ## Choosing between them | | Multi-tenancy | Groups with CRBAC | | - | - | - | | Isolation | Enforced by the database (PostgreSQL RLS) | Enforced by policy evaluation | | Administration | Each tenant administered independently | Central administration | | Best for | Separate customers or jurisdictions | Hierarchy and roles inside one customer | The two combine: multi-tenancy for the database-level boundary, groups for fine-grained permissions within it. ## Next steps * [Multi-tenancy](/pro/administration/multi-tenancy) — tenant API and database-level isolation * [Access control](/pro/administration/access-control) — policies, roles, and field masking * [Multi-jurisdiction deployment](/pro/concepts/global-deployment) — when a separate instance beats a separate tenant # Format-preserving tokenization Source: https://docs.databunker.org/pro/concepts/tokenization Databunker Pro provides **two distinct tokenization engines**, each designed for a different job: * **PII tokenization** (`UserCreate` / `UserGet`) — stores a complete user profile (JSON, N fields) as one encrypted record and returns a single UUID token representing the whole profile. Builds secure hashed search indexes over `email`, `phone`, `login`, and a `custom` field for efficient lookups. This is the *user-table replacement* pattern; see the [PII Vault](/pro/get-started/pii-vault) page for full detail. * **Format-preserving tokenization** (`TokenCreate` / `TokenGet`) — tokenizes individual sensitive values: a `creditcard`, which returns a Luhn-valid look-alike alongside a UUID, or a `string`, which returns a UUID. This is the *PCI / single-value* pattern, covered in the rest of this page. Both engines share the same vault, encryption, multi-tenancy, and access-control layers — so the same auditability, key management, and CRBAC policies apply to either flow. Databunker Pro was built with the latest data privacy requirements in mind, such as data minimization, and is engineered to handle millions of data tokenization requests. The API supports bulk tokenization for efficient batch operations. ## Supported data types Two token types are recommended, and they cover almost every case: | `tokentype` | Original Record Type | Format Preservation | Generated Token Format | | - | - | - | - | | `creditcard` | Credit card number | ✅ (with Luhn check) | Format-preserving token plus a UUID | | `string` | Any text — name, address, date, email, identifier | ❌ | UUID token | `string` is an alias for the canonical type name `text`; both are accepted and both store the value as `text`. > [!WARNING] > > Other token types exist — `unixtimestamp`, `uint32`, `uint64`, `email`, `ssn` and > `uuid` — but they are **not recommended**. The numeric types generate their > format-preserving token by drawing a random value and rejecting collisions, and their > keyspace is small. At hundreds of millions of records the generator spends longer and > longer looking for a free value, until requests slow down or fail outright with > `Not enough random tokens`. Use `creditcard` and `string`. ## Key features ### Automatic Expiration In Databunker Pro, expiration allows you to set a lifespan for sensitive data tokens, ensuring they automatically expire after a defined period. Use `slidingtime` for a relative window (e.g. `30d`, `1h`) or `finaltime` for an absolute Unix-timestamp expiry. ```json theme={null} // Set a 30-day sliding expiration for a tokenized record { "tokentype": "creditcard", "record": "4532015112830366", "slidingtime": "30d" } ``` ### Unique Record Support This unique flag is used for data deduplication. It ensures that each record is saved only once, and the same token value is returned for identical records. If the original record has an expiration flag set, its expiration countdown will be reset from the beginning. ```json theme={null} // Same input generates same token when enabled { "tokentype": "creditcard", "record": "4532015112830366", "unique": true } ``` ### Dual Token Generation By default, Databunker Pro generates two tokens: one in UUID format and another in a format-preserving manner. ```json theme={null} // Example response for credit card tokenization { "status": "ok", "tokenuuid": "550e8400-e29b-41d4-a716-446655440000", "tokenbase": "4111111111111111" // Format-preserving token (Luhn-valid, same length) } ``` ## Getting started ```bash theme={null} # Example API call for tokenization curl -X POST https://databunker.pro/v2/TokenCreate \ -H "X-Bunker-Token: " \ -H "X-Bunker-Tenant: " \ -H "Content-Type: application/json" \ -d '{ "tokentype": "creditcard", "record": "4532015112830366", "slidingtime": "30d", "unique": true }' ``` Output: ```json theme={null} { "status": "ok", "tokenuuid": "550e8400-e29b-41d4-a716-446655440000", "tokenbase": "4111111111111111" // Format-preserving token (Luhn-valid, same length) } ``` ## Bulk tokenization For batch workloads — migrations, nightly imports, mass detokenization — Databunker Pro creates, reads, and deletes many tokens in a single call. ### Create tokens in bulk `TokenCreateBulk` takes an array of records and returns a token pair for each. `slidingtime` / `finaltime` and `unique` apply to the whole batch. ```bash theme={null} curl -X POST https://databunker.pro/v2/TokenCreateBulk \ -H "X-Bunker-Token: " \ -H "X-Bunker-Tenant: " \ -H "Content-Type: application/json" \ -d '{ "records": [ { "tokentype": "creditcard", "record": "4532015112830366" }, { "tokentype": "creditcard", "record": "5467047429390590" } ], "unique": true }' ``` Output: ```json theme={null} { "status": "ok", "created": [ { "tokenuuid": "550e8400-e29b-41d4-a716-446655440000", "tokenbase": "4111111111111111", "record": "4532015112830366", "tokentype": "creditcard" }, { "tokenuuid": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "tokenbase": "5500005555555559", "record": "5467047429390590", "tokentype": "creditcard" } ] } ``` ### Read and delete in bulk Bulk read and delete return or destroy plaintext for many records at once, so they require a short-lived **[unlock UUID](/pro/api/authentication#bulk-unlock-uuid)** as an extra authorization step. Call `BulkListUnlock` first, then pass the returned `unlockuuid` to `BulkListTokens` or `BulkDeleteTokens` along with the token UUIDs. ```bash theme={null} # 1. Obtain an unlock UUID curl -X POST https://databunker.pro/v2/BulkListUnlock \ -H "X-Bunker-Token: " \ -H "X-Bunker-Tenant: " # -> { "status": "ok", "unlockuuid": "e1f2a3b4-..." } # 2. Retrieve the original values curl -X POST https://databunker.pro/v2/BulkListTokens \ -H "X-Bunker-Token: " \ -H "X-Bunker-Tenant: " \ -H "Content-Type: application/json" \ -d '{ "unlockuuid": "e1f2a3b4-...", "tokens": ["550e8400-e29b-41d4-a716-446655440000", "6ba7b810-9dad-11d1-80b4-00c04fd430c8"] }' # -> { "status": "ok", "rows": [ { "tokenuuid": "...", "tokenbase": "...", "record": "...", "tokentype": "creditcard" }, ... ] } # 3. Delete tokens curl -X POST https://databunker.pro/v2/BulkDeleteTokens \ -H "X-Bunker-Token: " \ -H "X-Bunker-Tenant: " \ -H "Content-Type: application/json" \ -d '{ "unlockuuid": "e1f2a3b4-...", "tokens": ["550e8400-e29b-41d4-a716-446655440000", "6ba7b810-9dad-11d1-80b4-00c04fd430c8"] }' # -> { "status": "ok", "deleted": 2 } ``` ## Compliance and scale Format-preserving tokenization addresses three concerns at once: | Concern | What tokenization gives you | | - | - | | **Privacy & compliance** | Supports GDPR data minimization and reduces PCI DSS scope — real card numbers never reach your application databases, logs, or analytics systems. | | **Legacy compatibility** | Tokens keep the original format and validation rules (e.g. the Luhn check for cards), so they drop into existing schemas, validators, and downstream systems without changes. | | **Scale** | Data partitioning and bulk endpoints handle millions of records at high throughput. | ## Next steps * [PII vault](/pro/get-started/pii-vault) — tokenizing a whole user record rather than a single value * [Access control](/pro/administration/access-control) — restricting who can detokenize, and which fields come back * [Licensing and limits](/pro/get-started/licensing#what-counts-as-a-record) — a standalone token counts as one record # Developer tools Source: https://docs.databunker.org/pro/developer-tools/overview Official clients for JavaScript, Python, PHP and Java. Each one wraps the same REST API, so anything in the [API reference](/pro/api/overview) is reachable from every SDK. Every SDK needs a running instance to talk to. The fastest way to get one is [demo mode](/pro/get-started/quickstart) — a single `docker run`, no database required. ## Install > [tab] JavaScript > > ```bash theme={null} > npm install databunkerpro-js > ``` > > The package ships CommonJS, ES module and browser builds from one install. > > ```javascript theme={null} > // ES modules > import DatabunkerproAPI from "databunkerpro-js"; > > // CommonJS > // const { DatabunkerproAPI } = require("databunkerpro-js"); > > const api = new DatabunkerproAPI( > "https://your-databunker-instance.com", > "YOUR_ACCESS_TOKEN" > ); > > const user = await api.createUser({ email: "jane@example.com", name: "Jane" }); > console.log(user.token); > ``` > > In a browser, loading the bundled build directly exposes the client as `window.DatabunkerproAPI`: > > ```html theme={null} > > > ``` > > > [!WARNING] > > > > Only do this for an internal admin console. A token shipped to a browser is readable by anyone with devtools — see [access control](/pro/administration/access-control) for scoping one down before it leaves your server. > [tab] TypeScript > > ```bash theme={null} > npm install databunkerpro-js > ``` > > Type definitions are bundled — there is no separate `@types` package to install. > > ```typescript theme={null} > import DatabunkerproAPI from "databunkerpro-js"; > > const api = new DatabunkerproAPI( > "https://your-databunker-instance.com", > process.env.DATABUNKER_TOKEN! > ); > > const user = await api.createUser( > { email: "jane@example.com", name: "Jane" }, > { finaltime: "365d" } // optional: retention, group and role assignment > ); > ``` > > Method parameters are typed, including the option objects (`UserOptions`, `FileOptions`, `LegalBasisOptions` and so on), so wrong argument shapes fail at compile time. > > Responses are returned as `any`, because the fields a call returns depend on the caller's [policy](/pro/administration/access-control) — masked fields are either `"***"` or absent entirely. Declare the shape you expect at the call site: > > ```typescript theme={null} > interface UserRecord { > status: string; > token: string; > profile?: { > email?: string; > name?: string; > }; > } > > const user: UserRecord = await api.createUser({ email: "jane@example.com" }); > > if (user.profile?.email) { > console.log(user.profile.email); > } > ``` > > > [!TIP] > > > > Mark every profile field optional in your own interfaces. A field the caller is not authorised to read is omitted from the response rather than returned empty, so non-optional fields will lie to you at runtime. > [tab] Python > > ```bash theme={null} > pip install databunkerpro > ``` > > Requires Python 3.7 or later. > > ```python theme={null} > from databunkerpro import DatabunkerproAPI > > api = DatabunkerproAPI( > base_url="https://your-databunker-instance.com", > x_bunker_token="YOUR_ACCESS_TOKEN", > ) > > user = api.create_user({"email": "jane@example.com", "name": "Jane"}) > print(user["token"]) > ``` > [tab] PHP > > ```bash theme={null} > composer require securitybunker/databunkerpro-php > ``` > > Requires PHP 7.3 or later, with the `curl` and `json` extensions. > > ```php theme={null} > use DatabunkerPro\DatabunkerproApi; > > $api = new DatabunkerproApi( > 'https://your-databunker-instance.com', > 'YOUR_ACCESS_TOKEN' > ); > > $user = $api->createUser(['email' => 'jane@example.com', 'name' => 'Jane']); > echo $user['token']; > ``` > [tab] Java > > The Java client is published to **GitHub Packages** and **JitPack** rather than Maven Central. GitHub Packages requires authentication, so JitPack is usually the simpler route: > > ```xml theme={null} > > > jitpack.io > https://jitpack.io > > > > > com.github.securitybunker > databunkerpro-java > v1.1.0 > > ``` > > ```java theme={null} > DatabunkerproApi api = new DatabunkerproApi( > "https://your-databunker-instance.com", > "YOUR_ACCESS_TOKEN", > null // tenant name, multi-tenant deployments only > ); > > Map profile = new HashMap<>(); > profile.put("email", "jane@example.com"); > profile.put("name", "Jane"); > > Map user = api.createUser(profile, null, null); > System.out.println(user.get("token")); > ``` > > Optional arguments have no defaults in Java, so pass `null` for the options and request-metadata parameters when you do not need them. Options are built with the typed builders — `UserOptions`, `FileOptions`, `BasicOptions`: > > ```java theme={null} > UserOptions options = UserOptions.builder().finaltime("365d").build(); > Map user = api.createUser(profile, options, null); > ``` > [!NOTE] > > The third constructor argument on every SDK is the tenant name, used only in [multi-tenant](/pro/administration/multi-tenancy) deployments. Leave it empty or `null` otherwise. ## Source repositories > [card] [JavaScript SDK](https://github.com/securitybunker/databunkerpro-js) > [card] [Python SDK](https://github.com/securitybunker/databunkerpro-python) > [card] [PHP SDK](https://github.com/securitybunker/databunkerpro-php) > [card] [Java SDK](https://github.com/securitybunker/databunkerpro-java) ## Choosing between the SDK and raw HTTP The SDKs are thin — they handle authentication headers, request shaping and error propagation, and nothing else. There is no local caching, no retry logic and no connection pooling beyond what the underlying HTTP client provides. If you already have a hardened HTTP layer, calling the [REST API](/pro/api/overview) directly is a perfectly reasonable choice. What the SDKs do save you is the per-endpoint request shaping, which is where most integration bugs come from: knowing that `mode` and `identity` travel together, that bulk endpoints need an [unlock uuid](/pro/api/authentication#bulk-unlock-uuid) first, and which parameters are optional. ## Next steps * [Quickstart](/pro/get-started/quickstart) — get an instance running in one command * [Authentication](/pro/api/authentication) — issuing and scoping the tokens these clients pass * [API reference](/pro/api/overview) — the full endpoint list # Architecture Source: https://docs.databunker.org/pro/get-started/architecture How Databunker Pro is put together — backend storage options, the two-layer encryption and key management model, deployment and scaling topology, and the tokenization paths for user records and payment data. ## Core architecture overview **Backend storage** * **PostgreSQL**: Reliable, secure backend for encrypted data storage. Supports multi-tenancy using RLS. * **MySQL**: Secure backend for encrypted data storage. Supports multi-tenancy. * **Oracle**: Secure backend for encrypted data storage. Supports multi-tenancy. * **Redis**: Used for encrypted storage of session information for faster, secure access. **Encryption and key management** * **Two-layer encryption**: Master encryption key secured by a separate wrapping key. * **Wrapping key rotation**: Rotate without re-encrypting all stored data. * **Shamir’s Secret Sharing**: Backup the wrapping key securely across multiple trusted parties. **Privacy management** * **DPO portal** for oversight and reporting. * **Consent management**, **audit trails**, and **data minimization** features built-in. * **One-click personal data reports** and full processing activity logs for compliance. **Scalability and deployment** * **Stateless architecture** for easy horizontal scaling on Kubernetes. * **High availability** with multi-instance deployment and database failover readiness. * **Container-based deployment**: Docker, Docker Compose, and Kubernetes templates included. * **Multi-jurisdiction deployment** — for global organisations subject to data-localisation laws in multiple countries, the recommended pattern is to run one Databunker Pro instance per jurisdiction, unified for operations via [Databunker DPO](https://databunker.org/use-case/dpo-management-portal/). See [Multi-jurisdiction deployment](/pro/concepts/global-deployment). **Integration** * Available client libraries for **PHP**, **JavaScript/TypeScript**, **Java**, and **Python** to simplify integration. * For SaaS and database connectors used in data-subject-rights and DPO workflows (Salesforce, HubSpot, MailChimp, MySQL, PostgreSQL, Oracle, SQL Server), see the separate **Databunker DPO** product in the Databunker Portal. ![Architecture diagram](https://mintcdn.com/databunker-a1572a73/qL-_zKq-_GLjhX3S/pro/get-started/databunker-diagram.png?fit=max\&auto=format\&n=qL-_zKq-_GLjhX3S\&q=85\&s=1bc2c4a9baa75dcc7f144c7a6a7f6be1) ## Security architecture deep dive **Data protection** * **SSL/TLS encryption** for all API and database communication. * **AES-256 encryption** at rest for all personal data. * **Secure hash-based indexing** for searchable fields like email, phone number, and login names. * **Zero clear-text storage** of sensitive information. **Access control** * Fine-grained, token-based API authentication. * Multi-tenant separation is supported on PostgreSQL, MySQL, and Oracle. On PostgreSQL it uses native Row-Level Security (RLS). * Default prevention of bulk data extraction. **Threat protection** * SQL injection prevention, API rate limiting, and session hardening. **Key management** * Wrapping key rotation and Shamir’s Secret Sharing-based key backups. *** # Specialized data protection features ## PII / PHI / KYC Data Tokenization / User Table Replacement Databunker Pro enables secure tokenization for full personal profiles (PII/PHI/KYC): * Accepts complete user profile JSON objects and generates a single token representing the full profile. * Builds secure hash-based search indexes automatically for searchable fields (e.g., email, phone number, login names), allowing efficient, privacy-preserving lookups. * Dynamic token expiration options, supporting both sliding and final expiration modes. * Tokens can be safely stored and used across internal systems without revealing sensitive information. ## Credit card tokenization For sensitive payment data, Databunker Pro offers dedicated credit card tokenization capabilities: * Each credit card is tokenized into a secure, unique identifier. * Supports **unique token generation** (same card → same token if enabled). * Dynamic token expiration options, supporting both sliding and final expiration modes * **Bulk tokenization support**: tokenize multiple credit cards efficiently in a single API request, with per-record expiration and validation. *** ## Real-world applications Organizations across industries use Databunker Pro to protect critical personal data: * **Financial Services**: Safeguarding customer PII while maintaining regulatory compliance. * **Healthcare Providers**: Protecting PHI with HIPAA-aligned security controls. * **E-commerce Platforms**: Managing customer data with GDPR compliance and strong privacy controls. * **SaaS Providers**: Implementing true multi-tenant security for user data. *** ## Next steps * [Security overview](/pro/get-started/security-overview) — the control set behind this architecture * [Performance and sizing](/pro/get-started/performance) — measured throughput and how to size each tier * [Quickstart](/pro/get-started/quickstart) — try the API against a throwaway instance first * [Installation](/pro/installation/docker-compose) — deploy with Docker Compose or Kubernetes # Frequently asked questions Source: https://docs.databunker.org/pro/get-started/faq > [accordion] How does Databunker Pro manage sensitive data tokenization? > > * Tokenizes entire user records (e.g., PII, PHI, KYC, PCI data) using UUID tokens or format-preserving tokens for specific data records (e.g., credit cards). > * Encrypts data with AES-256 and stores it in a secure vault. > * Provides access via RESTful APIs with role-based access controls (RBAC). > * Supports multi-tenancy for secure management of multiple clients. > [accordion] How is tokenization handled for multi-cloud or hybrid environments? > > * Supports multi-cloud and hybrid deployments via Docker Compose, Helm charts, or a cloud-hosted version. > * Uses a stateless architecture for consistency across environments with a centralized secure vault for token mapping. > * Enables multi-tenancy for secure data separation in shared cloud or hybrid setups. > * Offers APIs for seamless integration with cloud-native or on-premises systems. > [accordion] Does Databunker Pro implement tokenization for PII, card data, or account information? What approach is used? > > * Supports PII, card data (PCI), and account information (KYC). > * Tokenizes entire records with UUIDs or uses format-preserving tokenization for specific records (e.g., credit card numbers). > * Maintains data usability while ensuring security. > [accordion] Is there a secure vault for storing token-to-data mappings, or is a deterministic, format-preserving method used without a vault? > > * Uses a secure vault to store AES-256-encrypted token-to-data mappings. > * Offers format-preserving tokenization for specific records (for example for credit cards). > * Ensures secure storage and retrieval with isolated vaults for different clients via multi-tenancy. > [accordion] Are encryption, secure APIs, and access controls in place during tokenization workflows? > > * Encrypts data with AES-256 encryption. > * Uses secure RESTful APIs with RBAC to handle tokenization. > * Supports mutual TLS and certificate pinning for legitimate API access. > * Requires time-based tokens for special handling of bulk requests. > * Defines retrievable fields with a masking policy, masking others. > [accordion] What are the authentication, encryption, and access control mechanisms for the token vault? > > * **Authentication**: Uses temporary UUID-based access tokens (more secure than JWT, as user identity like email/ID isn’t encoded). Supports passwordless options (e.g., one-time codes via email/SMS) for the optional user portal. > * **Encryption**: Employs AES-256 for data and vault storage with secure indexing for searches. > * **Access Controls**: Restricts vault access with RBAC and a masking policy defining retrievable fields (others masked). Tracks operations with audit trails. Ensures secure data isolation for different clients via multi-tenancy. > [accordion] Does the tokenization process align with regulations like RBI, PCI DSS, GDPR, etc.? > > * Engineered to operate inside compliance programmes including **RBI, DPDPA, PCI DSS, GDPR, HIPAA, FERPA, ISO 27001, and SOC 2**. Databunker Pro provides the technical controls (AES-256 encryption, hashed indexing, CRBAC, audit trail, tenant isolation, key management) these frameworks require. > * Databunker Pro has historically been self-hosted, so customers typically inherit cloud-provider certifications (AWS, Azure, GCP) and add their own organisational SOC 2 / ISO 27001 on top. > * Product-level **SOC 2** attestation is in progress for the managed cloud offering (Databunker Portal) — expected within \~2–3 months. **ISO 27001** product-level certification is roadmapped alongside SOC 2. > * Supports data minimization, user consent management, audit trails, and a User Privacy Portal for data subject rights. > * Meets RBI's data localization and GDPR's privacy requirements via self-hosted in-region deployment. > * Provides multi-tenancy for compliance in multi-client environments. > [accordion] What about IRAP for Australian deployments? > > * Databunker Pro is not currently IRAP-assessed at the product level. > * Because Databunker Pro is self-hosted inside your own cloud tenant, it inherits the IRAP boundary of the underlying platform — **AWS Sydney (`ap-southeast-2`) and Azure Australia East are IRAP-assessed at PROTECTED**, and Databunker Pro runs cleanly inside that boundary. > * A product-level IRAP assessment can be scoped under professional services if your contract requires it. Australian public-sector and university customers typically combine the cloud platform's IRAP assessment with their own organisational IRAP scope and treat Databunker Pro as a controlled component inside it. > [accordion] What is the de-tokenization policy? Is it role-based, audited, and strictly controlled? > > * Role-based de-tokenization requiring RBAC permissions. > * Defines retrievable fields with a masking policy, masking others. > * Audits all operations with strict controls for compliance. > * Ensures tenant-specific de-tokenization via multi-tenancy. > [accordion] What audit and monitoring capabilities are provided for tokenization activities? > > * Provides comprehensive audit trails, logging all tokenization and de-tokenization activities (user, timestamp, data accessed, data before and after change). > * Currently offers no special monitoring capabilities beyond audit logs. > * Segregates audit logs per client via multi-tenancy. > [accordion] How is high availability and disaster recovery ensured for the tokenization engine? > > * Ensures high availability as a stateless service through containerized deployments (Docker, Helm) with load balancing. > * Supports disaster recovery via database backups (PostgreSQL/MySQL/Oracle) and replication. > [accordion] Is the tokenization system scalable to support large transaction volumes (e.g., millions of transactions per day)? What are the performance benchmarks? > > Yes. Databunker Pro is built in Go on a stateless, horizontally-scalable architecture. A recent internal benchmark — a single Databunker Pro instance on AWS EC2 `m6i.2xlarge` backed by a **dedicated AWS RDS PostgreSQL** database (10,000,000 records, 120-field user profiles) — sustained **\~5,800 records/sec** on bulk writes with linear scaling, ingesting 10 M records in \~28 minutes. Detokenisation (`UserGet`) ran at \~14 ms p50. Throughput **scales by adding stateless Databunker Pro instances** against the same database. At small table sizes this is near-linear (a short 6-instance test reached \~34,400 records/sec); at large row counts the **database CPU** becomes the limit (a sustained 50 M, 4-instance run drove RDS to \~80% CPU at \~11,800 records/sec), so size up the database as you grow. See the [performance page](/pro/get-started/performance) for the full sizing guide. > > For the full benchmark methodology, latency / throughput / storage numbers, and capacity-planning guidance, see [Performance & benchmarks](/pro/get-started/performance). > [accordion] How is token uniqueness ensured? Do you use randomization, hashing with salt, or cryptographic mapping? > > * Ensures token uniqueness by checking for duplicate records in the database and regenerating UUID tokens if duplicates are found. > * Uses cryptographic mapping for format-preserving tokens with hash-based indexing and salts for deduplication. > * Maintains unique tokens per tenant via multi-tenancy. > [accordion] What cryptographic algorithms are used in token generation? Are they NIST-compliant? > > * Uses AES-256 for encryption, SHA-256 for secure indexing, and cryptographic UUIDs or format-preserving methods for token generation. > * Aligns with NIST standards for encryption and key management. > * Supports secure multi-tenant environments. > [accordion] How are keys managed in the tokenization process? Are they stored in an HSM? What is the key rotation and lifecycle management policy? > > * Manages keys securely with a **master key** (never exposed) encrypting sensitive data in the vault using AES-256. > * Protects the master key with a **wrapping key**, storable as a Kubernetes secret or retrievable from AWS Key Vault, HashiCorp Vault, or HSMs (requires custom development). > * Supports **Shamir’s Secret Sharing** for generating wrapping keys, requiring 3 out of 5 key shares to reconstruct. > * Configures key rotation following best practices for lifecycle management. > [accordion] What mechanisms prevent token mapping leakage or reverse engineering of the token? Is there protection against brute-force or pattern analysis? > > * Prevents leakage and reverse engineering by using tokens (UUID-based or format-preserving) as pointers to AES-256-encrypted data in a secure vault. > * Ensures tokens contain no inherent data, making reverse engineering infeasible without vault access. > * Protects against brute-force or pattern analysis with RBAC, audit logs, and optional mutual TLS. > * Prevents cross-tenant leakage via multi-tenancy. > [accordion] How does Databunker Pro handle tokenization for structured and unstructured data? Is it applicable to database fields, documents, or images (e.g., OCR data)? > > * Tokenizes structured data (e.g., database fields like PII, or credit cards in PCI). > * For unstructured data (e.g., documents, OCR-extracted data), recommends generating a random password, saving it in the user profile, and using it to encrypt the original file. > [accordion] What happens if underlying data is updated after a token is generated and sent to the cloud? Is a new token generated, or is the old token updated? > > * Maintains the existing token’s validity, mapping to the updated data in the vault. > * Generates no new token unless a new record is created (checked via deduplication). > * Audits and encrypts updates, ensuring tenant-specific updates via multi-tenancy. > * Record versioning is supported as an optional mode (see [Record Versioning](/pro/concepts/record-versioning)). When enabled, every create and update retains an immutable version of the record with integrity checks, supporting forensic review, compliance audits, and rollback. # Licensing and limits Source: https://docs.databunker.org/pro/get-started/licensing What a Databunker Pro license controls, what counts as a record, how many licenses a deployment needs, and how the vault behaves when the record cap or the expiry date is reached. A Databunker Pro license controls two things: **how many records the vault can hold** and **when the license expires**. It does not gate features. Every capability — fuzzy search, format-preserving tokenization, multi-tenancy, file vault, record versioning, Shamir key shares — is available in every mode, including Trial. ## What counts as a record **One user profile is one record**, and everything attached to that profile is included in it: * Consents and legal basis * Application data * Sessions * The complete [version history](/pro/concepts/record-versioning) Enabling record versioning does not multiply your record count. A value tokenized through the [format-preserving tokenization](/pro/concepts/tokenization) API — a credit card, for example — also counts as one record. But a card stored **inside** a user profile is not metered separately: profile plus card is a single record. User profiles and format-preserving tokens draw on one shared pool. In practice, your record count is your user count. ## How many licenses you need A license is scoped to **one deployment — that is, one database**. The key is stored in the vault's own database, so every Databunker Pro instance pointed at that database shares one license. | Situation | Licenses needed | | - | - | | One instance | 1 | | Horizontal scaling / high availability — several stateless instances, one database | **1** | | Dev, QA, staging | One key per environment, requested in the portal — **three-month** term | | [Multi-jurisdiction deployment](/pro/concepts/global-deployment) — one vault per region | 1 per region, since each has its own database | > [!NOTE] > > The [sizing guide](/pro/get-started/performance#how-to-size-your-deployment) recommends running several stateless instances against a single database for large vaults. That is covered by a single license — you are not licensed per container. ### Non-production environments Development, QA, and staging deployments do not have to share your production license. Request a separate key for each in the [Databunker Portal](https://portal.databunker.org) — no sales call needed. Each is issued with a **three-month term**, and you can request a new one from the portal when it needs renewing. This keeps test data out of your production record count, and means staging never has to point at the production vault. > [!WARNING] > > A non-production key expires like any other. When it does, that environment degrades to [read-only](#when-the-license-expires) and writes return `License expired` — which will surface as failing integration tests or a broken staging sign-in rather than an obvious licensing error. Track the expiry date and renew before it lapses. ## Modes and caps > [tab] No license key > > Leaving the license key empty at setup runs Databunker Pro in **Trial mode**: up to **1,000 records**, valid for **14 days** from the moment the vault is initialised. > > > [!WARNING] > > > > Trial mode expires 14 days after setup. When it does, the vault degrades to read-only and write calls return `License expired`. For anything longer than a two-week evaluation, generate a trial key from the portal instead — it raises the limit to 1 million records and the window to 30 days. > [tab] Trial license key > > Create a free account at [portal.databunker.org/trial](https://portal.databunker.org/trial) to generate a trial key covering up to **1 million records for 30 days**. This is the right choice for any evaluation involving realistic data volumes, and it more than doubles the evaluation window compared with running without a key. > [tab] Paid license key > > A paid key carries its own record limit and expiry date, set to match your plan. > > Request a production license from the [Databunker Portal](https://portal.databunker.org). We will get in touch to agree the scope, and once it is approved the key becomes available to fetch from the portal — the same place you generate your non-production keys. > > See [Databunker plans](https://databunker.org/plans/) for the available tiers. Apply or replace a key on a running instance at any time — see [Update the license key](/pro/howtos/update-license). No restart is required. ## When the record cap is reached Four API calls create new records and are refused with `403 Record limit reached`: * `UserCreate` and `UserCreateBulk` * `TokenCreate` and `TokenCreateBulk` Everything else keeps working. Reading, updating, patching, and deleting records are unaffected, so an application at its cap continues to serve users normally — it just cannot add new ones. > [!NOTE] > > The limit is checked once before a write begins, not per record. A bulk request that starts below the cap completes in full and can finish slightly above it. Treat the cap as the point at which new records stop being accepted, rather than an exact ceiling. ## When the license expires There is no grace period. Once the expiry date passes, the vault degrades to **read-only**: calls that store or modify data return `403 License expired`, while reads, exports, and deletions keep working. This is deliberate. Your data is never held hostage by a lapsed license — you can always retrieve every record, and you can still honour erasure requests. **Calls refused while expired** | Area | Calls | | - | - | | User records | `UserCreate` · `UserCreateBulk` · `UserUpdate` · `UserPatch` · `UserUpdateRequest` · `UserPatchRequest` | | Application data | `AppdataCreate` · `AppdataUpdate` · `AppdataUpdateRequest` | | Files | `FileCreate` | | Format-preserving tokens | `TokenCreate` · `TokenCreateBulk` | | Sessions | `SessionUpsert` | | Agreements | `AgreementAccept` · `AgreementCancel` · `AgreementRevokeAll` | | Shared records | `SharedRecordCreate` | | Tenants | `TenantCreate` · `TenantUpdate` | Reads, searches, reports, audit access, bulk export, and all delete operations — including right-to-be-forgotten erasure — continue to work. > [!WARNING] > > If your application uses Databunker Pro for [session storage](/pro/api/overview), note that `SessionUpsert` is on the refused list: an expired license stops new sessions from being written, which prevents users from signing in. Treat license renewal as a production dependency, not a billing formality. ## Checking your usage `SystemGetSystemStats` reports current usage against your license, so you can alert on it before hitting the cap: ```bash theme={null} curl -X POST http://localhost:3000/v2/SystemGetSystemStats \ -H "X-Bunker-Token: YOUR-ROOT-TOKEN" \ -H "Content-Type: application/json" ``` The response includes three license fields: | Field | Meaning | | - | - | | `totalnumrecords` | Records currently stored — user profiles plus format-preserving tokens | | `licensemaxrecords` | The record cap from your license | | `licensefinalexpiration` | License expiry as a Unix timestamp | > [!TIP] > > Alert on `totalnumrecords / licensemaxrecords` crossing 80%, and on `licensefinalexpiration` coming within 30 days. Both failures are silent until a write is refused. ## Next steps * [Update the license key](/pro/howtos/update-license) — apply a new or renewed key to a running instance * [Performance and sizing](/pro/get-started/performance) — choose database and instance sizes for your record count * [Errors reference](/pro/api/errors) — the full list of API error messages # Databunker Pro Source: https://docs.databunker.org/pro/get-started/overview Databunker Pro is a self-hosted secure vault and a safer alternative to traditional user tables in SQL and NoSQL databases. It encrypts sensitive data (PII, PHI, PCI, KYC) and the documents behind it — passports, contracts, ID scans — replacing them in your database with safe, random tokens, without slowing down your app’s performance. A single instance serves 10M user records with \~14 ms lookups, and scales out to 100M. Every number is [measured](/pro/get-started/performance). ## The Big Problem with Traditional Database Encryption Traditional database encryption solutions often provide a false sense of security. While they may encrypt data at rest, they leave critical vulnerabilities: * **Encryption alone isn’t enough:** Most vendors offer disk-block encryption, ignoring API-level encryption * **Vulnerable GraphQL Queries:** Unfiltered queries can expose unencrypted data to attackers * **SQL Injection Risks:** Attackers can retrieve plaintext data through SQL injections Databunker Pro addresses these gaps with a secure, developer-focused solution for personal data tokenization and encrypted file storage. ## Enterprise security features * [Fuzzy search](/pro/concepts/fuzzy-search) — find a record from a misspelled name or partial email * [Multi-tenancy](/pro/administration/multi-tenancy) — isolate customers at the database level * [Key rotation](/pro/administration/key-rotation) — replace the wrapping key without re-encrypting the vault * [File Vault](/pro/concepts/file-vault) — store passports and contracts encrypted per user * [Record versioning](/pro/concepts/record-versioning) — keep the full history of every profile change * [Shamir's secret sharing](/pro/administration/shamir-keys) — split the recovery key so no one person holds it * [Advanced access control](/pro/administration/access-control) — scope a token to one app, group, or document type * [Format-preserving tokenization](/pro/concepts/tokenization) — tokens that keep the shape of a card number * [Multi-jurisdiction deployment](/pro/concepts/global-deployment) — keep each region's data in its own vault ## How It Works 1. Store sensitive data in Databunker Pro via API calls 2. Receive UUID tokens to reference data securely in your application 3. Query data using secure, hash-based indexing 4. Benefit from built-in protections against injections and bulk data leaks ![Pseudonymized identity](https://mintcdn.com/databunker-a1572a73/qL-_zKq-_GLjhX3S/pro/get-started/databunker-short-diagram.png?fit=max\&auto=format\&n=qL-_zKq-_GLjhX3S\&q=85\&s=a40c2a15b19cb6f2ed01d864ff238ee9) ## Compare Databunker Pro with popular tools > [card] [Databunker Pro vs AWS Cognito](/pro/comparisons/aws-cognito-alternative) > [card] [Databunker Pro vs HashiCorp Vault](/pro/comparisons/hashicorp-vault-alternative) > [card] [Databunker Pro vs Custom PII Vault](/pro/comparisons/custom-solution-alternative) ## Try it out for yourself Start a throwaway instance with one command — no database, no configuration, erased when the container stops: ```bash theme={null} docker run -p 3000:3000 -d --rm --name databunkerpro securitybunker/databunkerpro demo ``` Then follow the [quickstart](/pro/get-started/quickstart) to create a user record and store an encrypted file. Or explore common use cases in our hosted sandbox. > [card] [Secure user profile storage](https://databunker.org/user-table-replacement-demo/) > [card] [Credit card and PCI tokenization](https://databunker.org/pci-tokenization-demo/) > [card] [Consent storage and management](https://databunker.org/consent-management-demo/) > [card] [Encrypted file and document storage](https://databunker.org/file-storage-demo/) > [card] [Scoped role access tokens](https://databunker.org/role-access-token-demo/) > [card] [Parental control over a minor's data](https://databunker.org/parental-control-demo/) # Performance & benchmarks Source: https://docs.databunker.org/pro/get-started/performance Measured Databunker Pro throughput, detokenisation latency, and storage at 10M, 50M, and 100M records on dedicated AWS RDS PostgreSQL (plus a 10M Oracle comparison) — with a sizing guide for choosing database and application instances by record count. This page gives architects the numbers needed to size a Databunker Pro deployment. Every figure below is **measured** — we loaded a 120-field user-profile vault to **10, 50, and 100 million records** against a **dedicated AWS RDS PostgreSQL** database and recorded throughput, latency, storage, and resource utilisation. The methodology is documented so you can reproduce it with your own payloads. ## At a glance * **Storage is linear and predictable: \~5.7 KB per encrypted 120-field record.** Multiply by your record count to size the volume (10 M ≈ 59 GB, 100 M ≈ 585 GB). * **Index size scales with how many fields you make searchable — plan for *your* field set.** This benchmark indexed **only `email`** (plus the always-present `token` and retention indexes) → \~139 bytes/record. **Each additional searchable field you index (`phone`, `login`, `custom`) adds another index: budget roughly +40–50 bytes/record and more write CPU per field.** Size the database RAM to cache *all* your indexes (with email only, 100 M ≈ 14 GB; cache-hit ≥ 97%). * **Detokenisation is fast: \~14 ms** per single-record `UserGet`, regardless of vault size. * **Write speed depends on scale.** At small scale the **Databunker Pro app** is the limit and one instance does \~5,800 records/sec. At tens of millions of rows the **database** becomes the limit and write speed tops out around **\~12,000 records/sec** — so you size the **database** for large vaults, not the app tier. * **Rule of thumb:** pick your database and application instances from the [sizing guide](#how-to-size-your-deployment) by record count. For most workloads a single Databunker Pro instance is already more than enough. * **Running on Oracle instead?** A comparable 10 M run on RDS Oracle SE2 is included below: similar (slightly faster) read latency, **\~2.4× slower writes at peak** (PostgreSQL's multi-row `INSERT` is more efficient than Oracle's `INSERT ALL`), and roughly **3× the on-disk size** (`CLOB` storage). See [Oracle Database backend (10 M)](#oracle-database-backend-10-m). ## What we measured Three runs, same workload, increasing scale. In every run Databunker Pro (stateless, in Docker) ran on EC2 with the load generator co-located, writing to a **dedicated RDS PostgreSQL 16** instance in the same VPC (`eu-central-1`). Multiple app instances share one database and one wrapping key. | Run | Records | Application tier | Dedicated RDS database | Write result | | - | - | - | - | - | | **A** | 10 M | 1 × `m6i.2xlarge` | `db.m6i.2xlarge` — 8 vCPU / 32 GB | \~5,800 rec/s — **limited by the app** | | **B** | 50 M | 4 × `m6i.2xlarge` | `db.m6i.4xlarge` — 16 vCPU / 64 GB | \~11,800 rec/s — **limited by the database** | | **C** | 100 M | 5 × `m6i.2xlarge` | `db.m6i.8xlarge` — 32 vCPU / 128 GB | \~11,900 rec/s — **limited by the database** | **Common workload** * **Profile:** 120 fields per record (mixed PII + custom application fields). * **Write path:** `UserCreateBulk` at **4,000 records/request, 8 concurrent workers per instance**. * **Storage & encryption:** gp3 volumes; **AES-256 at rest, TLS in transit** (defaults). * **Indexes per record:** every user always has a unique **token** index (the detokenisation lookup) and a **retention** (`finaltime`) index. Search fields add one salted-hash index each — this benchmark sets only `email`, giving **three indexes/record** (\~139 bytes total). Databunker Pro can also index `phone`, `login`, and `custom` (a hashed index is written only when the field is present); setting those adds per-insert database CPU and lowers sustained write throughput at scale. `name` and the other profile fields are encrypted but not indexed. * **Placement:** loaders co-located with Databunker Pro (no client-side network noise); the only network hop measured is **App → RDS**. > [!NOTE] > > Redis is used only for transient session state and is **not** exercised by bulk writes; a production deployment points all instances at a shared Redis cluster. A separate 5 M run with PostgreSQL **co-located** on the app host managed only \~1,700 rec/s — moving to a **dedicated** database roughly tripled write throughput, which is why every run here uses dedicated RDS. ## Results | Records | DB size | Per-record | Indexes | Sustained bulk write | Detok p50 | Bottleneck | | - | - | - | - | - | - | - | | **10 M** | 58.5 GB | \~5.7 KB | 1.4 GB | **\~5,800 rec/s** (1 instance) | \~14 ms | app tier (RDS \~20% CPU) | | **50 M** | 292 GB | \~5.7 KB | 6.9 GB | **\~11,800 rec/s** (4 instances) | — | database (RDS \~80% CPU) | | **100 M** | 584 GB | \~5.7 KB | 13.9 GB | **\~11,900 rec/s** (5 instances) | — | database (RDS \~82% CPU) | | 150 M | \~875 GB | \~5.7 KB | \~21 GB | limited by the database *(projected)* | — | database | | 200 M | \~1.17 TB | \~5.7 KB | \~28 GB | limited by the database *(projected)* | — | database | All runs completed with **zero failed batches**. Per-record storage is essentially constant across scale — storage planning is simple linear math. ## The key insight: the bottleneck moves with scale This is the single most important thing to understand when sizing Databunker Pro. **At small scale, the application tier is the limit.** Encrypting and hash-indexing each record is CPU work done by Databunker Pro. At 10 M records one instance used \~3.2 of its 8 cores while the database sat at just \~20% CPU. Here, **adding Databunker Pro instances raises throughput** — the stateless app tier scales cleanly (we verified throughput grew almost proportionally from 1 to 6 instances on a small vault), and the database has plenty of spare capacity. **At large scale, the database CPU is the limit.** As the table grows, every insert costs the database more (deeper B-tree indexes, page splits, WAL, autovacuum). By tens of millions of rows this dominates: | | 10 M (1 instance) | 50 M (4 instances) | 100 M (5 instances) | | - | - | - | - | | RDS instance | `db.m6i.2xlarge` (8 vCPU) | `db.m6i.4xlarge` (16 vCPU) | `db.m6i.8xlarge` (32 vCPU) | | **RDS CPU (avg / peak)** | **20% / 33%** | **80% / 95%** | **82% / 95%** | | Aggregate write | \~5,800 rec/s | \~11,800 rec/s | \~11,900 rec/s | | App CPU (per instance) | \~3.2 cores | maxing out the database | maxing out the database | **Write speed tops out around \~12,000 records/sec.** Note that 50 M and 100 M delivered almost the same throughput **even though the 100 M run used twice the database vCPU** (32 vs 16). Doubling the database didn't help because the per-insert cost had also doubled with the larger index. To go faster than this, database vCPU has to grow *faster* than the table. **What this means for you:** * **Steady-state and real-time workloads** are nowhere near these limits — one Databunker Pro instance on a modest database handles them comfortably. * **Bulk backfills of very large vaults are limited by the database and take hours** (100 M ≈ \~2.3 h here). Size the **database** for the row count, and don't expect more app instances to speed it up once the database is at full CPU. ## How to size your deployment Pick the row you're targeting. Storage scales at \~5.7 KB/record. Index RAM depends on **how many fields you index** — the numbers below assume the benchmark's set (`token` + retention + **one** search index, `email`) ≈ \~139 bytes/record; **add \~40–50 bytes/record for each extra searchable field** you index (`phone`, `login`, `custom`). The database is what limits speed at scale, so it's sized for **vCPU (write speed) and RAM (index cache)**. Application nodes are stateless `m6i.2xlarge` (Databunker Pro uses \~3 vCPU at full load) — add them to speed up bulk loads only until the database reaches \~70–80% CPU. | User records | RDS database instance | RDS storage (gp3) | Index size, **email only** (vs instance RAM) | App instances | Confidence | | - | - | - | - | - | - | | **≤ 10 M** | `db.m6i.2xlarge` — 8 vCPU / 32 GB | 150 GB | \~2 GB (of 32) | 1 × `m6i.2xlarge` | measured | | **10–50 M** | `db.m6i.4xlarge` — 16 vCPU / 64 GB | 500 GB | \~7 GB (of 64) | 2–4 × `m6i.2xlarge` | measured @ 50 M | | **50–100 M** | `db.m6i.8xlarge` — 32 vCPU / 128 GB | 1 TB | \~14 GB (of 128) | 4–5 × `m6i.2xlarge` | measured @ 100 M | | **100–150 M** | `db.r6i.8xlarge` — 32 vCPU / 256 GB | 1.1 TB | \~21 GB (of 256) | 4–5 × `m6i.2xlarge` | projected | | **150–200 M** | `db.r6i.8xlarge` or **Aurora PostgreSQL** | 1.3–1.5 TB | \~28 GB | 4–6 × `m6i.2xlarge` | projected | The **index column is for the benchmark's index set only** (`token` + retention + the single `email` search index). Note the large spare capacity — 14 GB of indexes on a 128 GB instance — because these instances are chosen for **write vCPU**, not index RAM, so they hold several more indexes comfortably. **If you index more fields, recompute:** \~139 bytes/record (email only) **+ \~40–50 bytes/record per additional searchable field** (`phone`, `login`, `custom`), × your record count, and confirm it still fits in RAM. Storage and write vCPU are unaffected by this — only index RAM and per-insert write cost grow. **Three sizing rules** 1. **Storage** = 5.7 KB × records, plus **30–40% spare space** for WAL, bloat, and backups. 2. **RAM** must exceed your **total index size + hot rows** so lookups stay cached. Index storage = `token` + retention + **one per searchable field**. With only `email` indexed this was \~139 bytes/record (100 M ≈ 14 GB; cache-hit ≥ 97%); **add \~40–50 bytes/record for every extra field you index** (`phone`, `login`, `custom`). Multiply by your record count. 3. **Database vCPU** is what limits sustained write speed at scale — grow it (or move to **Aurora** for storage auto-scaling and read replicas) before adding app instances once RDS passes \~70% CPU. ## Reads: detokenisation latency Detokenisation (`UserGet`) is a hashed-index point lookup by token, measured against the fully-loaded 10 M vault: | Metric | Value | | - | - | | **Latency p50 / p95 / p99** | **\~14 ms / \~15 ms / \~16 ms** per single-record `UserGet` | | Read throughput (1 instance) | \~660 reads/sec synchronous (16 concurrent clients) | Latency is dominated by the round trip (HTTP, auth, index lookup, decryption), **not** index depth — the index cache-hit ratio stayed ≥ 97% at every scale, so lookups are served from memory. Read **throughput** scales horizontally: add Databunker Pro instances (and, for very large vaults, database read replicas) to serve more concurrent lookups. ## Storage footprint Encrypted profile blobs dominate the footprint; indexes are comparatively small (which is why a modest amount of RAM keeps them cached). | Component | 10 M | 100 M | Per record | | - | - | - | - | | Total database size | 58.5 GB | 584 GB | **\~5.7 KB** | | Encrypted profile data (TOAST) | \~55 GB | \~550 GB | \~5.5 KB | | Heap (`users` table) | 1.8 GB | \~9 GB | \~90 B | | **Indexes — email only** | 1.4 GB | 13.9 GB | **\~139 B** | The two figures that scale with your design: * **Encrypted profile data** grows with **payload size** — a bigger/smaller profile than our 120-field one moves the \~5.5 KB/record directly. * **Indexes** grow with **how many fields you make searchable.** The \~139 B/record above is the benchmark's set only — `token` (always) + retention + the single `email` search index. **Add \~40–50 B/record for each additional indexed field** (`phone`, `login`, `custom`). Storage total, heap, and per-record profile size are unaffected by indexing choices — only the index line (and per-insert write CPU) grows. ## Write latency: bulk vs single record The \~0.17 ms per record at 10 M is **averaged across a 4,000-record bulk request**. Individual `UserCreateBulk` calls take longer end-to-end (p50 \~4.5 s for a 4,000-record batch at 10 M, growing with table size), and **single-record synchronous writes** are typically 3–10 ms over a real network because each call carries its own connection, auth, and transaction overhead. * **Backfills / batch flows:** use `UserCreateBulk`. * **Real-time API flows:** assume single-digit-millisecond single-record writes; production throughput = `concurrency ÷ per-call latency`. ## Oracle Database backend (10 M) Databunker Pro also runs on [Oracle Database](/pro/installation/oracle-database). We repeated the 10 M user-record benchmark on **RDS for Oracle** so Oracle shops have a directly comparable number. **Why a different instance class.** The PostgreSQL runs above use `db.m6i.2xlarge`. In `eu-central-1`, RDS **Oracle Standard Edition 2 does not offer the `m6i` family** — its current-generation `m`-class options are `m5` and `m8i`. We therefore used **`db.m8i.2xlarge`**, the closest current-generation equivalent at the **same 8 vCPU / 32 GB**. So this is PostgreSQL on `m6i.2xlarge` vs Oracle on `m8i.2xlarge` — matched on vCPU, RAM, storage (400 GB gp3 / 12,000 IOPS), and TLS, one CPU generation apart. (We separately confirmed the instance size doesn't move Oracle's result: an identical run on `db.r6i.2xlarge` with **double the RAM, 64 GB**, produced the same throughput — the load is limited by disk I/O, not memory.) | Metric (10 M) | PostgreSQL 16 — `db.m6i.2xlarge` | Oracle SE2 19c — `db.m8i.2xlarge` | | - | - | - | | Sustained bulk write | \~5,800 rec/s — **limited by the app** | **\~5,100 rec/s** — **limited by disk I/O** | | Detok p50 / p95 / p99 | \~14 / 15 / 16 ms | **\~6.3 / 7.0 / 7.6 ms** | | Total database size | 58.5 GB | **169 GB** | | Per-record on disk | \~5.7 KB | **\~16.5 KB** | | Index size | 1.4 GB (\~139 B/rec) | 1.4 GB (\~140 B/rec) | | RDS CPU during load (avg) | \~20% | \~18% | | Transport | TLS | TLS (TCPS :2484) | | Write path | `UserCreateBulk` 4,000 × 8 workers | `UserCreateBulk` 1,000 × 16 workers | **What the numbers say:** * **At peak, Oracle writes are about 2.4× slower than PostgreSQL** (\~5,100 rec/s vs \~12,000) — mainly because **PostgreSQL's multi-row `INSERT` is more efficient than Oracle's `INSERT ALL`** for writing a batch. On a single instance the two are close (\~5,100 vs PostgreSQL's \~5,800 here), but Oracle's load was already **limited by disk I/O** (write IOPS near the 12,000 cap while CPU sat at \~18%), so it stays around 5,100 rec/s — whereas PostgreSQL is *limited by the app* at 10 M and scales toward \~12,000 rec/s by adding stateless app instances. Pushing Oracle higher needs **more provisioned IOPS**, not more workers. * **Reads are faster: \~6 ms** detok p50 vs \~14 ms on PostgreSQL — helped by the newer `m8i` CPU. Detokenisation is a hashed-index point lookup either way. * **Storage is \~3× heavier: \~16.5 KB/record** vs \~5.7 KB. Oracle stores the encrypted profile as a `CLOB`, which is far less space-efficient than PostgreSQL's TOAST — budget storage accordingly. **Indexes are the same \~140 B/record**; the index strategy (`token` + retention + `email`) is identical across engines. > [!NOTE] > > This run covers the **Oracle SE2 user-record vault path** only. Format-preserving tokenisation uses a range-partitioned table that requires Oracle **Enterprise Edition**, so it is out of scope on Standard Edition 2 — see [Oracle Database backend](/pro/installation/oracle-database) for setup and edition guidance. ## Reproduce this benchmark Start from the open-source Python load scripts in the [`databunkerpro-python`](https://github.com/securitybunker/databunkerpro-python) SDK repo: * **[`bulk_user_creator.py`](https://github.com/securitybunker/databunkerpro-python/blob/main/bulk_user_creator.py)** — drives `UserCreateBulk`. * **[`bulk_user_fetcher.py`](https://github.com/securitybunker/databunkerpro-python/blob/main/bulk_user_fetcher.py)** — drives `UserGet` for read latency. **1. Provision** Dedicated managed PostgreSQL (RDS / Aurora / Cloud SQL) plus a separate application host in the same VPC. **2. Match your payload** Edit the profile shape in `bulk_user_creator.py` to the JSON your application actually sends. **3. Load** Run the loader co-located with Databunker Pro, with multiple concurrent workers (and multiple instances for large loads). **4. Measure** Record sustained records/sec, p50/p95/p99 bulk latency, **database CPU and IOPS**, and **application-tier CPU** — whichever is maxed out is your bottleneck. **5. Read test** Run `bulk_user_fetcher.py` against the same vault to capture `UserGet` latency and throughput. Your numbers will vary with payload size, number of search indexes, access-control policy depth, and database instance/IOPS. Contact [office@databunkertech.com](mailto:office@databunkertech.com) if you'd like the professional-services team to run a benchmark against your representative payloads. ## Scope & roadmap These runs cover the **PII vault write path** (`UserCreateBulk`) and the **detokenisation read path** (`UserGet`). They do **not** cover the secure session-storage API, format-preserving tokenisation, or agreement/legal-basis flows — those have different characteristics and are measured separately. Coming next: 150 M–200 M measured runs (to replace the projected sizing rows), secure session-storage API, format-preserving tokenisation throughput, and a MySQL backend comparison. ## Next steps * [Licensing and limits](/pro/get-started/licensing) — confirm your record cap covers the count you just sized for * [Production checklist](/pro/installation/production-checklist) — the go-live gate * [Migrate a SQL users table](/pro/migrations/sql-users-table) — bulk-load an existing table at these rates # PII Vault - PII Storage & Tokenization in Databunker Pro Source: https://docs.databunker.org/pro/get-started/pii-vault The PII Vault stores and tokenizes personal data (PII, PHI, KYC, PCI) so it never sits in your application database. When sensitive data enters your system, Databunker instantly encrypts, tokenizes, and stores it in a secure vault. You get back a safe token to store anywhere — even in public databases. You can run Databunker in the cloud or on-premises, you can enable your enterprise customers to self-host their PII vault in any region, which solves PII export restrictions and reduces compliance risk. ## What is a PII Vault? The PII Vault is Databunker Pro's core feature that transforms how organizations handle sensitive personal data. Instead of storing PII directly in your application database, the PII Vault: * **Encrypts and tokenizes** entire user records using AES-256 encryption * **Generates secure UUID tokens** that can be safely stored anywhere * **Maintains searchable indexes** using secure hash-based lookups * **Provides audit trails** for every data access and modification * **Enables compliance** with GDPR, HIPAA, SOC2, and other privacy regulations ## Why Use PII Vault Instead of Regular Database Tables? ### Traditional Database Approach Problems ```sql theme={null} -- Traditional approach: PII stored in plain text or basic encryption CREATE TABLE users ( id SERIAL PRIMARY KEY, email VARCHAR(255), -- Exposed in logs, backups, queries first_name VARCHAR(100), -- Visible to all database users last_name VARCHAR(100), -- Accessible via SQL injection phone VARCHAR(20), -- Stored in application logs ssn VARCHAR(11), -- High-risk data exposure created_at TIMESTAMP ); ``` **Issues with this approach:** * ❌ **Data exposure** in logs, backups, and error messages * ❌ **SQL injection vulnerabilities** expose sensitive data * ❌ **Database admin access** reveals all personal information * ❌ **Compliance complexity** requires extensive additional controls * ❌ **Breach impact** exposes all stored PII immediately ### Databunker Pro PII Vault Solution Instead of storing PII in your application database, store only the user secure tokens (in UUID format): ```sql theme={null} -- Modern approach: Only tokens stored in application database CREATE TABLE users ( id SERIAL PRIMARY KEY, user_token UUID -- Safe to store anywhere ); ``` **Benefits of this approach:** * ✅ **Zero PII exposure** in application databases, logs, or backups * ✅ **Breach protection** - attackers only see meaningless tokens * ✅ **Built-in compliance** with privacy regulations * ✅ **Simplified architecture** - no complex encryption management * ✅ **Audit-ready** with comprehensive access logging ## How PII Vault Works ### 1. Data Ingestion and Tokenization When sensitive data enters your system, Databunker Pro: 1. **Accepts complete user profiles** in JSON format 2. **Extracts searchable fields** (email, phone, login, custom) for indexing 3. **Encrypts the entire record** using AES-256 encryption 4. **Generates a secure UUID token** for the record 5. **Stores encrypted data** in the secure vault 6. **Creates hashed search indexes** for efficient lookups ### 2. Uniqueness and identity resolution The hashed search indexes on `email`, `phone`, `login`, and `custom` are **unique within a tenant**. This has three practical consequences: * **Duplicates cannot coexist inside the same tenant.** A second attempt to create a user record under an existing email / phone / login / custom value is rejected at the vault level — identity uniqueness is a structural guarantee, not a discipline. * **Repeat identities resolve to the same token.** When the same person appears again, look them up by their indexed field and reuse the existing token; there is no risk of accidentally minting two tokens for the same underlying identity. * **Different tenants can hold their own record for the same person.** Tenants are cryptographically isolated boundaries (enforced with PostgreSQL row-level security, and also supported on MySQL and Oracle), so the same email tokenised in two tenants produces two different tokens — this is the basis of the multi-tenant, multi-token pattern used for separating analytics, operational, and external-integration domains. Together, these properties mean that **tokens within a tenant are stable, deterministic join keys** — SQL queries that previously joined on `email` can join on `user_token` with no round-trip to the vault. ### 3. Secure Storage Architecture ![Databunker Architecture](https://mintcdn.com/databunker-a1572a73/qL-_zKq-_GLjhX3S/pro/get-started/databunker-short-diagram.png?fit=max\&auto=format\&n=qL-_zKq-_GLjhX3S\&q=85\&s=a40c2a15b19cb6f2ed01d864ff238ee9) ## Code Examples: Storing and Retrieving User Records ### Storing User PII > [tab] cURL > > ```bash theme={null} > curl -X POST https://your-databunker-pro/v2/UserCreate \ > -H "X-Bunker-Token: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "profile": { > "email": "john.doe@example.com", > "first": "John", > "last": "Doe", > "phone": "+1-555-123-4567", > "ssn": "123-45-6789", > "address": "123 Main St, City, State 12345", > "dob": "1985-06-15" > } > }' > ``` > > **Response:** > > ```json theme={null} > { > "status": "ok", > "token": "a21fa1d3-5e47-11ef-a729-32e05c6f6c16" > } > ``` > [tab] JavaScript > > ```javascript theme={null} > const axios = require("axios"); > > async function storeUserPII(userData) { > try { > const response = await axios.post( > "https://your-databunker-pro/v2/UserCreate", > { > profile: { > email: userData.email, > first: userData.firstName, > last: userData.lastName, > phone: userData.phone, > ssn: userData.ssn, > address: userData.address, > dob: userData.dateOfBirth, > }, > }, > { > headers: { > "X-Bunker-Token": process.env.DATABUNKER_API_KEY, > "Content-Type": "application/json", > }, > } > ); > > return response.data.token; // Store this token in your database > } catch (error) { > console.error("Error storing user PII:", error); > throw error; > } > } > > // Usage > const userToken = await storeUserPII({ > email: "jane.smith@example.com", > firstName: "Jane", > lastName: "Smith", > phone: "+1-555-987-6543", > ssn: "987-65-4321", > address: "456 Oak Ave, City, State 54321", > dateOfBirth: "1990-03-22", > }); > ``` > [tab] Python > > ```python theme={null} > import requests > import json > > def store_user_pii(user_data): > url = "https://your-databunker-pro/v2/UserCreate" > headers = { > "X-Bunker-Token": "YOUR_API_KEY", > "Content-Type": "application/json" > } > > payload = { > "profile": { > "email": user_data["email"], > "first": user_data["first_name"], > "last": user_data["last_name"], > "phone": user_data["phone"], > "ssn": user_data["ssn"], > "address": user_data["address"], > "dob": user_data["date_of_birth"] > } > } > > response = requests.post(url, headers=headers, json=payload) > response.raise_for_status() > > return response.json()["token"] > > # Usage > user_token = store_user_pii({ > "email": "mike.johnson@example.com", > "first_name": "Mike", > "last_name": "Johnson", > "phone": "+1-555-456-7890", > "ssn": "456-78-9012", > "address": "789 Pine St, City, State 67890", > "date_of_birth": "1988-11-08" > }) > ``` ### Retrieving User PII > [tab] Retrieve by Token > > ```bash theme={null} > curl -X POST https://your-databunker-pro/v2/UserGet \ > -H "X-Bunker-Token: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "mode": "token", > "identity": "a21fa1d3-5e47-11ef-a729-32e05c6f6c16" > }' > ``` > [tab] Retrieve by Email > > ```bash theme={null} > curl -X POST https://your-databunker-pro/v2/UserGet \ > -H "X-Bunker-Token: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "mode": "email", > "identity": "john.doe@example.com" > }' > ``` > [tab] Retrieve by Phone > > ```bash theme={null} > curl -X POST https://your-databunker-pro/v2/UserGet \ > -H "X-Bunker-Token: YOUR_API_KEY" \ > -H "Content-Type: application/json" \ > -d '{ > "mode": "phone", > "identity": "+1-555-123-4567" > }' > ``` ## Security controls Records are encrypted with AES-256, access is governed by [role-based policies](/pro/administration/access-control), and every request is written to the [audit trail](/pro/get-started/security-overview). Tenants are isolated at the database level on PostgreSQL, and the application tier scales horizontally. See the [Security overview](/pro/get-started/security-overview) for the full control set. ## Next steps * [Quickstart](/pro/get-started/quickstart) — run a vault and store your first record in one command * [Search the vault](/pro/concepts/fuzzy-search) — exact, fuzzy, and partial lookups over encrypted records * [Tokenize credit cards](/pro/concepts/tokenization) — format-preserving tokens for PCI data * [Performance and sizing](/pro/get-started/performance) — measured throughput and instance sizing by record count * [Licensing and limits](/pro/get-started/licensing) — what counts as a record # Quickstart Source: https://docs.databunker.org/pro/get-started/quickstart Run Databunker Pro locally in demo mode with a single Docker command, then create a user record and store an encrypted file through the API. Demo mode starts a complete Databunker Pro instance with no database server, no configuration, and no setup wizard. It installs itself on an in-memory SQLite database and comes up ready to accept API calls, which makes it the fastest way to evaluate the API. > [!WARNING] > > Demo mode is for evaluation only. The database is held in memory and everything is erased when the container stops, the wrapping key is a fixed public value, and the root access token is the well-known string `DEMO`. Never expose a demo instance to a network you do not control, and never use it for real personal data. For a real deployment, see [Install with Docker Compose](/pro/installation/docker-compose). ## Step 1: Start Databunker Pro ```bash theme={null} docker run -p 3000:3000 -d --rm --name databunkerpro securitybunker/databunkerpro demo ``` The container installs itself on first start. Check the logs to confirm it is ready: ```bash theme={null} docker logs databunkerpro ``` ``` Databunker Pro demo is ready Web UI: http://localhost:3000/ Root access token: DEMO Database: in-memory, erased on restart ``` Open [http://localhost:3000/](http://localhost:3000/) to reach the web interface. Select **Admin** as the login method and enter `DEMO` as the access token. > [!NOTE] > > Demo mode requires Databunker Pro **0.14.23** or later. Every API call below authenticates with the `X-Bunker-Token: DEMO` header — in a real deployment this is your root access token, generated during [setup](/pro/installation/generate-admin-credentials). ## Step 2: Create a user record Storing a user record is the most common Databunker Pro operation. The vault encrypts the profile and returns a **user token** in UUID format. ```bash theme={null} curl -X POST http://localhost:3000/v2/UserCreate \ -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d '{"profile":{"email":"john@example.com","name":"John Doe","phone":"+15551234567"}}' ``` ```json theme={null} { "status": "ok", "token": "ab88ca3e-599f-8f17-10dd-c7f424504b94" } ``` That token is a pseudonymized identity. Store it in your own database in place of the personal data — on its own it reveals nothing, and deleting the user record in Databunker Pro renders the encrypted data unrecoverable. You can read the record back by user token, or by any indexed field such as `email`, `phone`, or `login`: ```bash theme={null} curl -X POST http://localhost:3000/v2/UserGet \ -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d '{"mode":"email","identity":"john@example.com"}' ``` ```json theme={null} { "status": "ok", "token": "ab88ca3e-599f-8f17-10dd-c7f424504b94", "profile": { "email": "john@example.com", "name": "John Doe", "phone": "+15551234567" }, "version": 1 } ``` The `mode` and `identity` pair identifies the user in every call that follows. Supported modes are `token`, `login`, `email`, `phone`, and `custom`. ## Step 3: Store an encrypted file Files are attached to a user and encrypted with a per-file key that is wrapped by that user's record key. File content is supplied as base64 in the `filedata` field. The optional `tags` field labels the file by document type, so you can find it later without relying on the filename: ```bash theme={null} FILEDATA=$(base64 -i passport.jpg | tr -d '\n') curl -X POST http://localhost:3000/v2/FileCreate \ -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d "{\"mode\":\"email\",\"identity\":\"john@example.com\", \"filename\":\"passport.jpg\",\"filedata\":\"$FILEDATA\", \"tags\":[\"passport\",\"kyc\"]}" ``` ```json theme={null} { "status": "ok", "token": "d328ce46-7f2e-3a8e-bd4d-db1dc282dc87", "fileuuid": "dc42ae8d-0789-ea5a-f29b-1dbcac0fe321", "duplicate": false, "tags": ["kyc", "passport"] } ``` The `fileuuid` is the handle for this file. The MIME type was not supplied — Databunker Pro detects it from the file content and stores it, so `image/jpeg` appears in the responses below. Pass `mimetype` explicitly only when you need to override that. Tags are lowercased, de-duplicated, and sorted on write, which is why they come back in a different order than they were sent. > [!NOTE] > > File tagging requires Databunker Pro **0.14.24** or later. Tags must match `^[a-z0-9][a-z0-9._-]{0,49}$`, and a file can carry up to 16 of them. Because tags are stored unencrypted so they can be indexed, use them for document types such as `passport` or `proof-of-address` — never for personal data. Upload a second file so the next steps have something to filter: ```bash theme={null} curl -X POST http://localhost:3000/v2/FileCreate \ -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d "{\"mode\":\"email\",\"identity\":\"john@example.com\", \"filename\":\"bill.pdf\", \"filedata\":\"$(base64 -i bill.pdf | tr -d '\n')\", \"tags\":[\"proof-of-address\",\"kyc\"]}" ``` > [!TIP] > > Uploading the same content twice for the same user does not create a second copy. The response returns the existing `fileuuid` with `"duplicate": true`. ## Step 4: List the user's files ```bash theme={null} curl -X POST http://localhost:3000/v2/FileListUserFiles \ -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d '{"mode":"email","identity":"john@example.com"}' ``` ```json theme={null} { "status": "ok", "token": "d328ce46-7f2e-3a8e-bd4d-db1dc282dc87", "files": [ { "fileuuid": "dc42ae8d-0789-ea5a-f29b-1dbcac0fe321", "filename": "passport.jpg", "mimetype": "image/jpeg", "size": 24, "tags": ["kyc", "passport"], "doublehash": "8504e89336b0c924aeb1907b5fe906319cfc7b0c859eafc0c129a93e93c4b37d", "creationtime": 1785906460 }, { "fileuuid": "8325231e-3ac3-3444-706f-f0b4ccd64169", "filename": "bill.pdf", "mimetype": "application/pdf", "size": 18, "tags": ["kyc", "proof-of-address"], "doublehash": "b1dc75a124dd909e2523325db46f381a37fa7993d7de1c8427b833f76c133a4f", "creationtime": 1785906460 } ] } ``` This returns metadata only. Filenames are encrypted at rest and decrypted for the response, so the listing itself never exposes file content. Add a `tag` to return just the files carrying it — useful for checking which documents a profile is still missing: ```bash theme={null} curl -X POST http://localhost:3000/v2/FileListUserFiles \ -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d '{"mode":"email","identity":"john@example.com","tag":"proof-of-address"}' ``` ```json theme={null} { "status": "ok", "token": "d328ce46-7f2e-3a8e-bd4d-db1dc282dc87", "files": [ { "fileuuid": "8325231e-3ac3-3444-706f-f0b4ccd64169", "filename": "bill.pdf", "mimetype": "application/pdf", "size": 18, "tags": ["kyc", "proof-of-address"], "doublehash": "b1dc75a124dd909e2523325db46f381a37fa7993d7de1c8427b833f76c133a4f", "creationtime": 1785906460 } ] } ``` ## Step 5: Retrieve a file Retrieve a file by its `fileuuid`, taken from the `FileCreate` response or from the listing above. The decrypted content comes back base64-encoded in `filedata`: ```bash theme={null} curl -X POST http://localhost:3000/v2/FileGet \ -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d '{"mode":"email","identity":"john@example.com", "fileuuid":"dc42ae8d-0789-ea5a-f29b-1dbcac0fe321"}' ``` ```json theme={null} { "status": "ok", "token": "d328ce46-7f2e-3a8e-bd4d-db1dc282dc87", "fileuuid": "dc42ae8d-0789-ea5a-f29b-1dbcac0fe321", "filename": "passport.jpg", "mimetype": "image/jpeg", "size": 24, "tags": ["kyc", "passport"], "filedata": "ZmFrZSBwYXNzcG9ydCBzY2FuIGJ5dGVz" } ``` To download the decrypted bytes directly instead of base64 inside JSON, add `"raw": true`. The response carries the original MIME type and a `Content-Disposition` header: ```bash theme={null} curl -X POST http://localhost:3000/v2/FileGet \ -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d '{"mode":"email","identity":"john@example.com", "fileuuid":"dc42ae8d-0789-ea5a-f29b-1dbcac0fe321","raw":true}' \ -o passport-downloaded.jpg ``` ## Step 6: Stop the instance ```bash theme={null} docker stop databunkerpro ``` The container was started with `--rm`, so it is removed on stop and the in-memory database goes with it. Starting demo mode again gives you a clean instance. ## Next steps > [card] [Install with Docker Compose](/pro/installation/docker-compose) > > Deploy with a real database, persistent storage, and generated credentials. > [card] [File Vault](/pro/concepts/file-vault) > > How file encryption, crypto-shredding, and the S3, GCS, and Azure backends work. > [card] [Access control](/pro/administration/access-control) > > Scope API tokens to roles and groups instead of using the root token. > [card] [API reference](/pro/api/overview) > > The full API surface, authentication, errors, and pagination. # Security overview Source: https://docs.databunker.org/pro/get-started/security-overview Information security's primary focus is the balanced protection of confidentiality, integrity, and availability of data. This document reviews Databunker Pro's security features based on these core principles. Databunker Pro is built following privacy-by-design principles, which are integral to **GDPR**, **CPRA**, and **SOC2** privacy standards. **Databunker Pro** allows you to build **privacy by design** compliant solutions, and to follow data minimization requirements. When using **Databunker Pro**, every API request generates an audit trail. **Databunker Pro** can be used as a **consent management system** and as a **repository for processing operations**. It serves as an external storage according to pseudonymization definition and complies with Schrems II cross-border personal data transfer implementation. Databunker Pro is the secure vault and tokenization engine. Data Protection Officer (DPO) operations — data-subject rights, SaaS and database connectors (HubSpot, MailChimp, Salesforce, MySQL, PostgreSQL, Oracle, SQL Server), and one-click personal data reports — are provided by the separate **Databunker DPO** product in the Databunker Portal. For global organisations running Pro in multiple jurisdictions, DPO also serves as the unifying operational layer across regional deployments — see [Multi-jurisdiction deployment](/pro/concepts/global-deployment). ## How we address confidentiality ### Encryption in transit and encryption at rest Databunker Pro enforces full encryption in transit and at rest by default. All network requests are secured using SSL encryption protocols. ### Record encryption Customer personal information records are encrypted using **AES-256** keys or securely hashed in the product internal database. AES-256 encryption is **FIPS 140-2 compliant** and meets federal cryptographic standards. ### Encryption of audit events Personally Identifiable Information (PII) in audit events is fully encrypted. ### Secure hash-based search index Databunker Pro extracts emails, phone numbers, and login names from user records to build a hashed-based search index. This method allows secure lookups of original user records. ### Backend database connectivity **Databunker Pro** supports **PostgreSQL**, **MySQL**, and **Oracle** as backend databases, connecting through a **secure SSL channel**. Multi-tenancy is supported on all three; on PostgreSQL it is enforced with native row-level security (RLS). ### Database-level tenant isolation On PostgreSQL, tenant isolation is enforced by the database rather than by the correctness of application queries. Two dedicated roles are created at setup, both `NOSUPERUSER NOLOGIN` so neither can be used to log into the database directly: | Role | Privileges | Used for | | - | - | - | | `mtenant` | No `BYPASSRLS` — bound by row-level security on every tenant-scoped table | All ordinary traffic | | `madmin` | `BYPASSRLS`, granted `SELECT` on the `users` table only | The few deliberate cross-tenant reads | Ordinary requests run as `mtenant` with the tenant fixed for the session, so a query that omits or mistakes its tenant condition still cannot return another tenant's rows — isolation does not depend on every query being written correctly. Roughly two dozen tables are covered. Cross-tenant reads are the narrow exception. They are restricted to the main-tenant administrator, additionally gated by a short-lived unlock UUID, and audited on every call. Because `madmin` is granted read-only access to a single table, even that bypass path cannot write anything or reach audit records, sessions, or files. On MySQL and Oracle, tenant scoping is applied in the queries Databunker Pro issues rather than by the database, so this second line of defence is specific to PostgreSQL. For the policy definitions, the covered tables, and the cross-tenant endpoints, see [Database-level tenant isolation](/pro/administration/multi-tenancy#database-level-tenant-isolation). ### FIPS compliance Databunker Pro uses **FIPS 140-2 compliant** cryptographic algorithms for core security operations: * **Certificate generation**: When deploying via Helm, certificates are generated using **RSA 2048-bit** key length, which is FIPS compliant. * **Record encryption**: All customer records are encrypted using **AES-256**, a FIPS-approved symmetric encryption algorithm. * **Go runtime**: The Go programming language runtime does not enforce FIPS mode internally, allowing Databunker Pro to operate in FIPS-enabled environments while maintaining compatibility. **Note on MD5 usage**: Databunker Pro uses MD5 for non-cryptographic purposes only: * As a distributed lock mechanism in the `users` and `userapps` tables to prevent concurrent modifications * As part of a double-hash (SHA256 + MD5) for duplicate detection in format-preserving tokenization engine * As salt material (MD5 of master key) for SHA256-based indexing of user records (e.g., email, phone numbers) These MD5 usages are for internal system operations and do not impact the FIPS compliance of cryptographic operations protecting customer data. ### Secure session storage Session data, including PII such as email addresses, IP addresses, and browser details, is securely stored in Databunker’s encrypted store via a dedicated API. ### Secure bulk data export/dump We have introduced a specialized secure API to control and limit bulk data exports. Learn more [here](/pro/concepts/select-security). ### Wrapping keys and Shamir key shares Databunker Pro uses a **master key** to encrypt all records. The master key is never exposed — not to users, not to administrators, and not through any API. It is itself encrypted by a **wrapping key**, which is the only key you handle. The master key is stored under two independent wrappings: one by the operational wrapping key your deployment reads at boot, and one by a recovery key reconstructable from any three of five **Shamir key shares** issued at setup. Rotating the wrapping key re-wraps the master key without re-encrypting any stored record, so rotation costs the same on a vault of 1,000 records as on one of 100 million, and previously issued shares stay valid. Databunker holds **no copy of your keys and operates no escrow**. This is why a compromise of Databunker's own systems cannot expose your data — and equally why key custody is your responsibility: if the wrapping key is lost and fewer than three shares remain, the data cannot be decrypted by anyone. See [Wrapping key rotation](/pro/administration/key-rotation) for the procedure and [What is recoverable](/pro/administration/key-rotation#what-is-recoverable) for the full failure matrix. ### Optional user scheme validation Databunker Pro supports user schema validation to enforce mandatory fields in user records. It returns error messages for objects missing required fields. ## How we address integrity ### Record update Databunker employs encrypted JSON objects for storing user profiles. During updates, Databunker ensures the presence of the original record in the database by verifying its checksum before executing SQL UPDATE queries. ### Multi-tenancy Databunker Pro implements [multi-tenancy](/pro/administration/multi-tenancy) on PostgreSQL, MySQL, and Oracle. Queries executed by specific tenants are restricted to their own records. On PostgreSQL, isolation is enforced with the database's native row-level security (RLS) mechanism — see [Database-level tenant isolation](#database-level-tenant-isolation) for the role model and the cross-tenant exceptions. ### Token-based API Access All API requests require a user token and tenant name. Databunker identifies user roles, verifies permissions, and blocks unauthorized requests within the tenant’s scope. ## How we address availability ### Containers Databunker Pro is distributed as Docker container, which can be easily deployed in cloud environments. Example scripts for running these containers using Docker Compose and Kubernetes are provided. ### Stateless application server Databunker Pro is a stateless application server, enabling multiple instances to run concurrently. The primary bottleneck is the backend database. To address this, Databunker Pro integrates with AWS Aurora PostgreSQL Auto-Scaling databases. PostgreSQL, MySQL, and Oracle are supported as backend databases. ### Scalability in Kubernetes Databunker Pro can be seamlessly scaled in Kubernetes using horizontal scaling. This ensures high availability and performance under increasing workloads. Kubernetes facilitates effortless scaling by dynamically adjusting the number of running instances based on resource utilization, ensuring that Databunker can meet growing demands efficiently. ### Encryption service availability The sections above cover capacity. Availability of the encryption service itself depends on one credential: the vault **cannot start without its wrapping key**. Key custody is therefore an availability control, not only a confidentiality one. Treat the wrapping key with the same operational care as the database itself: * Back up the database **and** the wrapping key. Either one alone is insufficient to restore service. * Store the wrapping key in a secret manager, and keep the five Shamir shares somewhere separate from it. * Verify at least three shares remain reachable on a schedule — a shortfall is invisible until the moment you need them. A wrapping key lost while the service is still running is routinely recoverable; the same loss discovered after it has stopped is not. See [What is recoverable](/pro/administration/key-rotation#what-is-recoverable). # Clean the users table Source: https://docs.databunker.org/pro/howtos/clean-users-table Remove all user records and related data from a Databunker Pro instance. This guide explains how to wipe **all** user data from a Databunker Pro instance while keeping its configuration (tenants, roles, policies, encryption keys, license) intact. It is intended for resetting a **test**, **staging**, or **to-be-decommissioned** instance. > [!WARNING] > > This operation is destructive and irreversible. It deletes every user across **all tenants** — the SQL `TRUNCATE` command ignores row-level security, so it cannot be limited to a single tenant. Never run it against a production database. Take a backup first. ## Background A user in Databunker Pro is identified by a UUID **token**. Beyond the main `users` table, the same token (or, for a few tables, the `usertoken` / `record` column) links a user to several auxiliary tables. A full cleanup must clear all of them: | Table | User column | Contents | | - | - | - | | `users` | `token` | Main encrypted user profile | | `userapps` | `token` | Per-user app records | | `userappversions` | `token` | App record version history | | `userversions` | `token` | User profile version history | | `usergroups` | `token` | Group memberships | | `sessions` | `token` | User sessions | | `sharedrecords` | `token` | Shared-record grants | | `requests` | `token` | Data-subject requests | | `agreements` | `token` | Consent / legal-basis agreements | | `audit` | `record` | Audit events for the user | | `files` | `token` | Encrypted file metadata and wrapped per-file keys | | `filetags` | `token` | File tags | | `xtokens` | `usertoken` | Per-user access tokens (only rows where `usertoken` is set — see below) | The tokenization vault (`tokens`) is **not** keyed by user token and is left out by default — see [Tokenization vault](#tokenization-vault) below. Clearing `files` removes the metadata and the encryption keys, but not the stored objects themselves — see [Stored file objects](#stored-file-objects) below. ## Before you start * Direct (`psql`) access to the PostgreSQL database backing Databunker Pro. * A recent backup. ## Truncate all user tables Run the following statements. `RESTART IDENTITY` resets the auto-increment sequences (only `usergroups` actually uses one) so a fresh instance starts clean. ```sql theme={null} TRUNCATE TABLE users RESTART IDENTITY; TRUNCATE TABLE userapps RESTART IDENTITY; TRUNCATE TABLE userappversions RESTART IDENTITY; TRUNCATE TABLE userversions RESTART IDENTITY; TRUNCATE TABLE usergroups RESTART IDENTITY; TRUNCATE TABLE sessions RESTART IDENTITY; TRUNCATE TABLE sharedrecords RESTART IDENTITY; TRUNCATE TABLE requests RESTART IDENTITY; TRUNCATE TABLE agreements RESTART IDENTITY; TRUNCATE TABLE audit RESTART IDENTITY; TRUNCATE TABLE files RESTART IDENTITY; TRUNCATE TABLE filetags RESTART IDENTITY; DELETE FROM xtokens WHERE usertoken IS NOT NULL AND usertoken::text <> ''; ``` `TRUNCATE` empties the tables in a single fast operation and reclaims disk space immediately, so a follow-up `VACUUM` is not required. > [!WARNING] > > Do **not** `TRUNCATE` the `xtokens` table. It holds the **root** and **role** access tokens (rows where `usertoken` is `NULL`) alongside the per-user login tokens. Wiping it would invalidate the root token and lock you out of the API. Delete only the rows that belong to a user with `DELETE FROM xtokens WHERE usertoken IS NOT NULL AND usertoken::text <> '';`, as shown above — this preserves the root and role tokens. > [!NOTE] > > `TRUNCATE` ignores row-level security, so it always clears every tenant regardless of the `my.tenantid` session setting. If you need to remove the users of a single tenant only, delete by `tenantid` with `DELETE` statements instead of truncating. ## Tokenization vault If you use [tokenization](/pro/concepts/tokenization), a user's sensitive fields may be stored in the `tokens` vault. This table is **not** keyed by the user token, so it is intentionally excluded above to avoid breaking tokens that are still referenced elsewhere. Truncate it only if you want to erase the entire vault as part of a full reset: ```sql theme={null} -- Empties the tokenization vault. It is RANGE-partitioned; -- truncating the parent cascades to tokens_p0..p240. TRUNCATE TABLE tokens RESTART IDENTITY; ``` ## Stored file objects The `files` table holds the metadata and the per-file key; the encrypted file itself lives in the configured [object storage](/pro/concepts/file-vault) backend — local disk, Amazon S3, Google Cloud Storage, or Azure Blob Storage — under `tenant///`. Truncating `files` destroys the keys, so the stored objects can never be decrypted again. What remains is unreadable ciphertext, plus object paths that still reveal which user tokens existed. Remove them as well to reclaim the space: ```bash theme={null} # local backend, using the object_storage.local_dir from databunker.yaml rm -rf /databunker/files/tenant/* ``` ```bash theme={null} # Amazon S3 aws s3 rm "s3:///tenant/" --recursive ``` Do this **after** truncating the tables — deleting the objects first leaves metadata rows pointing at files that no longer exist. ## What is preserved The following configuration tables are **not** touched, so the instance stays usable after the cleanup: `tenants`, `config` (including the license key), `encryptionkeys`, `policies`, `roles`, `rolepolicies`, `groups`, `connectors`, `legalbasis`, and `processingactivities`. # How-tos overview Source: https://docs.databunker.org/pro/howtos/overview Short, task-focused guides for common Databunker Pro operations. This section collects short, task-focused guides for operations you perform against a running Databunker Pro instance. ## Available how-tos * [Update the license key](/pro/howtos/update-license) — apply a new license to a running instance via the API or the web interface. * [Clean the users table](/pro/howtos/clean-users-table) — remove all user records and related data for a full reset (testing, staging, or decommissioning). * [Store user fields](/pro/howtos/store-user-fields) — choose between a whole encrypted profile and per-field tokens, and share a single field without handing out a credential. * [Tokenize LLM prompts](/pro/howtos/tokenize-llm-prompts) — strip personal data out of a prompt before calling a hosted model, and restore it in the reply. * [Session management](/pro/howtos/session-management) — keep login sessions encrypted in the vault, with expiry, logout and log-out-everywhere. > [!NOTE] > > These guides assume you already have Databunker Pro [installed](/pro/installation/docker-compose) and an admin (root) access token. See [Generate admin credentials](/pro/installation/generate-admin-credentials) if you have not completed the initial setup. # Secure session management Source: https://docs.databunker.org/pro/howtos/session-management Keep login sessions server-side in Databunker Pro — encrypted, expiring and revocable — and hand the browser only a random ID. A session is how your application remembers a logged-in user between requests: a record on the server, found by a random ID that the browser sends in a cookie. Developers routinely keep customer details in it — email, name, IP address, device — so the session store ends up holding personal data. Those same details are what a security team relies on to spot a hijacked session and investigate an incident, so they need to be both protected and available. A session that lives in a signed cookie or a JWT cannot be taken back: logging out deletes the browser's copy, and anyone who copied it first keeps a working credential until it expires. A server-side session can be revoked, but it usually sits in a table nobody thinks of as sensitive. Databunker Pro provides an API that developers use to store sessions in the vault, encrypted like user records. The browser gets a random UUID; the session data is encrypted with its own record key; expiry is enforced by the vault; and one call ends the session everywhere it was used. ## How it works 1. At login your backend generates a UUID and calls `SessionUpsert` with the session data. 2. The backend sets that UUID as a cookie. Nothing else reaches the browser. 3. On every request the backend calls `SessionGet`. A `404` means the session expired or was deleted — treat the user as logged out. 4. At logout the backend calls `SessionDelete`. Every call comes from your backend with a server-side access token. `SessionUpsert` requires an admin token, so sessions cannot be created from the browser. Sessions are kept in Redis when `REDIS_HOST` is set and in the database otherwise. The API and behaviour are the same either way. ## Create a session at login Generate the session ID on the server — never accept one from the client, or an attacker can plant a known ID before the victim logs in (session fixation). It must be a UUID. To link the session to a user, put one of `token`, `login`, `email`, `phone` or `custom` inside `sessiondata`. Without it the session still works, but it is not attached to anyone and [log out everywhere](#log-out-everywhere) cannot find it. > [tab] curl > > ```bash theme={null} > curl -X POST https://your-databunker/v2/SessionUpsert \ > -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ > -H "Content-Type: application/json" \ > -d '{ > "sessionuuid": "6f1c2a7e-4b8d-4e2f-9a31-0c5d7e8f9a10", > "sessiondata": { > "token": "USER_TOKEN", > "ip": "203.0.113.7", > "agent": "Mozilla/5.0 (Macintosh; ...)" > }, > "slidingtime": "1800", > "finaltime": "12h" > }' > ``` > [tab] JavaScript > > ```javascript theme={null} > import { randomUUID } from "node:crypto"; > > const sessionId = randomUUID(); > await api.upsertSession( > sessionId, > { token: userToken, ip: req.ip, agent: req.get("user-agent") }, > { slidingtime: "1800", finaltime: "12h" } > ); > > res.cookie("sid", sessionId, { httpOnly: true, secure: true, sameSite: "lax" }); > ``` > [tab] Python > > ```python theme={null} > import uuid > > session_id = str(uuid.uuid4()) > api.upsert_session( > session_id, > {"token": user_token, "ip": request.remote_addr, "agent": request.user_agent.string}, > {"slidingtime": "1800", "finaltime": "12h"}, > ) > > response.set_cookie("sid", session_id, httponly=True, secure=True, samesite="Lax") > ``` Calling `SessionUpsert` again with the same `sessionuuid` replaces the data and restarts both timers. ## Set expiry Two timers end a session; set both. | Parameter | Ends the session | Typical value | | - | - | - | | `slidingtime` | after this long **without** a `SessionGet` — each read restarts it | 15–30 minutes | | `finaltime` | at this point no matter how active the session is | 8–24 hours | `slidingtime` alone lets an active session — or a stolen one being replayed — live forever. `finaltime` alone logs users out mid-task. With neither, the session never expires. `finaltime` is capped by `policy.max_session_retention_period` in `databunker.yaml`. The shipped file sets `1h`, so a `finaltime` of `12h` is silently cut to one hour until you raise it: ```yaml theme={null} policy: max_session_retention_period: "12h" ``` > [!WARNING] > > Durations are a number with an optional unit: `s` seconds, `h` hours, `d` days and **`m` months — not minutes**. `"30m"` is 30 months. Write 30 minutes as `"1800"` or `"1800s"`. ## Check the session on every request ```bash theme={null} curl -X POST https://your-databunker/v2/SessionGet \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"sessionuuid": "6f1c2a7e-4b8d-4e2f-9a31-0c5d7e8f9a10"}' ``` ```json theme={null} { "status": "ok", "sessionuuid": "6f1c2a7e-4b8d-4e2f-9a31-0c5d7e8f9a10", "finaltime": 1793900656, "sessiondata": { "token": "USER_TOKEN", "ip": "203.0.113.7", "agent": "Mozilla/5.0 (Macintosh; ...)" } } ``` `finaltime` in the response is when the session will expire if it is not used again. A `404` means it has expired or been deleted: clear the cookie and send the user to log in. Comparing the stored `ip` or `agent` with the current request is a cheap way to spot a replayed cookie. Decide what a mismatch means for your users before enforcing it — mobile networks change IPs often. ## Log out ```bash theme={null} curl -X POST https://your-databunker/v2/SessionDelete \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"sessionuuid": "6f1c2a7e-4b8d-4e2f-9a31-0c5d7e8f9a10"}' ``` The next `SessionGet` for that ID returns `404`, so a copy of the cookie is now worthless. Clear the cookie as well. ## Rotate the ID when privileges change When a user logs in from an anonymous session, completes MFA, or switches into an admin role, create a session under a new UUID and delete the old one. An ID that was seen before the change cannot be used after it. ## Log out everywhere For "sign out of all devices", or after a password reset, list the user's sessions and delete each one: ```bash theme={null} curl -X POST https://your-databunker/v2/SessionListUserSessions \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"mode": "token", "identity": "USER_TOKEN"}' ``` ```json theme={null} { "status": "ok", "total": 2, "rows": [ { "sessionuuid": "6f1c2a7e-...", "lastusedtime": 1793898856, "data": { "ip": "203.0.113.7", "...": "..." } }, { "sessionuuid": "a90e44d1-...", "lastusedtime": 1793812400, "data": { "ip": "198.51.100.23", "...": "..." } } ] } ``` In the list, session data is under `data`, not `sessiondata`. The same response can back an "active sessions" page that shows each device and when it was last used. Only sessions linked to the user — through `token`, `login`, `email`, `phone` or `custom` in `sessiondata` — appear here. ## Cookie settings The cookie carries only the session UUID, but it is still a bearer credential: * `HttpOnly` — scripts on the page, including injected ones, cannot read it. * `Secure` — sent over HTTPS only. * `SameSite=Lax` (or `Strict`) — not sent on cross-site POSTs. * No `Max-Age` longer than `finaltime`. Expiry is enforced by the vault regardless, but a stale cookie just produces failed lookups. ## What to keep in a session Keep session data small: the user token, what you need to detect replay, and flags such as an MFA step completed. Load the profile with `UserGet` when you need it rather than copying it into the session, where it goes stale. Never store a password or a password hash in a session. Deleting a user also deletes every session linked to them, so an erased user is logged out on the next request. ## Next steps * [Access control](/pro/administration/access-control) — limit what the token your backend uses for session calls can do. * [Multi-tenancy](/pro/administration/multi-tenancy) — sessions are scoped to the tenant of the access token. * [Architecture](/pro/get-started/architecture) — where Redis fits in a deployment. # Store user fields Source: https://docs.databunker.org/pro/howtos/store-user-fields Choose between storing a whole user profile and tokenizing individual fields, and share a single field without handing out a credential. Databunker Pro can hold a user's data two ways: as **one encrypted profile** addressed by a single token, or as **individual tokenized values**, one token per field. They are not interchangeable — the choice decides which features you keep and how much the data costs to store. This guide shows both, then a third thing people often reach for when they say "per-field": exposing one field of a profile to an outside party without giving that party a credential. ## Option 1 — Store the whole profile `UserCreate` encrypts the entire profile as one record and returns a UUID token. ```bash theme={null} curl -X POST https://your-databunker/v2/UserCreate \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "profile": { "email": "jane@example.com", "phone": "+12065550100", "login": "jane", "custom": "legacy-4471", "first": "Jane", "last": "Doe", "address": "1 Market Street, San Francisco, CA", "dob": "1985-04-12", "creditcard": "4532015112830366", "ssn": "123-45-6789" } }' ``` ```json theme={null} { "status": "ok", "token": "8ba70d19-a8b1-0b82-f0b9-d5952221be67" } ``` Store that token in your own database in place of every field above. Read the record back by the token or by any indexed field — `email`, `phone`, `login`, `custom`: ```bash theme={null} curl -X POST https://your-databunker/v2/UserGet \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{"mode":"email","identity":"jane@example.com"}' ``` Use `UserCreateBulk` to load many profiles in one call — see [Migrating a SQL users table](/pro/migrations/sql-users-table). ### What you get * **Indexed lookup** by `email`, `phone`, `login` and `custom`, using secure hashed indexes. * **App data** for fields that do not belong in the profile. `AppdataCreate` attaches a named JSON record to the user — `"appname": "billing"`, `"appname": "preferences"` — kept separate from the profile and readable on its own with `AppdataGet`. A user can have as many as you need. * **Group membership.** `GroupAddUser` puts the user in a group, so you can organise users and scope [access-control policies](/pro/administration/access-control) to a group rather than to individuals. * **One licensed record** per user, however many fields it holds. App data, consents, sessions and the full version history are all included in that one record, and a card stored inside the profile is not metered separately. * **Erasure in one call.** `UserDelete` wipes the profile; the token remains as an empty shell, lookups by email stop resolving, and anything derived from the profile stops returning data. `UserDeleteBulk` does the same for many users at once. * Everything else keyed to a user token: [shared records](/pro/concepts/shared-records), [record versioning](/pro/concepts/record-versioning), consent agreements, data-subject requests, and a per-user audit trail. ### What it costs you * **The four indexed fields must be unique.** `email`, `phone`, `login` and `custom` are what makes lookup possible, and no two users can share a value in any of them — a second `UserCreate` with an email already in use fails with `Duplicate index: email`. Two family members sharing one phone number cannot both carry it in `phone`; keep the shared value in an ordinary field, which has no such constraint. * The record is **all or nothing**. Anyone who can call `UserGet` sees every field, unless you restrict them with an [access-control policy](/pro/administration/access-control). ## Option 2 — Tokenize individual fields `TokenCreate` tokenizes one value, `TokenCreateBulk` a whole batch. Neither has any connection to a user record, and what comes back depends on the `tokentype`: > [tab] A string — user name > > ```bash theme={null} > curl -X POST https://your-databunker/v2/TokenCreate \ > -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ > -H "Content-Type: application/json" \ > -d '{ > "tokentype": "string", > "record": "Jane Doe", > "unique": true > }' > ``` > > ```json theme={null} > { > "status": "ok", > "tokenuuid": "a07d6340-2b45-ee79-98a5-e5c737966b3c" > } > ``` > > Names, addresses, dates, identifiers and free text all go through `string`. It is stored under the canonical type name `text`, which `TokenGet` reports back and which you may also send instead. > > There is no `tokenbase`: a string has no format to preserve, so you get a UUID and nothing else. Store the `tokenuuid` in place of the name and detokenize it with `TokenGet`. > [tab] A credit card > > ```bash theme={null} > curl -X POST https://your-databunker/v2/TokenCreate \ > -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ > -H "Content-Type: application/json" \ > -d '{ > "tokentype": "creditcard", > "record": "4532015112830366", > "unique": true > }' > ``` > > ```json theme={null} > { > "status": "ok", > "tokenuuid": "106ad147-5559-fdea-a2af-1a1075f0d0f4", > "tokenbase": "3371363676177808" > } > ``` > > Here you get both forms. `tokenuuid` addresses the token; `tokenbase` is the format-preserving one — same length, still Luhn-valid, so it drops into a column that already validates card numbers. Either value detokenizes through `TokenGet`. > [tab] Both, in one batch > > `TokenCreateBulk` takes an array of records and may mix types freely, so a whole > profile goes across in one call. `unique` applies to the batch. > > ```bash theme={null} > curl -X POST https://your-databunker/v2/TokenCreateBulk \ > -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ > -H "Content-Type: application/json" \ > -d '{ > "records": [ > { "tokentype": "string", "record": "Jane Doe" }, > { "tokentype": "string", "record": "1 Market Street, San Francisco, CA" }, > { "tokentype": "creditcard", "record": "4532015112830366" }, > { "tokentype": "creditcard", "record": "5467047429390590" } > ], > "unique": true > }' > ``` > > ```json theme={null} > { > "status": "ok", > "created": [ > { "record": "Jane Doe", "tokentype": "text", "tokenbase": "", > "tokenuuid": "89c8c648-a3ca-98ec-9e29-502140c64aaf" }, > { "record": "1 Market Street, San Francisco, CA", "tokentype": "text", "tokenbase": "", > "tokenuuid": "77216530-3981-b814-9ea3-c3922dfe0502" }, > { "record": "4532015112830366", "tokentype": "creditcard", "tokenbase": "7219729206681484", > "tokenuuid": "87cc52c7-b538-3186-1ff0-fe058c33d5f4" }, > { "record": "5467047429390590", "tokentype": "creditcard", "tokenbase": "9162147674613009", > "tokenuuid": "e9cc9ca7-bcca-abeb-2196-5af0814be7b4" } > ], > "summary": { "created": 4, "duplicates": 0, "errors": 0, "total": 4 } > } > ``` > > Each record comes back with the value it came from, so you can map the tokens onto your > own columns. The `string` rows report `text`, the canonical type name, and carry an > empty `tokenbase`; only the cards get a format-preserving one. > > Send the same batch again with `unique` and nothing new is minted — the four move from > `created` to `duplicates`, carrying the tokens issued the first time: > > ```json theme={null} > { "summary": { "created": 0, "duplicates": 4, "errors": 0, "total": 4 } } > ``` `unique: true` deduplicates: the same input returns the same token instead of minting a new one. > [!NOTE] > > Use `creditcard` and `string` — between them they cover every field. Only `creditcard` returns a format-preserving `tokenbase`; `string` returns a UUID, so do not expect a look-alike value for a name or an address. > > The other types (`unixtimestamp`, `uint32`, `uint64`, `email`, `ssn`, `uuid`) are **not recommended** — they do not scale. See [format-preserving tokenization](/pro/concepts/tokenization#supported-data-types). ### Read a batch back Bulk detokenization returns plaintext for many records at once, so it takes a short-lived unlock UUID as a second authorization step. Call `BulkListUnlock` first, then pass the `unlockuuid` to `BulkListTokens` with the tokens you want: ```bash theme={null} curl -X POST https://your-databunker/v2/BulkListUnlock \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" # -> { "status": "ok", "unlockuuid": "289f9b87-a8f3-d6ae-442c-eb06c2938652" } curl -X POST https://your-databunker/v2/BulkListTokens \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "unlockuuid": "289f9b87-a8f3-d6ae-442c-eb06c2938652", "tokens": ["89c8c648-a3ca-98ec-9e29-502140c64aaf", "87cc52c7-b538-3186-1ff0-fe058c33d5f4"] }' ``` ```json theme={null} { "status": "ok", "total": 2, "rows": [ { "tokenuuid": "89c8c648-a3ca-98ec-9e29-502140c64aaf", "record": "Jane Doe", "tokentype": "text", "creationtime": 1787317854, "finaltime": 0, "slidingtime": 0 }, { "tokenuuid": "87cc52c7-b538-3186-1ff0-fe058c33d5f4", "record": "4532015112830366", "tokentype": "creditcard", "tokenbase": "9899464476958601", "creationtime": 1787317854, "finaltime": 0, "slidingtime": 0 } ] } ``` `BulkDeleteTokens` takes the same `unlockuuid` and token list to erase them. ### What you get * **Value-level granularity.** A card number can live in a PCI-scoped system while the rest of the profile does not. * **Deduplication** across the whole vault with `unique`. * **Format preservation** for `creditcard`, so legacy schemas and card validators keep working. ### What it costs you * **Each token is a licensed record.** Ten fields tokenized individually is ten records, where the same ten fields inside a profile is one. See [what counts as a record](/pro/get-started/licensing#what-counts-as-a-record). * **Erasure is yours to manage.** The `tokens` table is not keyed by user token, so `UserDelete` does not touch these tokens and a data-subject erasure request will not reach them. Nothing links a token back to the user's profile, and there is no index to search, so you must record the mapping yourself and delete with `TokenDelete` or `BulkDeleteTokens` — or give each token an expiry, as below. Lose the mapping and only an expiry will ever remove the value. * **`unique` makes equal values linkable.** The same input always yields the same token, so anyone holding two records can tell they carry the same value without detokenizing either. Leave `unique` off where that inference matters — see [why shared records, not long-lived tokens](/pro/concepts/shared-records). * **Groups do not apply.** Every group endpoint identifies its member by `mode` and `identity` — a *user*. A standalone token cannot be put in a group, so you cannot organise or query tokenized values that way. * No indexed lookup, no app data, no versioning, no agreements, no per-user audit trail — those all hang off a user record. ## Share a single field, without a credential If the goal is to let an outside party read **one field** of a profile, do not tokenize that field separately — create a [shared record](/pro/concepts/shared-records) scoped to it. ```bash theme={null} curl -X POST https://your-databunker/v2/SharedRecordCreate \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "mode": "token", "identity": "8ba70d19-a8b1-0b82-f0b9-d5952221be67", "fields": "email", "partner": "partner-acme-billing", "finaltime": "7d" }' ``` ```json theme={null} { "status": "ok", "recorduuid": "a9ad8567-d6ce-9363-88f3-1f3161515c50" } ``` Hand the `recorduuid` to the consumer. Retrieving it needs **no `X-Bunker-Token`** — that is the point, the partner never receives a vault credential: ```bash theme={null} curl -X POST https://your-databunker/v2/SharedRecordGet \ -H "Content-Type: application/json" \ -d '{"recorduuid":"a9ad8567-d6ce-9363-88f3-1f3161515c50"}' ``` ```json theme={null} { "status": "ok", "data": { "email": "jane@example.com" } } ``` Only the field named in `fields` comes back. After `finaltime` the UUID stops resolving on its own, with no cleanup call. `partner` tags every retrieval in the audit trail. Repeat the call once per field to hand different fields to different consumers, each with its own expiry. Add `appname` to share fields from one of the user's app data records instead of the profile. > [!WARNING] > > Shared records work on **user records only**. There is no equivalent for a standalone `TokenCreate` token, so a field you move out of the profile into its own token can no longer be shared this way. Decide this before you tokenize. ## Expire data automatically Neither option obliges you to delete anything by hand. Both `UserCreate` and `TokenCreate` — and their bulk forms — accept an expiry at creation, after which the record is gone without a call from you. Two parameters, usable together: | Parameter | Meaning | | - | - | | `finaltime` | An absolute lifetime. The record is removed once it elapses, however often it was used. | | `slidingtime` | A window that restarts on every access. Records that stop being used expire; active ones stay. | ```bash theme={null} # a profile kept for a year, or 90 days after it was last touched curl -X POST https://your-databunker/v2/UserCreate \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "profile": { "email": "jane@example.com", "first": "Jane" }, "finaltime": "1y", "slidingtime": "90d" }' ``` ```bash theme={null} # a card token that disappears after 30 days curl -X POST https://your-databunker/v2/TokenCreate \ -H "X-Bunker-Token: YOUR_ACCESS_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "tokentype": "creditcard", "record": "4532015112830366", "unique": true, "finaltime": "30d" }' ``` Afterwards an expired profile reports `The user record has expired` and an expired token reports `Token not found`. Indexed lookups stop resolving as well. The same two parameters apply to `FileCreate`, `SessionUpsert` and the `XTokenCreate` calls; `SharedRecordCreate` and `AgreementAccept` take `finaltime` only. > [!NOTE] > > Expiry is the practical answer to the tracking problem in option 2. A standalone token is invisible to `UserDelete`, but a token created with `finaltime` removes itself, so a retention limit does not depend on your bookkeeping being right. Give every per-field token an expiry unless you have a reason not to. ## Choosing | | Whole profile | Per-field tokens | | - | - | - | | What your application stores | one UUID for the whole profile | one token per value — `creditcard` also returns a Luhn-valid look-alike | | Licensed records for 10 fields | 1 | 10 | | Indexed lookup | `email`, `phone`, `login`, `custom` | none | | Erasure | `UserDelete` / `UserDeleteBulk`, by token or any indexed field | `TokenDelete` / `BulkDeleteTokens`, by token only — nothing links one back to the user's profile | | Automatic record expiration | `finaltime`, `slidingtime` | `finaltime`, `slidingtime` | | Groups, app data, shared records, versioning, agreements, audit | yes | no | | The same address on two users | stored on each user profile | one token for both, with `unique` | **Store the whole profile** for anything that is a user — it is the cheaper, more capable default, and it is what the [PII vault](/pro/get-started/pii-vault) is for. **Tokenize a field on its own** when the value has to leave the user record: a card number crossing into a PCI-scoped system, or a value that must keep its original format for a legacy schema. **Mix them** for the common case. Keep the profile in the vault, and tokenize only the one high-risk field separately, storing its `tokenuuid` inside the profile: ```json theme={null} { "profile": { "email": "jane@example.com", "first": "Jane", "creditcard_token": "106ad147-5559-fdea-a2af-1a1075f0d0f4" } } ``` Remember that the separately tokenized value is now outside the reach of `UserDelete` — delete it explicitly when erasing the user. ## Related * [PII vault](/pro/get-started/pii-vault) — how whole-profile tokenization works * [Format-preserving tokenization](/pro/concepts/tokenization) — token types, expiration, bulk operations * [Shared records](/pro/concepts/shared-records) — sharing a scoped, expiring view of a record * [Licensing and limits](/pro/get-started/licensing#what-counts-as-a-record) — what counts as a record # Tokenize PII before it reaches an LLM Source: https://docs.databunker.org/pro/howtos/tokenize-llm-prompts Replace personal data in a prompt with Databunker Pro tokens before calling a model, then restore the real values in the response. A prompt sent to a hosted model leaves your infrastructure. So does the retrieved context behind it, the tool output the agent reads back, and the trace your observability stack keeps. Anything personal in that text is now held by a third party, on their retention schedule, in logs you do not control. Tokenization removes the personal data before the call and puts it back afterwards. The model reasons over placeholders; the plaintext never leaves the vault. ## What it looks like Say your application builds this prompt: ``` Draft a reply to the customer at sarah.chen@example.com about the disputed $420 charge on card 4532015112830366. Their phone on file is +1 415-555-0142 and their SSN is 123-45-6789. ``` Four pieces of personal data, all of which would be handed to the model provider as written. This is what reaches the model instead: ``` Draft a reply to the customer at [EMAIL:cfd20fe2-8872-d109-780b-5bcadb96ebd0] about the disputed $420 charge on card [CARD:600c5f6d-a18d-1f01-da05-4a5c3ee5ac24]. Their phone on file is [PHONE:dce7e4f4-4aeb-231c-daaf-2efd7bd2ae71] and their SSN is [SSN:b6c14fa6-715f-ee1d-aede-9dad4059da03]. ``` The task survives the substitution. The model can still see that there is an email address, a card, a phone number and a national ID, and which is which — everything it needs to draft the reply, and none of the values. So it answers in the same terms: ``` I've emailed [EMAIL:cfd20fe2-8872-d109-780b-5bcadb96ebd0] to confirm, and the $420 charge on card [CARD:600c5f6d-a18d-1f01-da05-4a5c3ee5ac24] will be reversed within 3 business days. ``` Your application swaps the real values back before that answer goes anywhere: ``` I've emailed sarah.chen@example.com to confirm, and the $420 charge on card 4532015112830366 will be reversed within 3 business days. ``` The customer gets a correct, personalized reply. The model provider never held a single personal value. ## How it works ``` prompt ──▶ find PII ──▶ TokenCreateBulk ──▶ prompt with tokens ──▶ model │ answer ◀── BulkListTokens ◀── reply with tokens ◀───────────────────┘ ``` Each placeholder is a label and a token: the label says what kind of value it stands for, the token is a UUID the vault can resolve back to the original. The rest of this guide builds that in four steps. This guide uses [demo mode](/pro/get-started/quickstart) — one `docker run`, root token `DEMO` — so every call below is runnable as written. ```bash theme={null} docker run -p 3000:3000 -d --rm --name databunkerpro securitybunker/databunkerpro demo ``` > [!TIP] > > If the personal data reaches the prompt from your own database rather than from free text, you can skip detection altogether: tokenize at ingest and store the token in place of the value, the pattern in [Store user fields](/pro/howtos/store-user-fields). Prompts built from those rows are tokenized before they are assembled. ## Step 1: Find the personal data Regular expressions handle values with a fixed shape. Order them most specific first, and discard any match that overlaps a span already taken, or a loose pattern will claim a span a precise one should own. ```python theme={null} import re DETECTORS = [ ("EMAIL", re.compile(r"\b[\w.%+-]+@[\w.-]+\.[A-Za-z]{2,}\b")), ("SSN", re.compile(r"\b\d{3}-\d{2}-\d{4}\b")), ("CARD", re.compile(r"\b(?:\d[ -]?){12,18}\d\b")), ("PHONE", re.compile(r"\+?\d[\d\s().-]{7,}\d")), ] def find_pii(text): spans = [] for label, rx in DETECTORS: for m in rx.finditer(text): if not any(m.start() < e and s < m.end() for s, e, _, _ in spans): spans.append((m.start(), m.end(), label, m.group())) return sorted(spans) ``` Put `SSN` after `PHONE` in that list and `123-45-6789` is tokenized as a phone number — the digit pattern matches it too, and whichever runs first wins. > [!WARNING] > > Patterns only find values with a fixed shape. Names, street addresses, employers, and diagnoses are missed entirely. They also produce false positives: the `PHONE` pattern above matches the bare date `2026-08-23`, which then becomes an opaque token the model cannot reason about. > > For free text that may carry values without a fixed shape, run a named-entity recognition model such as [Microsoft Presidio](https://microsoft.github.io/presidio/) and treat these regexes as a backstop. Detection quality, not the vault, sets the ceiling on what this pattern protects. ## Step 2: Tokenize the values How a value becomes a placeholder depends on where it came from: discovered in free text, or already held as a user record. Pick the tab that matches your prompt — the two take different calls. The Python snippets throughout use one small HTTP helper: ```python theme={null} import json, os, re, urllib.request BUNKER = os.environ.get("DATABUNKER_URL", "http://localhost:3000/v2") BUNKER_TOKEN = os.environ.get("DATABUNKER_TOKEN", "DEMO") def bunker(op, body): req = urllib.request.Request( f"{BUNKER}/{op}", data=json.dumps(body).encode(), headers={"X-Bunker-Token": BUNKER_TOKEN, "Content-Type": "application/json"}) with urllib.request.urlopen(req) as r: return json.load(r) ``` > [tab] Found in free text > > The values come from `find_pii` above, so each label is whatever the matching pattern was named. > > ```bash theme={null} > curl -X POST http://localhost:3000/v2/TokenCreateBulk \ > -H "X-Bunker-Token: DEMO" \ > -H "Content-Type: application/json" \ > -d '{ > "records": [ > { "tokentype": "string", "record": "sarah.chen@example.com" }, > { "tokentype": "string", "record": "+1 415-555-0142" }, > { "tokentype": "creditcard", "record": "4532015112830366" }, > { "tokentype": "string", "record": "123-45-6789" } > ], > "unique": true, > "finaltime": "24h" > }' > ``` > > ```json theme={null} > { > "status": "ok", > "created": [ > { "record": "sarah.chen@example.com", "tokentype": "text", "tokenbase": "", > "tokenuuid": "cfd20fe2-8872-d109-780b-5bcadb96ebd0" }, > { "record": "+1 415-555-0142", "tokentype": "text", "tokenbase": "", > "tokenuuid": "dce7e4f4-4aeb-231c-daaf-2efd7bd2ae71" }, > { "record": "4532015112830366", "tokentype": "creditcard", "tokenbase": "6372210073800049", > "tokenuuid": "600c5f6d-a18d-1f01-da05-4a5c3ee5ac24" }, > { "record": "123-45-6789", "tokentype": "text", "tokenbase": "", > "tokenuuid": "b6c14fa6-715f-ee1d-aede-9dad4059da03" } > ], > "num": 4, > "summary": { "created": 4, "duplicates": 0, "errors": 0, "total": 4 } > } > ``` > > Each row echoes the `record` it came from, which is what lets you map tokens back onto the spans you found. `string` is stored under its canonical name `text`, and only `creditcard` carries a `tokenbase`. > > Which gives the placeholders the prompt is built from: > > ``` > [EMAIL:cfd20fe2-8872-d109-780b-5bcadb96ebd0] > [PHONE:dce7e4f4-4aeb-231c-daaf-2efd7bd2ae71] > [CARD:600c5f6d-a18d-1f01-da05-4a5c3ee5ac24] > [SSN:b6c14fa6-715f-ee1d-aede-9dad4059da03] > ``` > > Two parameters matter here: > > * **`unique: true`** returns the *same* token for a value already in the vault, so an email keeps one identity across every turn of a conversation and across restarts. Without it each call mints a new token and the model sees the same person as a different one each time. Send a value again and it comes back under `duplicates`, carrying the original token: > > ```json theme={null} > { "created": null, > "duplicates": [ { "record": "sarah.chen@example.com", "tokentype": "text", "tokenbase": "", > "tokenuuid": "cfd20fe2-8872-d109-780b-5bcadb96ebd0" } ], > "summary": { "created": 0, "duplicates": 1, "errors": 0, "total": 1 } } > ``` > > * **`finaltime`** expires the token without a cleanup call. A prompt token rarely needs to outlive the conversation — see [Retention](#retention) below. > [tab] The user profile is known > > **Do not tokenize a second time.** If the person is already a user record, the profile is encrypted in the vault and the user token already stands in for it. Minting per-field tokens on top would store a second copy of the same data and bill a licensed record for every field. > > Create the user once, at signup or migration — not per prompt: > > ```bash theme={null} > curl -X POST http://localhost:3000/v2/UserCreate \ > -H "X-Bunker-Token: DEMO" \ > -H "Content-Type: application/json" \ > -d '{ > "profile": { > "name": "Sarah Chen", > "email": "sarah.chen@example.com", > "phone": "+1 415-555-0142", > "address": "1 Market Street, San Francisco, CA" > } > }' > ``` > > ```json theme={null} > { "status": "ok", "token": "cba3da40-cab0-fc94-a020-8bab3eaaa7c9" } > ``` > > That token is what your own database stores in place of the profile. The whole record — four fields here, and any you add later — is **one** licensed record. > > Now the prompt writes itself, because a field is fully identified by *which user* and *which field*. Use the user token as the UUID and the field name as the label: > > ```python theme={null} > USER_FIELDS = ("NAME", "EMAIL", "PHONE", "ADDRESS") > > def profile_placeholders(user_token, fields=USER_FIELDS): > return {f: f"[{f}:{user_token}]" for f in fields} > ``` > > ```python theme={null} > ph = profile_placeholders("cba3da40-cab0-fc94-a020-8bab3eaaa7c9") > > profile_prompt = ( > f"Draft a reply to {ph['NAME']} at {ph['EMAIL']} about the disputed " > f"$420 charge, and confirm the address on file is {ph['ADDRESS']}.") > ``` > > ``` > Draft a reply to [NAME:cba3da40-cab0-fc94-a020-8bab3eaaa7c9] at > [EMAIL:cba3da40-cab0-fc94-a020-8bab3eaaa7c9] about the disputed $420 charge, and > confirm the address on file is [ADDRESS:cba3da40-cab0-fc94-a020-8bab3eaaa7c9]. > ``` > > No `TokenCreateBulk` call, no extra records, and no plaintext in your process — you never had to read the profile to build the prompt. The address and name are covered as reliably as the email, which is the one thing pattern matching cannot promise. > > > [!WARNING] > > > > Every placeholder for one user carries the same UUID, so the label is what selects the field — it is load-bearing here, not a hint. The reverse map must be keyed on the pair, which is what `detokenize` in [Step 4](#step-4-detokenize-the-reply) does. > > > > It also means one stable identifier per user appears in every prompt about them. That is the same linkability trade-off as `unique: true`; if it matters, mint a short-lived `TokenCreate` token per conversation instead. Either way the prompt ends up carrying `[LABEL:uuid]` in place of every value. The label is what lets the model reason — it can write an email address into a sentence about sending mail without ever seeing one. The UUID is what makes detokenization stateless: the placeholder carries its own identity, so any process holding vault access can resolve it later, with nothing kept on the side in between. ## Step 3: Build the prompt and call the model Substitute back-to-front so earlier replacements do not shift the offsets of later spans. ```python theme={null} def tokenize(text, ttl="24h"): spans = find_pii(text) if not spans: return text records = [{"tokentype": "creditcard" if label == "CARD" else "string", "record": value} for _, _, label, value in spans] resp = bunker("TokenCreateBulk", {"records": records, "unique": True, "finaltime": ttl}) minted = {r["record"]: r["tokenuuid"] for r in (resp.get("created") or []) + (resp.get("duplicates") or [])} for start, end, label, value in reversed(spans): text = text[:start] + f"[{label}:{minted[value]}]" + text[end:] return text ``` Tell the model what the placeholders are, so it carries them through instead of inventing values: ```python theme={null} import anthropic SYSTEM = """Text in square brackets such as [EMAIL:] is a placeholder for redacted personal data. Treat each one as an opaque identifier for a real value of that type. Copy any placeholder you need to reference exactly as written. Never invent, complete, or alter a placeholder.""" client = anthropic.Anthropic() def ask(prompt): response = client.messages.create( model="claude-opus-5", max_tokens=16000, system=SYSTEM, messages=[{"role": "user", "content": prompt}], ) return "".join(b.text for b in response.content if b.type == "text") ``` ## Step 4: Detokenize the reply The model's reply comes back carrying the same placeholders. Resolving them is one regex pass plus a source of plaintext — and the source is whichever tab you took in [Step 2](#step-2-tokenize-the-values). ```python theme={null} PLACEHOLDER = re.compile(r"\[([A-Z]+):([0-9a-fA-F-]{36})\]") ``` > [tab] Resolve through the vault > > Bulk detokenization returns plaintext, so it takes a short-lived unlock UUID as a second authorization step: call `BulkListUnlock`, then pass the `unlockuuid` to `BulkListTokens`. > > ```bash theme={null} > curl -X POST http://localhost:3000/v2/BulkListUnlock \ > -H "X-Bunker-Token: DEMO" > # -> { "status": "ok", "unlockuuid": "29ffb00c-2585-7ed2-0278-14bcbb884471" } > > curl -X POST http://localhost:3000/v2/BulkListTokens \ > -H "X-Bunker-Token: DEMO" \ > -H "Content-Type: application/json" \ > -d '{ > "unlockuuid": "29ffb00c-2585-7ed2-0278-14bcbb884471", > "tokens": ["cfd20fe2-8872-d109-780b-5bcadb96ebd0", > "600c5f6d-a18d-1f01-da05-4a5c3ee5ac24"] > }' > ``` > > ```json theme={null} > { > "status": "ok", > "total": 2, > "rows": [ > { "tokenuuid": "cfd20fe2-8872-d109-780b-5bcadb96ebd0", > "record": "sarah.chen@example.com", "tokentype": "text", > "creationtime": 1787490564, "finaltime": 1787576964, "slidingtime": 0 }, > { "tokenuuid": "600c5f6d-a18d-1f01-da05-4a5c3ee5ac24", > "tokenbase": "6372210073800049", "record": "4532015112830366", > "tokentype": "creditcard", "creationtime": 1787490564, > "finaltime": 1787576964, "slidingtime": 0 } > ] > } > ``` > > An `unlockuuid` is good for one bulk session — fetch a fresh one each time rather than caching it. > > In Python, collect the distinct UUIDs the model echoed back and resolve them in one call: > > ```python theme={null} > def detokenize(text, known=None): > known = known or {} # {(label, uuid): plaintext} > need = {u for l, u in PLACEHOLDER.findall(text) if (l, u) not in known} > vault = {} > if need: > unlock = bunker("BulkListUnlock", {})["unlockuuid"] > rows = bunker("BulkListTokens", > {"unlockuuid": unlock, "tokens": list(need)})["rows"] > vault = {r["tokenuuid"]: r["record"] for r in rows} > > def resolve(m): > label, uuid = m.group(1), m.group(2) > if (label, uuid) in known: > return known[(label, uuid)] > return vault.get(uuid, m.group(0)) > > return PLACEHOLDER.sub(resolve, text) > ``` > > ```python theme={null} > answer = detokenize(reply) > ``` > > This is the general case: it resolves any token, including ones minted in an earlier turn or by another service. > [tab] Resolve from a prefetched profile > > If the placeholders came from a user record, they all carry the same user token, and one `UserGet` covers every one of them — no `BulkListUnlock`, no bulk-export privilege. > > ```bash theme={null} > curl -X POST http://localhost:3000/v2/UserGet \ > -H "X-Bunker-Token: DEMO" \ > -H "Content-Type: application/json" \ > -d '{"mode":"token","identity":"cba3da40-cab0-fc94-a020-8bab3eaaa7c9"}' > ``` > > ```json theme={null} > { > "status": "ok", > "token": "cba3da40-cab0-fc94-a020-8bab3eaaa7c9", > "profile": { > "name": "Sarah Chen", > "email": "sarah.chen@example.com", > "phone": "+1 415-555-0142", > "address": "1 Market Street, San Francisco, CA" > }, > "version": 1 > } > ``` > > Key the map on the `(label, uuid)` pair, since the UUID alone does not say which field: > > ```python theme={null} > def profile_map(user_token, fields=USER_FIELDS): > profile = bunker("UserGet", {"mode": "token", "identity": user_token})["profile"] > return {(f, user_token): profile[f.lower()] > for f in fields if f.lower() in profile} > ``` > > Pass it as `known` and those placeholders resolve locally: > > ```python theme={null} > answer = detokenize(reply, profile_map("cba3da40-cab0-fc94-a020-8bab3eaaa7c9")) > ``` > > Anything the model echoed that is *not* in that profile — a token from free text, or one carried over from an earlier turn — still falls through to `BulkListTokens`, for exactly those tokens and no more. > > > [!NOTE] > > > > A profile fetched this way is one `UserGet` against a record you are already entitled to read, rather than a bulk detokenization. Scope that entitlement with an [access-control policy](/pro/administration/access-control) so the component resolving replies can read the users it serves and no others. A placeholder neither source recognizes — one the model hallucinated, or one that has expired — is left in place by the `vault.get(uuid, m.group(0))` fallback. It fails closed: an unresolvable token is never silently replaced with the wrong value. ## The complete round trip The four steps compose into the exchange shown at the [top of this page](#what-it-looks-like): ```python theme={null} prompt = ("Draft a reply to the customer at sarah.chen@example.com about the " "disputed $420 charge on card 4532015112830366. Their phone on file " "is +1 415-555-0142 and their SSN is 123-45-6789.") safe = tokenize(prompt) reply = ask(safe) print(detokenize(reply)) ``` `tokenize` finds the four values and swaps in placeholders, `ask` sends a prompt carrying no personal data, and `detokenize` restores the values in the answer. Nothing personal is written to your logs, your traces, or the provider's. ## Retention Give prompt tokens an expiry. A token minted for a conversation rarely needs to outlive it, and expiry means a retention limit does not depend on your bookkeeping being correct: ```bash theme={null} curl -X POST http://localhost:3000/v2/TokenCreate \ -H "X-Bunker-Token: DEMO" \ -H "Content-Type: application/json" \ -d '{"tokentype":"string","record":"sarah.chen@example.com","unique":true,"finaltime":"24h"}' ``` After `finaltime` elapses the token reports `token expired` and stops resolving, with no cleanup call from you. `slidingtime` restarts the window on every access instead, which suits a long-running conversation. To remove a token early, use `TokenDelete` for one or `BulkDeleteTokens` — which takes the same `unlockuuid` as `BulkListTokens` — for many. > [!NOTE] > > Because `unique: true` returns an existing token, a value already in the vault keeps the expiry it was created with. The `finaltime` you send on a repeat call does not extend it. ## What this does not protect Tokenization narrows the blast radius. It does not make the problem go away, and a security reviewer will ask about each of these. * **Tokenized data is still personal data.** This is pseudonymization, not anonymization. Under GDPR the tokenized prompt remains in scope, because you hold the key that reverses it. It reduces exposure to the model provider; it does not take the workload out of scope. * **Detection sets the ceiling.** Everything the patterns miss is sent in the clear. Names, employers, and locations need NER, and NER is not perfect either. * **Context can re-identify.** "The patient in room 4 admitted Tuesday" identifies someone with no tokenizable field present. `unique: true` makes it worse in one specific way: equal values produce equal tokens, so anyone holding two prompts can tell they concern the same person without resolving anything. That is the price of cross-turn consistency — see [why shared records, not long-lived tokens](/pro/concepts/shared-records). * **The model cannot use what it cannot see.** It cannot validate an address, sort by surname, or judge whether an email looks like a throwaway domain. If the task genuinely needs the value, tokenizing that field breaks the task. * **Detokenization is a privilege boundary.** Whatever resolves the reply holds a credential that turns tokens back into plaintext. Scope it with an [access-control policy](/pro/administration/access-control) rather than using the root token, and keep the detokenizing step out of any component that forwards text onward. * **The audit trail records the call, not the token.** `TokenGet`, `BulkListUnlock`, and `BulkListTokens` each write an audit event with the caller identity, tenant, timestamp, and status — enough to show who detokenized and when, but not which values they resolved. ## Why not just build the token store? This is a small enough problem to build yourself, and with a model helping you write it, an afternoon is enough. A table, a UUID per value, two functions: ```python theme={null} # tokens(uuid TEXT PRIMARY KEY, label TEXT, value TEXT) def mint(db, label, value): tok = str(uuid.uuid4()) db.execute("INSERT INTO tokens VALUES (?, ?, ?)", (tok, label, value)) return tok def resolve(db, tok): row = db.execute("SELECT value FROM tokens WHERE uuid = ?", (tok,)).fetchone() return row[0] if row else None ``` That is not a strawman. It is the right shape, it survives restarts and multiple workers, and on the happy path it does everything this guide describes. What it also does is collect every personal value that has ever passed through a prompt into one table, in plaintext, next to the token that names it. That table is now the most sensitive asset in your system: anything that can read it has undone the tokenization for your entire history, and the more prompts you tokenize the more that is worth. The remaining work is not prompt handling — it is turning a mapping table into something you can defend, and hand to an auditor. | | Your own token store | Databunker Pro | | - | - | - | | The mapping at rest | A plaintext column, as safe as the database around it | Each record AES-256 encrypted under a [master key](/pro/administration/master-key) that is never exposed — not to you, not through any API | | Key custody | One key in an environment variable; leaking it and losing it are both terminal | You hold only the wrapping key. [Rotate it](/pro/administration/key-rotation) through an API call without re-encrypting a record; recover it from any three of five [Shamir shares](/pro/administration/shamir-keys) | | Who may turn a token back into a value | Anyone holding database credentials, or anyone who can reach the endpoint | A scoped [access-control policy](/pro/administration/access-control) per API token — the component that resolves replies need not be able to do anything else | | Reading many values at once | One `SELECT` away, which is also what an attacker runs first | A separate `BulkListUnlock` authorization step, plus [bulk export controls](/pro/concepts/select-security) on how much can leave at all | | Evidence for an auditor | Logging you write, covering what you remembered to cover | Every create and every resolve audited, with the PII inside the audit events itself encrypted | | Tenant isolation | `WHERE tenant = ?` on every query, correct every time, forever | PostgreSQL [row-level security](/pro/administration/multi-tenancy#database-level-tenant-isolation) — a query that omits its tenant condition still returns nothing | | Retention | A cleanup job you write, and your bug if it misses | `finaltime` and `slidingtime` expire the token unprompted | | An erasure request | Locate every surviving copy, including replicas and backups | `TokenDelete`, or `BulkDeleteTokens` for many | | The same email on turn 1 and turn 7 | Dedupe yourself, or one person looks like a different one each turn | `unique: true` returns the token already issued | | A card that must stay card-shaped | Implement format-preserving encryption yourself | `tokenbase` — same length, still Luhn-valid | The vault is not free, and the honest entries run the other way too: | | Your own token store | Databunker Pro | | - | - | - | | Latency | A local query | One call to tokenize, one to resolve | | Cost per value | Storage | One licensed record per distinct value — see [what counts as a record](/pro/get-started/licensing#what-counts-as-a-record) | | Failure mode | Your database is already on the request path | The vault becomes a dependency on the request path | So the question is not whether you can build it. It is whether the table that reverses tokenization for every prompt you have ever sent is something you want to own, secure, rotate keys for, isolate per tenant, and defend in an audit. Once it is, you have started building a vault — and the [build-or-buy trade-off](/pro/comparisons/custom-solution-alternative) applies in full. ## Related * [Store user fields](/pro/howtos/store-user-fields) — whole-profile records versus per-field tokens * [Format-preserving tokenization](/pro/concepts/tokenization) — token types, expiry, bulk operations * [Access control](/pro/administration/access-control) — scoping who may detokenize * [Licensing and limits](/pro/get-started/licensing#what-counts-as-a-record) — what counts as a record # Update the license key Source: https://docs.databunker.org/pro/howtos/update-license Apply a new license key to a running Databunker Pro instance. Databunker Pro stores its license key in the database (the `config` table, under the `licensekey` key). You can replace it at any time on a running instance — there is no need to restart the service or redeploy. > [!NOTE] > > This page covers applying a key. For what a license controls — record caps, what counts as a record, how many licenses a deployment needs, and what happens at the cap or at expiry — see [Licensing and limits](/pro/get-started/licensing). A new license is typically applied when you: * Move from **Trial** mode to a paid license. * Renew a license that is about to expire. * Increase the maximum number of records (`maxrecords`) your plan allows. > [!NOTE] > > Only the **main tenant** administrator (root token, tenant id `1`) can set the license key. The new key is validated before it is saved — an invalid or expired key is rejected and the existing license stays in place. ## Before you start To complete this guide, you'll need: * A running Databunker Pro instance. * The **root access token** of the main tenant. See [Generate admin credentials](/pro/installation/generate-admin-credentials). * A valid license key. Request or renew one in the [Databunker Portal](https://portal.databunker.org), then fetch it from there once it is approved. ## Update via the API Send the new key to the `SystemSetLicenseKey` endpoint. All Databunker Pro API calls use `POST /v2/` and authenticate with the `X-Bunker-Token` header. ```bash theme={null} curl -X POST http://localhost:3000/v2/SystemSetLicenseKey \ -H "X-Bunker-Token: YOUR-ROOT-TOKEN" \ -H "Content-Type: application/json" \ -d '{"licensekey": "YOUR-NEW-LICENSE-KEY"}' ``` A successful response looks like this: ```json theme={null} { "status": "ok", "result": "done" } ``` If the key is invalid or expired, the call returns an error and the current license is left unchanged: ```json theme={null} { "status": "error", "message": "License key is invalid" } ``` > [!TIP] > > You can pre-load a license at first start with the `DATABUNKER_LICENSEKEY` environment variable. This is only used during the initial setup; once a key is stored in the database, update it using the API call above. # Install with Docker Compose Source: https://docs.databunker.org/pro/installation/docker-compose This page walks you through the steps to install Databunker Pro using Docker Compose. > [!TIP] > > Only evaluating? [Demo mode](/pro/get-started/quickstart) runs a complete instance from a single `docker run`, with no database server and no setup wizard. Use this guide when you want persistent storage and real credentials. ## Before you start To complete this guide, you'll need [Docker Compose](https://docs.docker.com/compose/install/) installed on your computer. To confirm if Docker Compose is available, run the following command: ```sh theme={null} docker compose version ``` ## Clone the setup repository The repository contains configuration and helper scripts to help you get started. ```sh theme={null} git clone https://github.com/securitybunker/databunkerpro-setup.git cd databunkerpro-setup ``` ## Generate configuration files In this step, you'll generate a set of environment files that will be used to configure each of the services deployed by Docker Compose. **1. Choose your preferred database** This determines the database that Docker Compose should deploy. You don't need an existing database. > [tab] PostgreSQL > > ```sh theme={null} > cd docker-compose-pgsql > ``` > [tab] MySQL > > ```sh theme={null} > cd docker-compose-mysql > ``` > [tab] Oracle > > ```sh theme={null} > cd docker-compose-oracle > ``` > > This stack runs Oracle Database 23ai Free using the [`gvenzl/oracle-free`](https://github.com/gvenzl/oci-oracle-free) image. See [Oracle Database backend](/pro/installation/oracle-database) for the connection variables and for pointing Databunker Pro at a managed Oracle instance instead. **2. Generate environment files** The following command will create a `.env` directory containing environment files for each Docker Compose service. ```sh theme={null} ./generate-env-files.sh ``` ## Deploy Databunker Pro using Docker Compose **1. Start Docker Compose services** ```sh theme={null} docker compose up -d ``` **2. Copy the access code from the logs** On first start Databunker Pro switches to installation mode and prints a one-time six-digit access code. Follow the Databunker Pro container logs to read it: ```sh theme={null} ./logs.sh ``` ``` 2026/07/30 06:32:08 Databunker tables are missing - switching to installation mode 2026/07/30 06:32:08 Open HTTP listener 0.0.0.0:3000 2026/07/30 06:32:08 Access code: 392629 ``` Copy the access code, then press `Ctrl-C` to leave the log view. This only stops following the logs — the container keeps running. **3. Access the web interface** In your browser, open [localhost:3000](http://localhost:3000) to access the Databunker web interface. **4. Last Step: Generate admin credentials** Continue to **[Generate admin credentials](/pro/installation/generate-admin-credentials)** to submit the access code, apply a license key, and capture your root access token, wrapping key, and Shamir key shares. ## Oracle-specific notes If you chose the Oracle stack, a few things differ from PostgreSQL and MySQL: * **First boot takes a few minutes** while Oracle initializes — longer on Apple Silicon, where the image runs emulated. Follow the progress with `./logs.sh` and wait for the access code before opening the web interface. * **There is no separate database to create.** The image auto-creates the schema user from `APP_USER` / `APP_USER_PASSWORD` inside the `FREEPDB1` pluggable database, and in Oracle the schema *is* the namespace (`ORACLE_SERVICE=FREEPDB1`). * **Passwords are short by design.** Oracle limits passwords to 30 bytes and parses them as identifiers, so `generate-env-files.sh` produces a short, letter-initial, alphanumeric password. * **TLS is opt-in** and requires an Oracle wallet. Run `./generate-env-files.sh ssl` and see `docker-compose-oracle/README.md` for the two-step setup. * `./oracle.sh` opens a `sqlplus` session as the schema user. # Generate admin credentials Source: https://docs.databunker.org/pro/installation/generate-admin-credentials This page explains the steps needed to set up Databunker Pro for the first time. ## Before you start To complete this guide, you'll need: * Databunker Pro installed * *(Optional)* A Databunker Pro License Key. > [!NOTE] > > Automating your deployment? You can complete this setup over the API without a browser — see [Unattended installation](/pro/installation/unattended-installation). ## Copy the generated access code from the logs When Databunker Pro starts for the first time, it generates a six-digit access code and outputs it to the service logs. How you read the logs depends on how you deployed Databunker Pro: > [tab] Docker Compose > > From your `docker-compose-*` directory, follow the Databunker Pro container logs and wait for the access code, then press `Ctrl-C` to leave the log view: > > ```sh theme={null} > ./logs.sh > ``` > [tab] Kubernetes > > ```sh theme={null} > kubectl logs deployment/databunkerpro | grep "Access code" > ``` ## Complete the setup in your browser To complete the setup, you'll need access to the Databunker Pro web interface from your browser. **1. Open the web interface in your browser** By default, the web interface is exposed on port 3000. **2. Submit access code and license key** You have three options for the license key field: * **Trial license key** — create a free trial account at [portal.databunker.org/trial](https://portal.databunker.org/trial) and generate a key that covers up to **1 million records for 30 days**. * **Leave it empty** — Databunker Pro runs in Trial mode, limited to **1,000 records for 14 days**, which is enough to evaluate it. * **Paid license key** — request a production license in the [Databunker Portal](https://portal.databunker.org) and fetch the key once it is approved. > [!NOTE] > > Trial mode expires 14 days after setup, after which the vault becomes read-only. A portal trial key raises this to 1 million records for 30 days. See [Licensing and limits](/pro/get-started/licensing) for record caps, expiry behaviour, and how many licenses a deployment needs. ![Initial setup for Databunker Pro](https://mintcdn.com/databunker-a1572a73/hvGKCYP1R-BJ-Gdg/pro/installation/setup-form.png?fit=max\&auto=format\&n=hvGKCYP1R-BJ-Gdg\&q=85\&s=d7d1f371b51595961192209f13b82e10) **3. Copy the generated secrets** Copy the following secrets from the page and store them securely: * Root Access Token * Wrapping Key * Shamir Key Shares ![A setup page displaying root access token and encryption keys](https://mintcdn.com/databunker-a1572a73/hvGKCYP1R-BJ-Gdg/pro/installation/setup-complete.png?fit=max\&auto=format\&n=hvGKCYP1R-BJ-Gdg\&q=85\&s=24513fe31ef138c1126857960f95f7d3) **4. Start Databunker Pro** Finally, click **Start Databunker Pro** to start the service. Databunker Pro is now running and ready to use. Next, learn how to issue scoped credentials in the [Authentication reference](/pro/api/authentication) — and before going live, work through the [production checklist](/pro/installation/production-checklist). # Install with Kubernetes using Helm Source: https://docs.databunker.org/pro/installation/kubernetes-helm This page walks you through the steps to install Databunker Pro on Kubernetes using Helm. ## Before you start To complete this guide, you'll need: * [Kubernetes](https://kubernetes.io/docs/setup/) installed * [Helm](https://helm.sh/docs/intro/install/) installed ## Set up the Helm repository In this step, you'll set up the Databunker Pro Helm repository so that you can download the latest Helm charts. **1. Add the Databunker Pro Helm repository** ```sh theme={null} helm repo add databunkerpro https://securitybunker.github.io/databunkerpro-setup ``` **2. Verify the repository was added** ```sh theme={null} helm repo list ``` You'll see the following output: ```plain theme={null} NAME URL databunkerpro https://securitybunker.github.io/databunkerpro-setup ``` **3. Download the latest Helm chart** ```sh theme={null} helm repo update ``` > [!NOTE] > > You can find the Helm charts in the > [databunkerpro-setup](https://github.com/securitybunker/databunkerpro-setup) > repository. ## Deploy Databunker Pro using Helm **1. Install the Databunker Helm chart** ```sh theme={null} helm install databunkerpro databunkerpro/databunkerpro ``` **2. Set up port forwarding** ```sh theme={null} kubectl port-forward service/databunkerpro 3000:3000 ``` For more information about port-forwarding in Kubernetes, see [Use Port Forwarding to Access Applications in a Cluster](https://kubernetes.io/docs/tasks/access-application-cluster/port-forward-access-application-cluster/). **3. Access the web interface** In your browser, open [localhost:3000](http://localhost:3000) to access the Databunker web interface. **4. Follow the instructions in web interface** For detailed instructions, see [Generate admin credentials](/pro/installation/generate-admin-credentials). # Oracle Database backend Source: https://docs.databunker.org/pro/installation/oracle-database Run Databunker Pro on Oracle Database — supported editions, connection settings, schema bootstrap, and a complete AWS RDS for Oracle setup including TLS. Databunker Pro stores its encrypted vault in a SQL database. Alongside PostgreSQL (the default) and MySQL, it supports **Oracle Database**. The Oracle backend is built into the standard image and selected automatically at startup when the **`ORACLE_HOST`** environment variable is set — there is no separate build or plugin. The driver is the pure-Go [`go-ora`](https://github.com/sijms/go-ora) client. ## Choose an edition Before you provision, pick the edition that matches the features you need. | Feature | Standard Edition 2 (SE2) | Enterprise Edition (EE) | | - | - | - | | User-record vault (tokenize/detokenize user profiles) | ✅ | ✅ | | Format-preserving tokenization (e.g. credit cards) | ❌ | ✅ | Format-preserving tokenization stores its data in a **range-partitioned `tokens` table**, and table partitioning is an **Enterprise Edition** option — it is not available in SE2 (or in any release, including 23ai, without EE). On SE2, Databunker Pro creates the full user-record schema and runs normally; the partitioned `tokens` table is **not** created, so the [format-preserving tokenization](/pro/concepts/tokenization) feature is unavailable. > [!NOTE] > > **Rule of thumb:** If you only tokenize **user records**, **Standard Edition 2** is enough — and on AWS RDS it is available with a bundled license (no Oracle license to procure). If you need **format-preserving tokens** (credit cards, deterministic field tokens), use **Enterprise Edition**. ## Connection settings Point Databunker Pro at Oracle with these environment variables: | Variable | Required | Description | | - | - | - | | `ORACLE_HOST` | ✅ | Hostname of the Oracle listener. Setting this selects the Oracle backend. | | `ORACLE_PORT` | | Listener port. Default `1521`; use `2484` for TLS (TCPS). | | `ORACLE_SERVICE` | ✅ | Service name (or PDB name). On AWS RDS this is the DB name / SID. | | `ORACLE_SID` | | Alternative to `ORACLE_SERVICE` if your instance uses a SID. | | `ORACLE_USER_NAME` | ✅ | Application schema user (e.g. `bunkeruser`). | | `ORACLE_USER_PASS` | ✅ | Password for the schema user. | | `ORACLE_USER_PASS_FILE` | | Path to a file holding the password (takes precedence over `ORACLE_USER_PASS`). | | `ORACLE_SSL_MODE` | | Set to `require` to connect over TLS. Any value other than `disable`/`false` enables TLS. | > [!WARNING] > > Oracle limits passwords to **30 bytes** and parses them as identifiers. Use a short, letter-initial, alphanumeric password for the schema user (avoid long hex strings and special characters). > [!NOTE] > > When `ORACLE_SSL_MODE` enables TLS, Databunker Pro **encrypts the connection but does not currently verify the server certificate**. The transport is encrypted; server-identity verification is not performed. Keep Databunker Pro and the database on a private network. ## Create the schema user Databunker Pro creates its own tables and indexes on first start, but it needs a **schema user to own them**. Connect as a privileged user (a DBA, or the RDS master user) and create it once: ```sql theme={null} CREATE USER bunkeruser IDENTIFIED BY "ChangeMe1234"; GRANT CONNECT, RESOURCE TO bunkeruser; GRANT CREATE SESSION, CREATE TABLE, CREATE SEQUENCE, CREATE VIEW, CREATE PROCEDURE, CREATE TRIGGER TO bunkeruser; ALTER USER bunkeruser QUOTA UNLIMITED ON USERS; ``` Unlike PostgreSQL, Oracle has no separate `databunkerdb` database — the **schema is the namespace**, so there is nothing else to create. Then set `ORACLE_USER_NAME=bunkeruser` and `ORACLE_USER_PASS=…` and start Databunker Pro. ## Docker Compose Point the Databunker Pro service at your Oracle instance through its environment file: ```sh .env/databunker.env theme={null} DATABUNKER_WRAPPINGKEY=<48-hex-character wrapping key> # Oracle connection ORACLE_HOST=oracle.internal ORACLE_PORT=1521 ORACLE_SERVICE=ORCL ORACLE_USER_NAME=bunkeruser ORACLE_USER_PASS=ChangeMe1234 # ORACLE_SSL_MODE=require # and ORACLE_PORT=2484 for TLS # Redis connection REDIS_HOST=redis REDIS_PORT=6379 REDIS_USER_PASS= REDIS_USER_NAME=default ``` The rest of the Compose file is identical to the [Docker Compose](/pro/installation/docker-compose) guide — only the database variables change. ## AWS RDS for Oracle RDS is the most common managed-Oracle target. A few RDS-specific details matter. **1. Create the instance** Choose the edition and licensing model: * **SE2 with a bundled license** — no Oracle license to bring: ```sh theme={null} aws rds create-db-instance \ --db-instance-identifier databunker-oracle \ --engine oracle-se2 --license-model license-included \ --engine-version 19.0.0.0.ru-2026-04.spb-1.r1 \ --db-name ORCL \ --db-instance-class db.r6i.2xlarge \ --allocated-storage 400 --storage-type gp3 --storage-encrypted \ --master-username admin --manage-master-user-password \ --no-publicly-accessible ``` * **Enterprise Edition** uses `--engine oracle-ee` and requires **Bring-Your-Own-License** (`--license-model bring-your-own-license`). RDS does not offer EE with a bundled license. The **DB name** you pass (`ORCL`, ≤ 8 characters) becomes the `ORACLE_SERVICE` value. **2. Create the schema user** Connect as the RDS **master user** (not `SYS`) and run the [`CREATE USER` block above](#create-the-schema-user). The master user has the privileges to create `bunkeruser` and grant it a quota. **3. Enable TLS (recommended)** RDS does not serve Oracle TLS by default — you enable it with an **option group** that adds the `SSL` option and opens the **TCPS listener on port 2484** (port 1521 stays plaintext). ```sh theme={null} aws rds create-option-group --option-group-name databunker-oracle-ssl \ --engine-name oracle-se2 --major-engine-version 19 \ --option-group-description "TLS for Databunker Pro" aws rds add-option-to-option-group --option-group-name databunker-oracle-ssl \ --apply-immediately \ --options '[{"OptionName":"SSL", "VpcSecurityGroupMemberships":["sg-xxxxxxxx"], "OptionSettings":[ {"Name":"SQLNET.SSL_VERSION","Value":"1.2"}, {"Name":"SQLNET.CIPHER_SUITE","Value":"TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"}]}]' ``` Then attach the option group to the instance (`--option-group-name databunker-oracle-ssl` on create or `modify-db-instance`), and set `ORACLE_PORT=2484` and `ORACLE_SSL_MODE=require`. > [!WARNING] > > **Do not leave `SQLNET.CIPHER_SUITE` at the RDS default.** The default (`SSL_RSA_WITH_AES_256_CBC_SHA`) is a legacy RSA-CBC cipher that Go's TLS stack does not offer, so the `go-ora` driver **cannot complete the handshake** and you will see `tls: handshake failure`. Pin a modern ECDHE-GCM suite such as `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`, which both RDS and the driver support. ## Verify Once Databunker Pro is running against Oracle, confirm it is serving: ```sh theme={null} curl -fsS http://localhost:3000/status ``` For automated first-time setup, see [Unattended installation](/pro/installation/unattended-installation) — the flow is identical; only the `ORACLE_*` variables replace the `PGSQL_*` ones. ## Next steps * [Generate admin credentials](/pro/installation/generate-admin-credentials) and start the vault. * Review capacity and throughput expectations on the [Performance & benchmarks](/pro/get-started/performance) page. # Production checklist Source: https://docs.databunker.org/pro/installation/production-checklist What to confirm before putting Databunker Pro in front of real users — keys, database, network, access control, backup, and monitoring. Work through this before go-live. Each item links to the page that explains it; this page is the list, not the explanation. ## Keys and secrets * [ ] **The wrapping key is stored in a secret manager**, not in a file next to the deployment. AWS Secrets Manager, HashiCorp Vault, Google Secret Manager, or a Kubernetes secret. * [ ] **All five [Shamir key shares](/pro/administration/shamir-keys) are captured and distributed** to different custodians, in different systems. Three or more must never be reachable by one person. * [ ] **Custody is documented** — who holds which share, and how to reach them. Never record the share values themselves. * [ ] **A [wrapping key rotation](/pro/administration/key-rotation) has been rehearsed** on a non-production vault. It exercises the same three-share path as recovery, with no risk to data. * [ ] **`DATABUNKER_SETUPKEY` has been removed** from the environment. It is only needed for [unattended installation](/pro/installation/unattended-installation) and stays disabled once the vault is installed. > [!WARNING] > > If the wrapping key is lost and fewer than three shares remain, the data cannot be decrypted — by you or by us. See [what is recoverable](/pro/administration/key-rotation#what-is-recoverable). ## Database * [ ] **Using a dedicated database server** — RDS, Cloud SQL, Azure Database, Oracle Cloud, or a properly managed self-hosted instance. Do not run the production database as a container alongside the application. * [ ] **Sized for your record count.** See the [sizing guide](/pro/get-started/performance#how-to-size-your-deployment) — storage is \~5.7 KB per record, and database vCPU is what limits write throughput at scale. * [ ] **TLS enforced on the database connection** (`PGSQL_SSL_MODE=require`, `ORACLE_SSL_MODE=require`, or the equivalent). * [ ] **On PostgreSQL, the `mtenant` and `madmin` roles exist** and are granted to the login user. These enforce [database-level tenant isolation](/pro/administration/multi-tenancy#database-level-tenant-isolation). * [ ] **Automated backups are enabled and retention is set** to match your recovery objective. * [ ] **A restore has actually been tested.** An untested backup is an assumption. ## Network and TLS * [ ] **Databunker Pro is not exposed to the public internet.** It should be reachable only from your application tier. * [ ] **TLS terminates in front of the service** — ingress, load balancer, or service mesh. * [ ] **Security groups and firewall rules** restrict database access to the application subnet. * [ ] **The web interface is restricted** to administrators, not published alongside the API. ## Access control * [ ] **The root token is not used by applications.** Issue [scoped role tokens](/pro/api/authentication) instead and keep root for administration. * [ ] **Roles and policies reflect least privilege** — see [access control](/pro/administration/access-control). * [ ] **Field-level masking is configured** so responses return only the fields each role needs. * [ ] **Bulk retrieval stays disabled** unless you need it. The [bulk-unlock mechanism](/pro/concepts/select-security) is default-deny by design; `list_users` should stay off unless something depends on it. * [ ] **Tenant tokens are used for tenant-scoped work**, so a compromised token cannot reach across tenants. ## Backup and recovery See [backup and recovery](/pro/administration/backup-and-recovery) for the runbook and the export path. * [ ] **Backups cover the database *and* the wrapping key.** Either one alone will not restore service. * [ ] **The licence key is recorded** somewhere you can reach during an incident. * [ ] **Recovery objectives are written down** — how much data you can lose, and how long a restore may take. * [ ] **Someone other than the person who set it up** has run through the restore procedure. ## Licence and capacity * [ ] **The licence record cap covers your projected growth**, not just today's count. See [licensing and limits](/pro/get-started/licensing). * [ ] **Alerting on `totalnumrecords / licensemaxrecords` crossing 80%** and on `licensefinalexpiration` coming within 30 days. Both failures are silent until a write is refused. * [ ] **Non-production environments use their own licence keys**, so test data never consumes production capacity. ## Monitoring See [monitoring](/pro/administration/monitoring) for the scrape config and alert rules. * [ ] **Service health is polled** — `GET /status`. * [ ] **Database CPU alerts at 70%.** Past that point, adding application instances will not raise write throughput. * [ ] **Index cache-hit ratio is watched** — it stayed above 97% in every benchmark run; a sustained drop means the working set no longer fits in RAM. * [ ] **403 rate is monitored.** A spike means either a licence limit was reached or something is failing authorisation. * [ ] **Audit-write failures page someone.** The [audit trail](/pro/get-started/security-overview) is a compliance control, not just a log. ## Before you switch traffic on * [ ] The deployment has run under realistic load in staging. * [ ] The team knows where the wrapping key lives and who holds the Shamir shares. * [ ] Someone is on call who has read [what is recoverable](/pro/administration/key-rotation#what-is-recoverable). # Unattended installation Source: https://docs.databunker.org/pro/installation/unattended-installation Complete the Databunker Pro first-time setup automatically over the API — no browser required — for CI/CD, infrastructure-as-code, and reproducible deployments. The [browser-based setup](/pro/installation/generate-admin-credentials) is the easiest way to install Databunker Pro by hand. For automated, repeatable deployments — CI/CD pipelines, infrastructure-as-code, container orchestration — Databunker Pro exposes a **`POST /autoinstall`** endpoint that performs the same first-time setup **without a browser**. This guide shows how to complete the install programmatically and capture the generated credentials. ## Before you start * Databunker Pro **deployed** (see [Docker Compose](/pro/installation/docker-compose) or [Kubernetes / Helm](/pro/installation/kubernetes-helm)). * The **`DATABUNKER_SETUPKEY`** environment variable set on the Databunker Pro container — this enables the `/autoinstall` endpoint (details below). * A reachable database. If you use a **dedicated / managed database** (e.g. AWS RDS), create the `databunkerdb` database and roles first — see [Using an external database](#using-an-external-database). * *(Optional)* a Databunker Pro **license key**. Without one, Databunker Pro runs in Trial mode. ## How it works Unattended installation is three HTTP calls against the Databunker Pro service: 1. **`GET /status`** — wait until the service is up. 2. **`GET /dbstatus`** — check whether setup is still required (`{"installed": false}`). 3. **`POST /autoinstall`** — perform the setup and return the credentials. > [!NOTE] > > **Setup endpoints are ephemeral.** While the vault is not yet installed, Databunker Pro runs a small **setup server** that hosts `/dbstatus`, `/setup`, and `/autoinstall`. As soon as setup completes, that server shuts down and the container **restarts in normal operational mode** — where only the regular API (`/status`, `/v2/*`) is served and **`/dbstatus` returns `404`**. That 404 is expected: it means the vault is already installed. (`/dbstatus` only ever returns a boolean `installed` flag — no sensitive data.) The install runs once: call `/autoinstall` **only** when `/dbstatus` explicitly returns `installed: false`; treat a `404`, a connection error, or any other response as **"already installed — skip."** ## Enable the setup endpoint The `/autoinstall` endpoint is only available when a setup key is configured. Set **`DATABUNKER_SETUPKEY`** (and the persistent **`DATABUNKER_WRAPPINGKEY`**) in the container environment before starting Databunker Pro — for Docker Compose, in `.env/databunker.env`: ```sh theme={null} # Enables unattended install DATABUNKER_WRAPPINGKEY=<48-hex-character wrapping key> DATABUNKER_SETUPKEY= # Database connection PGSQL_HOST=postgresql PGSQL_PORT=5432 PGSQL_USER_NAME=bunkeruser PGSQL_USER_PASS= PGSQL_DATABASE=databunkerdb PGSQL_SSL_MODE=disable # Redis connection REDIS_HOST=redis REDIS_PORT=6379 REDIS_USER_NAME=default REDIS_USER_PASS= ``` `DATABUNKER_SETUPKEY` is only needed to run the unattended install — once the vault is installed you can remove it, and the setup endpoint stays disabled. **`DATABUNKER_WRAPPINGKEY`, on the other hand, must persist for the life of the vault**: it is the wrapping key that unlocks the encrypted database on every start, so the container cannot open the vault without it. The `PGSQL_*` and `REDIS_*` keys point the container at your backing stores. > [!WARNING] > > `DATABUNKER_SETUPKEY` only matters during the install, which is a one-time operation: anyone who reaches the service with it can install the vault, so use a long random value. Once the vault is installed the setup endpoint is disabled and the key stops being sensitive — you can safely remove it. Then reference that file from the Databunker Pro service in `docker-compose.yml`: ```yaml theme={null} services: databunkerpro: image: securitybunker/databunkerpro:latest restart: unless-stopped env_file: - .env/databunker.env entrypoint: /bin/sh command: -c "/databunker/bin/databunkerpro -db databunkerdb -conf /databunker/conf/databunker.yaml" volumes: - ../conf/databunker.yaml:/databunker/conf/databunker.yaml ports: - "3000:3000" ``` `DATABUNKER_WRAPPINGKEY` and `DATABUNKER_SETUPKEY` are loaded from `.env/databunker.env`, so the `/autoinstall` endpoint is enabled as soon as the container comes up. ## Run the unattended install **1. Wait until Databunker Pro is ready** Poll `GET /status` until it returns `200 OK`: ```sh theme={null} until curl -fsS http://localhost:3000/status >/dev/null; do sleep 2; done ``` **2. Check whether setup is required** ```sh theme={null} curl -s http://localhost:3000/dbstatus ``` Only `{"status":"ok","installed":false}` means setup is needed. Any other outcome — `installed: true`, a **`404`** (the setup server has already shut down), or a connection error — means the vault is already installed, so **skip `/autoinstall`**. **3. Run autoinstall** Send the setup key (and optional license key) as form fields: > [tab] curl > > ```sh theme={null} > SETUPKEY=$(grep '^DATABUNKER_SETUPKEY=' .env/databunker.env | cut -d= -f2-) > > curl -s -X POST http://localhost:3000/autoinstall \ > --data-urlencode "setupkey=$SETUPKEY" \ > --data-urlencode "licensekey=$LICENSEKEY" # optional; omit for Trial mode > ``` > > > [!NOTE] > > > > Use `--data-urlencode` (not `-d`): license keys are base64 and may contain `+` or `/`, which `-d` would corrupt. > [tab] Python > > ```python theme={null} > import time > import requests > > BASE = "http://localhost:3000" > SETUPKEY = "..." # value of DATABUNKER_SETUPKEY > LICENSEKEY = "" # optional; leave empty for Trial mode > > # 1. wait until ready > for _ in range(30): > try: > if requests.get(f"{BASE}/status", timeout=5).ok: > break > except requests.ConnectionError: > pass > time.sleep(2) > > # 2. install only if the vault explicitly reports installed=false. > # A 404 / error means the setup server is gone -> already installed -> skip. > def needs_install() -> bool: > try: > return requests.get(f"{BASE}/dbstatus", timeout=10).json().get("installed") is False > except Exception: > return False > > if needs_install(): > body = {"setupkey": SETUPKEY} > if LICENSEKEY: > body["licensekey"] = LICENSEKEY > resp = requests.post(f"{BASE}/autoinstall", data=body, timeout=30).json() > assert resp.get("status") == "ok" and resp.get("root_token"), resp > # 3. persist resp securely — see next step > save_credentials(resp) > else: > print("Databunker Pro already installed — skipping autoinstall") > ``` **4. Save the generated credentials** On success the response contains the vault credentials: ```json theme={null} { "status": "ok", "root_token": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", "wrapping_key": "...", "shamir_keys": ["...", "...", "...", "...", "..."] } ``` Store all of these in your secrets manager immediately. > [!WARNING] > > These secrets are shown **once** and cannot be retrieved again. The **`root_token`** is your admin credential — you pass it as the `X-Bunker-Token` header on every administrative API call. Losing it means re-installing. ## Verify The setup server restarts the container in normal mode. Confirm it is serving, then use the root token for API calls: ```sh theme={null} curl -fsS http://localhost:3000/status ``` ```sh theme={null} curl -s -X POST http://localhost:3000/v2/SystemGetSystemStats \ -H "X-Bunker-Token: $ROOT_TOKEN" ``` ## Using an external database The bundled Docker Compose project provisions the `databunkerdb` database and its roles automatically. When you point Databunker Pro at a **dedicated / managed** database (AWS RDS, Cloud SQL, Azure Database), create them yourself first — connect as the database master user and run: ```sql theme={null} CREATE ROLE bunkeruser NOSUPERUSER LOGIN PASSWORD ''; CREATE ROLE mtenant NOSUPERUSER NOLOGIN; CREATE ROLE madmin BYPASSRLS NOSUPERUSER NOLOGIN; CREATE DATABASE databunkerdb OWNER bunkeruser; -- then, connected to databunkerdb: GRANT ALL ON SCHEMA public TO bunkeruser; GRANT mtenant TO bunkeruser; GRANT madmin TO bunkeruser; ``` Point the container at the database with the `PGSQL_HOST`, `PGSQL_USER_NAME`, `PGSQL_USER_PASS`, and `PGSQL_SSL_MODE` environment variables, then run the unattended install as above. > [!NOTE] > > If you run **multiple Databunker Pro instances** against one shared database, they must all use the **same `DATABUNKER_WRAPPINGKEY`** (only one instance runs `/autoinstall`; the others start against the already-installed database). The wrapping key must persist across restarts, or the vault cannot be reopened. ## Next steps * [Update your license key](/pro/howtos/update-license) at any time after install. * Rotate and back up your [master (wrapping) key](/pro/administration/master-key) and [Shamir key shares](/pro/administration/shamir-keys). * Learn how to issue scoped credentials in the [Authentication reference](/pro/api/authentication). # Migrate from AWS Cognito Source: https://docs.databunker.org/pro/migrations/aws-cognito Move user attributes out of a Cognito user pool into Databunker Pro — export with ListUsers, import with UserCreateBulk, then cut over authentication with a one-time password reset. This guide moves the user records in an AWS Cognito user pool into Databunker Pro. For the phases and mechanics shared by every migration, see the [migration overview](/pro/migrations/overview). For why teams replace Cognito with an auth library plus a PII vault, see [AWS Cognito vs Databunker Pro](/pro/comparisons/aws-cognito-alternative). > [!WARNING] > > **Cognito does not export password hashes.** There is no API that returns them, so no migration can carry passwords across. Every user must either set a new password once, or sign in through a federated provider. Plan the migration around that constraint — it drives the timing of every other step. ## What moves where Cognito is doing two jobs: authenticating users, and storing their attributes. Databunker Pro replaces only the second. | Cognito holds | After migration | | - | - | | Passwords, MFA enrolment, federated identities | Your new [auth layer](/pro/comparisons/aws-cognito-alternative#authentication-is-now-an-afternoon-not-a-project) | | `email`, `phone_number`, `given_name`, custom attributes | Databunker Pro vault | | `sub` (immutable user id) | Databunker Pro vault, in the indexed `custom` field | | Groups | Databunker Pro groups, or your auth layer | ## Before you start * A running Databunker Pro instance and a **root or admin access token**. * A [license](/pro/get-started/licensing) whose record cap covers your user count. * AWS credentials with `cognito-idp:ListUsers` on the pool. * `pip install databunkerpro boto3` * Your replacement auth layer built and tested, but not yet live. ## No mapping table needed Unlike a [SQL users table migration](/pro/migrations/sql-users-table), there is nothing here to keep in step with the vault. Cognito's `sub` goes into the indexed `custom` field, so any user can be resolved directly: ```python theme={null} api.get_user("custom", sub) ``` The token belongs on your new auth layer's user row — next to the password hash and MFA secret — and that row is created when the user first signs in, not now. So this migration writes only to the vault. ## Step 1: Export and import `ListUsers` returns at most 60 users per page and is throttled, so the export is usually the slow part — not the import. The script runs in two phases: page through the whole pool first, then import the result in chunks of 1,000 via `UserCreateBulk`. Cognito returns attributes as a list of name/value pairs, so they are flattened first, then mapped onto the fields Databunker Pro indexes: | Cognito | Vault field | Notes | | - | - | - | | `sub` | `custom` | Always present. Makes every record findable by its Cognito id. | | `email` | `email` | Only if your pool collects it — email is not mandatory. | | `phone_number` | `phone` | Copied under the name Databunker Pro indexes. | | `Username` | `login` | Skipped when it equals `sub`: pools configured with `UsernameAttributes: ["email"]` generate an opaque UUID rather than a real sign-in name. | Everything else is carried across unchanged, including `custom:*` attributes. ```python theme={null} import csv import os import boto3 from databunkerpro import DatabunkerproAPI CHUNK = 1000 POOL_ID = os.environ["COGNITO_USER_POOL_ID"] cognito = boto3.client("cognito-idp", region_name=os.environ["AWS_REGION"]) api = DatabunkerproAPI( os.environ["DATABUNKER_API_URL"], os.environ["DATABUNKER_API_TOKEN"], os.getenv("DATABUNKER_TENANT_NAME", ""), ) def to_profile(user): """Flatten Cognito attributes into a vault profile keyed by 'sub'.""" attrs = {a["Name"]: a["Value"] for a in user["Attributes"]} profile = dict(attrs) profile["custom"] = attrs["sub"] # indexed: always present if "phone_number" in attrs: profile["phone"] = attrs["phone_number"] # indexed field name in Databunker Pro if user["Username"] != attrs["sub"]: profile["login"] = user["Username"] # indexed: the real sign-in name profile["cognito_status"] = user["UserStatus"] profile["cognito_enabled"] = user["Enabled"] return profile def databunkerpro_create_bulk(batch, errors): result = api.create_users_bulk([{"profile": p} for p in batch]) if result.get("status") != "ok": raise SystemExit(f"Batch failed: {result.get('message')}") for item in result.get("errors", []): errors.writerow([item["profile"].get("custom"), item["reason"]]) return len(result.get("created", [])), len(result.get("errors", [])) def cognito_fetch_all_users(): """Page through the whole pool. ListUsers returns at most 60 at a time.""" users = [] for page in cognito.get_paginator("list_users").paginate(UserPoolId=POOL_ID): users.extend(page["Users"]) print(f"exported {len(users)}", flush=True) return users def main(): users = cognito_fetch_all_users() total = len(users) migrated, failed = 0, 0 with open("cognito-errors.csv", "w", newline="") as fh: errors = csv.writer(fh) errors.writerow(["sub", "reason"]) for offset in range(0, total, CHUNK): batch = [to_profile(u) for u in users[offset:offset + CHUNK]] ok, bad = databunkerpro_create_bulk(batch, errors) migrated, failed = migrated + ok, failed + bad print(f"{offset + len(batch)}/{total} migrated={migrated} failed={failed}", flush=True) print(f"\nDone. Migrated {migrated}, failed {failed}.") if failed: print("Review cognito-errors.csv before continuing.") if __name__ == "__main__": main() ``` > [!NOTE] > > Cognito allows two accounts to hold the same email when the pool is not configured to require uniqueness. Databunker Pro enforces uniqueness per tenant, so the second one is rejected with `Duplicate email value` and appears in `cognito-errors.csv`. Decide which account survives before cutting over. ### Groups If you use Cognito groups, export them separately — `ListUsersInGroup` per group is far cheaper than one `AdminListGroupsForUser` call per user: ```python theme={null} for group in cognito.get_paginator("list_groups").paginate(UserPoolId=POOL_ID): for g in group["Groups"]: members = cognito.get_paginator("list_users_in_group").paginate( UserPoolId=POOL_ID, GroupName=g["GroupName"] ) # map each member's 'sub' to a Databunker group or a role in your auth layer ``` ## Step 2: Verify **1. Counts match** `SystemGetSystemStats` — `totalnumrecords` should have grown by the pool's user count, less anything in `cognito-errors.csv`. **2. Spot-check detokenization** ```python theme={null} sub = ... # a known Cognito sub print(api.get_user("custom", sub)["profile"]["email"]) ``` Because `sub` went into `custom`, any user resolves by their Cognito id directly. **3. Re-run to catch stragglers** Users created in Cognito while the export was running will have been missed. Re-run the script — already-migrated records come back as `Duplicate custom value` in the error CSV, and only the new ones are added. ## Step 3: Cut over authentication This is the step that affects users, so it is worth staging. **1. Point the new auth layer at Databunker Pro** Sign-in looks the user up by email, reads the profile from the vault by token, and issues your own session. No Cognito call remains in the path. **2. Trigger the password reset** Email every user a one-time reset link. Send in waves rather than all at once, so support load and email-reputation damage stay manageable. **3. Keep Cognito readable during the transition** Leave the pool in place but stop writing to it. If something is missing you can still read it, and users who have not reset yet can be identified from `cognito_status` in their vault profile. > [!TIP] > > Federated users — Google, Apple, SAML — need no password reset. Their identity lives with the external provider, so re-pointing your auth layer at the same provider signs them straight back in. Migrating those users first shrinks the population that needs a reset email. ## Step 4: Decommission the pool Once the reset campaign has run its course and Cognito has served no sign-ins for a full business cycle, delete the user pool. > [!WARNING] > > Deleting a Cognito user pool is immediate and irreversible, and there is no export of what it held. Confirm every user is in the vault first, and keep a copy of your export output until you are certain. ## Working with the vault afterwards The calls that replace the Cognito operations you were making before. Every one of the four indexed fields — `email`, `phone`, `login`, `custom` — works as a lookup key, so you rarely need the token itself. **Sign-in: look a user up by email** ```python theme={null} result = api.get_user("email", "jane@example.com") if result.get("status") != "ok": raise ValueError("no such user") token = result["token"] # store this on the auth row you create profile = result["profile"] # given_name, phone, custom:* — as migrated ``` Replaces `AdminGetUser`. The same call works with `"phone"`, `"login"`, or `"custom"` — use `custom` when you hold the Cognito `sub`: ```python theme={null} api.get_user("custom", "9f8b1c2e-...") ``` **Update a profile** ```python theme={null} api.update_user("email", "jane@example.com", {"phone": "+15551234567"}) ``` Replaces `AdminUpdateUserAttributes`. Only the fields you pass are changed. **Delete a user (right to erasure)** ```python theme={null} api.delete_user("email", "jane@example.com") ``` Replaces `AdminDeleteUser` — but unlike Cognito this erases the personal data itself, since it lived only in the vault. The audit trail records the deletion without retaining the data. **Check whether someone exists, without reading their data** ```python theme={null} exists = api.get_user("email", candidate).get("status") == "ok" ``` Useful during the reset campaign, where you want to know whether an address belongs to a migrated user before sending mail to it. > [!TIP] > > `UserGet` returns `404` for an unknown identity, so treat a non-`ok` status as "not found" rather than an error. Every call is written to the [audit trail](/pro/get-started/security-overview), including the ones that find nothing. ## Rolling back | Stage | How to undo | | - | - | | During export and import | Nothing in Cognito has changed. [Wipe the vault](/pro/howtos/clean-users-table) and start again. | | After the auth cutover | Point the application back at Cognito. Passwords still work — users who already reset must use their old Cognito password. | | After deleting the pool | No route back. Rebuild from your export output. | ## Next steps * [Migrate a SQL users table](/pro/migrations/sql-users-table) — if application data also lives in your own database * [Licensing and limits](/pro/get-started/licensing) — what counts as a record * [AWS Cognito vs Databunker Pro](/pro/comparisons/aws-cognito-alternative) — the architecture this migration lands on # Migrating to Databunker Pro Source: https://docs.databunker.org/pro/migrations/overview How to move existing user records into Databunker Pro — the shared migration pattern, and which guide applies to your source system. Adopting Databunker Pro means moving user records you already have into the vault and replacing them with tokens. This section covers how to do that without downtime and without a one-way door. ## Pick your source | Source | Guide | | - | - | | A SQL `users` table (PostgreSQL, MySQL, Oracle) | [SQL users table](/pro/migrations/sql-users-table) | | AWS Cognito user pool | [AWS Cognito](/pro/migrations/aws-cognito) | Migrating from something not listed? The pattern below applies to any source. [Contact us](https://cal.com/databunker-team/30min) if you would like the professional-services team to review your plan. ## The shared pattern Every migration follows the same five phases. Only extraction differs between source systems. **1. Build a parallel destination** Create the token-holding structure alongside the existing one rather than altering it in place. The original stays untouched and readable for the whole migration, which is what makes every earlier phase reversible. **2. Backfill in chunks** Read the source in batches, send each batch to `UserCreateBulk`, and record the returned tokens. Backfilling runs against a live system — the application keeps serving traffic throughout. **3. Verify** Confirm every source record has a token, and that detokenizing returns the original values. Do this before anything is deleted. **4. Move the application to the vault** Dual-write new records, switch reads to the vault, and run in that mode for a full business cycle. Code paths still reading the old data surface here, while recovery is still free. **5. Cut over and remove the old data** Swap in the new structure, keep the old one until you are satisfied, then delete it. This is the only irreversible step. ## Mechanics common to every migration **Keep the record whole.** The entire user record goes into the vault profile — not just the obviously sensitive fields, but every application attribute as well. Splitting a user across two stores leaves you reconciling two sources of truth, with some attributes protected and some not. A 120-field profile is normal; that is what the [benchmarks](/pro/get-started/performance) were run against. **Carry your existing primary key in the profile.** `UserCreateBulk` echoes the submitted profile back alongside each token, so the mapping never depends on response ordering. Putting your source identifier in the indexed `custom` field also makes re-runs safe — a second attempt for the same record is rejected as a duplicate rather than minting a second token — and lets you look records up by legacy id afterwards. **Expect partial success.** A batch does not fail as a unit. `UserCreateBulk` returns `created` and `errors` arrays, with a per-record `reason` for each failure. The usual cause is a duplicate `email`, `phone`, `login`, or `custom` value: Databunker Pro enforces uniqueness within a tenant, so records your source allowed to coexist are rejected here. Log the failures and resolve them before cutting over — those users have no token. **Make the backfill resumable.** Skip records that already have a token, so an interrupted run can simply be restarted. For large sources this matters more than raw speed. **Size the database first.** Bulk writes sustain roughly 5,800 records/sec on one instance, and at tens of millions of rows the **database** becomes the limit rather than Databunker Pro. Check the [sizing guide](/pro/get-started/performance#how-to-size-your-deployment) before a large backfill — adding application instances will not help once the database is at full CPU. **Check your licence covers the row count.** The record cap is evaluated when a bulk request begins. Trial mode stops at 1,000 records; see [licensing and limits](/pro/get-started/licensing). > [!WARNING] > > Deleting the source data is the one step you cannot undo from inside Databunker Pro. Take a fresh backup immediately before it, and be aware that removing rows does not remove them from disk or history — values persist in dead tuples, write-ahead logs, replicas, and any earlier backups until those are vacuumed and expired. ## Rehearse it Run the whole migration against a copy of your data first, on a non-production vault. [Non-production licence keys](/pro/get-started/licensing#non-production-environments) are available from the portal on a three-month term, so a rehearsal does not consume production record capacity. Between attempts, [wipe the vault](/pro/howtos/clean-users-table) for a clean slate. # Migrate a SQL users table Source: https://docs.databunker.org/pro/migrations/sql-users-table Move an existing SQL users table into Databunker Pro — build a token-only newusers table, backfill in chunks with UserCreateBulk, verify, then swap the tables. This guide moves an existing `users` table into Databunker Pro. The whole user record goes into the vault; your application database keeps nothing but a token. For the phases and mechanics shared by every migration, see the [migration overview](/pro/migrations/overview). Rather than altering `users` in place, you build a parallel `newusers` table, backfill it while the application keeps running, verify it, and then swap the two tables in a single transaction. Nothing is destructive until that swap, and the swap itself is reversible. > [!NOTE] > > Timing comes from the [performance benchmarks](/pro/get-started/performance): bulk writes sustain roughly **5,800 records/sec** on a single instance, so 10 M records take about 28 minutes and 100 M around 2.3 hours. At tens of millions of rows the **database** is the limit, not Databunker Pro — see the [sizing guide](/pro/get-started/performance#how-to-size-your-deployment) before starting a large backfill. ## Before you start * A running Databunker Pro instance and a **root or admin access token**. * A [license](/pro/get-started/licensing) whose record cap covers your row count. Trial mode stops at 1,000 records, and the cap is checked when a bulk request begins — see [when the record cap is reached](/pro/get-started/licensing#when-the-record-cap-is-reached). * The Python SDK: `pip install databunkerpro psycopg2-binary` * A **backup of the users table.** ## Step 1: Create the newusers table Two columns: your existing primary key, and the token Databunker Pro returns. > [tab] Standard SQL > > ```sql theme={null} > CREATE TABLE newusers ( > userid BIGINT PRIMARY KEY, -- same value as users.userid > usertoken UUID NOT NULL UNIQUE > ); > ``` > > `userid` is copied from `users.userid`, so no generator is needed for the backfill itself. > [tab] PostgreSQL > > ```sql theme={null} > CREATE TABLE newusers ( > userid BIGSERIAL PRIMARY KEY, -- same value as users.userid > usertoken UUID NOT NULL UNIQUE > ); > ``` > > Use `SERIAL` if your existing `userid` is a 32-bit `INTEGER`. > [tab] MySQL > > ```sql theme={null} > CREATE TABLE newusers ( > userid BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, > usertoken CHAR(36) NOT NULL UNIQUE > ) ENGINE=InnoDB; > ``` > > MySQL has no native UUID column — `CHAR(36)` stores the token as returned. > [!WARNING] > > **On PostgreSQL, reset the sequence before you cut over.** Explicit id inserts do not advance a `SERIAL` sequence, so it is still at 1 while your ids run into the millions, and the first insert after the swap collides with an existing row: > > ```sql theme={null} > SELECT setval(pg_get_serial_sequence('newusers', 'userid'), > (SELECT max(userid) FROM newusers)); > ``` > > MySQL needs no equivalent — `AUTO_INCREMENT` advances itself when you insert a higher explicit value. Everything else in `users` goes into the encrypted vault profile — not just the personal data, but every application field as well: `created_at`, `status`, `plan`, and the rest. A 120-field profile is entirely normal; that is what the benchmarks were run against. Keeping the record whole is the point. Split it across two stores and you are back to reconciling two sources of truth for the same user, with some attributes protected and some not. ## Step 2: Decide how tokens map back to rows `UserCreateBulk` returns the **original profile alongside each token**, so the mapping never depends on response ordering. To use that, carry your primary key inside the profile. The `custom` field is the best place for it. It is one of the four indexed fields and is unique within a tenant, which buys you two things: * **A re-run cannot create duplicate tokens.** A second attempt for the same `userid` is rejected with `Duplicate custom value` instead of silently minting a second token. * **You can look a user up by `userid` later** with `UserGet` using `mode=custom`. The trade-off is that `custom` is then spoken for. If you need it for something else, use a plain unindexed field such as `legacy_userid` — the mapping still works, but you lose the duplicate protection above. ## Step 3: Backfill in chunks The script counts the rows, walks the table in chunks of 4,000, sends each chunk to `UserCreateBulk`, and writes `userid` plus the returned token into `newusers`. Failures are written to a CSV for review. It is written for PostgreSQL. On MySQL, swap `psycopg2` for your connector and `ON CONFLICT (userid) DO NOTHING` for `INSERT IGNORE`. Each chunk prints its offset **before** processing it, so if a run is interrupted you can see exactly where it stopped and resume from there: ```sh theme={null} START_OFFSET=2000000 python migrate.py ``` Resuming matters on a large table. Without it a restart replays every chunk from the beginning — harmless, because the vault rejects records it already holds and `ON CONFLICT DO NOTHING` guards `newusers`, but it re-sends millions of profiles and fills the error log with duplicate reports that bury the genuine conflicts you need to act on. ```python theme={null} import csv import os import psycopg2 import psycopg2.extras from databunkerpro import DatabunkerproAPI CHUNK = 4000 START_OFFSET = int(os.getenv("START_OFFSET", "0")) # resume point after an interruption api = DatabunkerproAPI( os.environ["DATABUNKER_API_URL"], # e.g. https://databunkerpro.myorg.com os.environ["DATABUNKER_API_TOKEN"], os.getenv("DATABUNKER_TENANT_NAME", ""), ) conn = psycopg2.connect(os.environ["APP_DATABASE_URL"]) def count_users(): with conn.cursor() as cur: cur.execute("SELECT count(*) FROM users") return cur.fetchone()[0] def fetch_chunk(offset): with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: cur.execute( "SELECT * FROM users ORDER BY userid LIMIT %s OFFSET %s", (CHUNK, offset), ) return cur.fetchall() def to_profile(row): """The whole row becomes the vault profile; 'custom' carries userid for lookups.""" profile = {k: v for k, v in row.items() if v is not None} profile["custom"] = str(row["userid"]) return profile def save_tokens(created): pairs = [(int(item["profile"]["custom"]), item["token"]) for item in created] with conn.cursor() as cur: psycopg2.extras.execute_values( cur, "INSERT INTO newusers (userid, usertoken) VALUES %s " "ON CONFLICT (userid) DO NOTHING", pairs, ) conn.commit() return len(pairs) def main(): total = count_users() migrated, failed = 0, 0 print(f"{total} users to migrate, starting at offset {START_OFFSET}") # A fresh run starts the error log; a resumed run appends to it. with open("migration-errors.csv", "a" if START_OFFSET else "w", newline="") as fh: errors = csv.writer(fh) if not START_OFFSET: errors.writerow(["userid", "reason"]) for offset in range(START_OFFSET, total, CHUNK): # Printed before the work, so an interrupted run tells you where to resume: # re-run with START_OFFSET set to this value. print(f"offset {offset}/{total}", flush=True) rows = fetch_chunk(offset) result = api.create_users_bulk([{"profile": to_profile(r)} for r in rows]) if result.get("status") != "ok": # Whole request rejected — nothing was inserted. Stop and investigate. raise SystemExit(f"Batch failed: {result.get('message')}") # 'created' echoes the submitted profile, so match on it rather than order. migrated += save_tokens(result.get("created", [])) for item in result.get("errors", []): errors.writerow([item["profile"].get("custom"), item["reason"]]) failed += 1 print(f" migrated={migrated} failed={failed}", flush=True) print(f"\nDone. Migrated {migrated}, failed {failed}.") if failed: print("Review migration-errors.csv before continuing.") if __name__ == "__main__": main() ``` > [!WARNING] > > **Partial success is normal and is not an error.** A batch of 4,000 can return 3,998 in `created` and 2 in `errors`. The usual reason is a duplicate `email`, `phone`, `login`, or `custom` value — Databunker Pro enforces uniqueness per tenant, so rows your old table allowed to coexist will be rejected here. Work through `migration-errors.csv` before continuing; those users have no token and no row in `newusers`, so they would disappear at the swap. ## Step 4: Verify **1. Every row made it across** ```sql theme={null} SELECT (SELECT count(*) FROM users) AS old_rows, (SELECT count(*) FROM newusers) AS new_rows; ``` The counts must match, or differ only by the rows listed in `migration-errors.csv`. **2. Spot-check detokenization** Confirm the vault returns what the old table holds: ```python theme={null} row = ... # a row from users token = ... # its usertoken from newusers assert api.get_user("token", token)["profile"]["email"] == row["email"] ``` **3. Confirm the vault count** `SystemGetSystemStats` — `totalnumrecords` should have grown by the number you migrated. See [checking your usage](/pro/get-started/licensing#checking-your-usage). ### Recover from an interrupted run If the counts do not match, some rows reached the vault but their tokens were never written locally — the script died between the two writes. Because `custom` holds the legacy id, those tokens can be looked up again and written into `newusers`: ```python theme={null} # reconcile.py — recover tokens for rows missing from newusers. # Reuses the imports, `api`, and `conn` from the backfill script above. CHUNK = 4000 with conn.cursor() as cur: cur.execute("SELECT userid FROM users WHERE userid NOT IN (SELECT userid FROM newusers)") missing = [r[0] for r in cur.fetchall()] print(f"{len(missing)} users without a token") recovered = 0 for offset in range(0, len(missing), CHUNK): batch = missing[offset:offset + CHUNK] # The unlock UUID is short-lived, so take a fresh one for each chunk. unlock = api.bulk_list_unlock()["unlockuuid"] found = api.bulk_list_users( unlock, [{"mode": "custom", "identity": str(uid)} for uid in batch] ) pairs = [(int(r["profile"]["custom"]), r["token"]) for r in found.get("rows", [])] if pairs: with conn.cursor() as cur: psycopg2.extras.execute_values( cur, "INSERT INTO newusers (userid, usertoken) VALUES %s " "ON CONFLICT (userid) DO NOTHING", pairs, ) conn.commit() recovered += len(pairs) print(f" {offset + len(batch)}/{len(missing)} checked, {recovered} recovered", flush=True) print(f"\n{len(missing)} missing, {recovered} recovered, " f"{len(missing) - recovered} never reached the vault") ``` `BulkListUsers` is not paginated — every criterion you send is evaluated — so the chunking here is about keeping request bodies and unlock lifetimes sane, not about paging through results. Ids with no vault record are simply absent from `rows`: those never reached the vault, so find them in `migration-errors.csv` and resolve the conflict there. Re-running is safe. Each pass recomputes `missing` from the two tables, so recovered rows drop out and only genuine gaps remain. > [!NOTE] > > This call requires the `list_users` configuration flag to be enabled, otherwise it returns `403 BulkListUsers is disabled`. > [!WARNING] > > Run this before Step 6. Once `users` has been renamed and dropped there is nothing left to compare against, and orphaned records cannot be found. ## Step 5: Point the application at the vault Do this before swapping anything. 1. **Dual-write.** On user creation, call `UserCreate` and insert the returned token into `newusers` in the same transaction as the `users` row, so new users appear in both tables. 2. **Switch reads** to fetch the profile from the vault by token. Joins that used `email` can join on `usertoken` — tokens are stable within a tenant, so this needs no round trip to the vault. 3. **Run in this mode for a full business cycle.** Any code still reading a column directly surfaces here, while the data is present and recovery is free. ## Step 6: Swap the tables Once step 5 has run clean. Both renames must land together, or requests arriving in between hit a missing table. > [tab] PostgreSQL > > DDL is transactional, so both renames commit as one and the cutover is effectively instant: > > ```sql theme={null} > BEGIN; > ALTER TABLE users RENAME TO users_old; > ALTER TABLE newusers RENAME TO users; > COMMIT; > ``` > [tab] MySQL > > DDL auto-commits, so a transaction gives you nothing here. Use `RENAME TABLE`, which swaps both in a single atomic statement: > > ```sql theme={null} > RENAME TABLE users TO users_old, newusers TO users; > ``` Keep `users_old` until you are satisfied, then drop it: ```sql theme={null} DROP TABLE users_old; ``` If other tables have foreign keys pointing at it, the drop is refused until those constraints are dropped or repointed at the new `users`. > [!WARNING] > > **Foreign keys follow the table, not the name.** Any table with a foreign key to `users(userid)` now references `users_old`, because constraints track the table itself rather than its name. Check before swapping, and recreate the constraints against the new `users` afterwards: > > ```sql theme={null} > SELECT conrelid::regclass AS referencing_table, conname > FROM pg_constraint > WHERE confrelid = 'users'::regclass AND contype = 'f'; > ``` > > Sequences, indexes, and constraints also keep their original names after a rename. They function normally, but `newusers_pkey` on a table now called `users` is confusing later — rename them if that matters to you. > [!NOTE] > > Dropping `users_old` removes the personal data from the live table, but **not from disk or from history**. The values remain in dead tuples, the write-ahead log, replicas, and every backup taken before this point. Treat the PII as still present until `VACUUM FULL` has run and those backups have expired. ## Rolling back | Stage | How to undo | | - | - | | During backfill (steps 1–4) | `users` is untouched. `DROP TABLE newusers` and start again, or [wipe the vault](/pro/howtos/clean-users-table) for a clean rehearsal. | | After cutover (step 5) | Revert the application to reading columns from `users`. They are still populated. | | After the swap (step 6), `users_old` still present | Reverse the renames in one transaction — the old table still holds every column. | | After `DROP TABLE users_old` | Restore from backup. There is no other route back. | ## Next steps * [Performance and sizing](/pro/get-started/performance) — size the database before a large backfill * [Licensing and limits](/pro/get-started/licensing) — what counts as a record * [Clean the users table](/pro/howtos/clean-users-table) — reset a test vault between rehearsals