Open Valstorm API (apps/open-api)
Greenfield PostgreSQL-Powered Core Engine for Open Valstorm
Open Valstorm API is a greenfield backend built with Python 3.13, uv, and PostgreSQL 16. It introduces a dedicated logical database-per-tenant architecture with an automated DDL compiler and native SQL query execution, completely eliminating application-layer Python joins and legacy regex SQL transpiling.
1. Architectural Highlights
Dedicated Database-Per-Tenant Isolation
- Zero Cross-Tenant Leaks: Every customer organization operates inside an isolated PostgreSQL database (
CREATE DATABASE org_xyz). Cross-database queries are physically prohibited by the PostgreSQL engine. - Central Directory DB (
valstorm_directory): Coordinates global authentication, organization routing, and the marketplace catalog (app). - Universal Support User Pattern: Every provisioned tenant database automatically attaches an attributable Support User (
support@...), enabling platform administrators to assist customers, run scheduled workflows, and debug without requesting user passwords. - $O(1)$ Instant Custom Fields: Adding custom fields compiles to native PostgreSQL DDL (
ALTER TABLE ... ADD COLUMN ...), executing as an instantaneous metadata-only change in PostgreSQL 11+. - Native ANSI SQL Optimizer: Relational joins (
JOIN ... ON ...) are executed directly by the PostgreSQL query planner with AST sanitization viasqlglot.
2. Tech Stack
| Component | Technology | Description |
|---|---|---|
| Runtime | Python 3.13 | High-performance async runtime |
| Package Manager | uv | Sub-second virtual environment & dependency management |
| Web Framework | FastAPI (ASGI) | REST API & OpenAPI documentation |
| Database Driver | asyncpg | Native async PostgreSQL binary protocol driver |
| Relational Store | PostgreSQL 16 | Dedicated database-per-tenant architecture |
| Cache & Pub/Sub | Valkey 7.2 | High-throughput in-memory token & session caching |
| SQL Engine | sqlglot | AST parser, validator, and LIMIT injector |
3. Quickstart Guide
Step 1: Start the Local Infrastructure
From the repository root, start PostgreSQL and Valkey:
docker compose -f docker-compose.open.yaml up -d- PostgreSQL Port:
localhost:5432(Database:valstorm_directory, User:valstorm, Password:valstorm_password) - Valkey/Redis Port:
localhost:6379
Step 2: Install Python Dependencies via uv
cd apps/open-api
uv syncStep 3: Run the Core Seeder
Initialize the central Directory DB and provision the Admin Org and Client Workspace.
Option A: Interactive Setup Wizard (Recommended for new installs)
uv run python app/seed.py --interactiveOption B: CLI Flags (Ideal for CI/CD & Automation)
Note for macOS (
zsh) /bashusers: Always wrap passwords containing!or$in single quotes ('...') rather than double quotes ("..."). Inzsh,!"inside double quotes triggers history expansion and leaves the quote unclosed (dquote>).
uv run python app/seed.py \
--admin-org-name 'Apex Aerospace HQ' \
--admin-email '[email protected]' \
--admin-password 'AdminSecret123!' \
--support-email '[email protected]' \
--support-password 'SupportSecret123!' \
--client-org-name 'Cyberdyne Systems' \
--client-user-name 'Miles Dyson' \
--client-email '[email protected]' \
--client-password 'ClientSecret123!'Option C: Default Valstorm Development Seed
uv run python app/seed.py- Super Admin:
[email protected]/valstorm_admin_password(Org:org_AwmQ8vSogMavWkw9) - Support User:
[email protected]/valstorm_support_password(Injected into all orgs) - Client Admin:
[email protected]/valstorm_client_password(Org:org_dSnPMRjS1ZkkdYQ2)
Step 4: Start the API Server
uv run uvicorn app.main:app --port 8010 --reloadThe API will be available at http://localhost:8010. Interactive Swagger documentation is available at http://localhost:8010/docs.
4. The 33 Foundational Base App Tables
The Base App (app_0Ik4pJ5P60Bk7x1u) automatically seeds these 33 foundational schemas and tables into each tenant database:
| Category | PostgreSQL Tables |
|---|---|
| Identity & Access | user, role, permission, user_group, auth_credential |
| System & Environment | organization, environment_configuration, app, app_metadata, onboarding |
| Triggers & Logic | api_trigger, record_trigger, function, schedule_trigger, schedule_trigger_run, schedule_trigger_setting, scheduled_item |
| UI & Layout | app_page, dashboard, report, list_filter, template, guide |
| File Storage | file, related_file |
| Notifications | notification, notification_setting, notification_subscriber |
| Commercial / Billing | app_product, app_product_price, integrated_app |
| Metadata & Categorization | tag, log |
5. API Reference Summary
All routes maintain exact compatibility with the Valstorm frontend (packages/components, apps/workspace, and apps/valstorm-desktop):
Authentication (/auth)
POST /auth/register- Create a new user, register an organization, and provision a dedicated database.POST /auth/login- Authenticate with email/password and obtain a JWT bearer token.GET /auth/me- Retrieve authenticated user profile and organization scoping.
Object & Schema DDL (/schema)
POST /schema/object- Define a new custom object; compiles and executesCREATE TABLE.POST /schema/field- Add a field to an existing object; compiles and executesALTER TABLE ... ADD COLUMN.GET /schema/object- Retrieve all registered schemas and property definitions for the tenant.
Record CRUD (/records/c/{object_name})
POST /records/c/{object_name}- Batch create records with Base62 ID generation (tick_...,con_...).PUT /records/c/{object_name}- Batch update records by ID.DELETE /records/c/{object_name}- Batch delete records by ID list ({"ids": [...]}).GET /records/c/{object_name}- Paginated list of records (?limit=50&offset=0).
Native SQL Queries (/query)
POST /query/sql- Execute parameterized ANSI SQL directly on PostgreSQL:
``json { "query": "SELECT id, name, priority FROM ticket WHERE is_closed = false ORDER BY created_date DESC", "limit": 50 } ``
Tenant Sandboxes (/sandbox)
POST /sandbox/create- Provision a dedicated sandbox database (CREATE DATABASE {prod_org}_s_{name}).DELETE /sandbox/delete- Cleanly drop and terminate active connections for a sandbox database.
6. Code Quality, Security & Compliance Audits
The open-api service enforces an automated multi-layer quality and security verification pipeline before any code is approved for deployment.
Code Quality & Linting Checklist (Ruff)
Open Valstorm uses Ruff for high-performance Python 3.13 linting, import sorting (isort), and formatting:
# Check code style, unused imports, and syntax rules
uv run ruff check .
# Automatically apply safe fixes and organize imports
uv run ruff check --fix .
# Verify formatting without mutating files
uv run ruff format --check .
# Format all files to PEP 8 standards
uv run ruff format .Security & Vulnerability Audits
Run individual security scanners or the unified CI/CD audit script:
# 1. Static Application Security Testing (SAST) via Bandit
uv run bandit -c .bandit.yaml -r app
# 2. Software Supply Chain Vulnerability Scan (SCA) via pip-audit
uv run pip-audit
# 3. Secret Leak Detection via Gitleaks
gitleaks git --log-opts="HEAD~10..HEAD" --verbose
# 4. Dependency License Compliance Audit (0 copyleft/GPL contamination)
uv run pip-licenses --summary
# 5. Full 8-Gate Security & Quality CI/CD Pipeline
./scripting/cicd/security_audit.sh7. Python Sandbox & AST Security Gatekeeper
Server-side Python functions and record triggers run inside an AST-enforced, asynchronous sandbox (apps/open-api/app/core/sandbox/):
- Whitelisted Standard Modules:
math,datetime,re,orjson,uuid,decimal,random,typing. - Performance Enforcement (
orjson): Importing the standardjsonlibrary is actively intercepted by the AST gatekeeper, throwing aSecurityViolationErrorinstructing developers to useorjsonfor high-throughput serialization. - Prohibited Built-ins & Calls:
eval(),exec(),open(),compile(),globals(),locals(),vars(),__import__(),breakpoint(). - Introspection & Escape Armor: Access to dunder attributes (
__class__,__subclasses__,__bases__,__mro__,__globals__,__dict__) and dynamic dunder access viagetattr/setattrare strictly rejected at parse time. - Resource Constraints:
- Script Execution Timeout:
5.0smaximum wall clock limit (CodeExecutionTimeout/ HTTP 408). - Trigger Recursion Guard: Maximum depth of 3 nested triggers (
TriggerRecursionError/ HTTP 400).
8. Automated Testing & Verification
Run the full automated test suite using pytest:
uv run pytest -vTest Suite Directory (apps/open-api/tests/)
The test suite consists of 50 integration and unit tests across 19 specialized modules:
| Test Module | Coverage Domain |
|---|---|
tests/test_triggers_and_sandbox.py | AST security gatekeeper, orjson enforcement, Before/After record triggers, recursion prevention. |
tests/test_platform_context.py | Direct SDK and REST API route parity for records, query, schemas, files/vfs, apps, sandboxes. |
tests/test_query_service.py | SQL AST validation, SELECT-only enforcement, LIMIT capping, and injection sanitization. |
tests/test_query_hydration.py | Relational lookup hydration (hydrate: true/false) and reverse resolution. |
tests/test_phase3_security_and_sql.py | Object-Level Security (OLS), Field-Level Security (FLS), Row-Level Security (RLS), and SQL macro rewriting. |
tests/test_iteration_a_security_gaps.py | Canonical prefix mapping, schema validation rules, OAuth2 refresh tokens, and OLS/RLS gates. |
tests/test_enterprise_licensing.py | Multi-tier enterprise licensing, license activation, and dynamic feature flag toggles. |
tests/test_ddl_compiler.py | Schema definition to PostgreSQL DDL compilation (CREATE TABLE, ALTER TABLE, DROP COLUMN). |
tests/test_schema_sync_reflection.py | Dual-system schema synchronization, PostgreSQL drift detection, and prefix utilities. |
tests/test_vfs_and_files.py | Virtual File Service (VFS), Knowledge Vault hierarchy, file revisions, and rollback. |
tests/test_cud_notifications.py | CUD mutation event publishing, Valkey pub/sub, and WebSocket distribution. |
tests/test_graphql.py | Dynamic GraphQL schema generation, Strawberry resolvers, and dataloaders. |
tests/test_graphql_page_record_errors.py | Complex type handling and field error boundaries in GraphQL execution. |
tests/test_app_deployment.py | Application marketplace installation, bundle deployment, and subscriber tracking. |
tests/test_bootstrap_v2.py | Full V2 bootstrap lifecycle and org provisioning. |
tests/test_seeder.py | End-to-end default core bootstrap seeding (33 foundational Base App tables). |
tests/test_generic_seeder.py | Custom non-proprietary org seeding and Universal Support User verification. |
tests/test_e2e_seeded_api.py | Production v1 API contract verification against seeded live tenant data. |
tests/test_api_endpoints.py | Health endpoints, OpenAPI schema generation, and service readiness. |
9. Resetting & Wiping Your Local Instance (Fresh Admin & Client Setup)
To completely wipe your local Open Valstorm instance—including the central valstorm_directory database, all isolated per-tenant PostgreSQL databases (org_*), Valkey/Redis cache, and local VFS storage—and bootstrap a fresh Admin and Client workspace from the ground up, follow these steps:
Step 1: Wipe the Databases, Volumes & Local Storage
Because Open Valstorm dynamically creates a dedicated PostgreSQL database for each tenant (org_awmq8vsogmavwkw9, org_dsnpmrjs1zkkdyq2, sandboxes, etc.) inside the open_pgdata Docker volume, tear down the compose stack with -v (remove volumes) from the monorepo root:
# Tear down containers and delete the open_pgdata PostgreSQL volume
docker compose -f docker-compose.open.yaml down -v
# Optional: Remove any local VFS files written to disk during previous test runs
rm -rf apps/open-api/storageStep 2: Start Fresh PostgreSQL & Valkey Containers
Choose whether to run only the database/cache in Docker (with the FastAPI server running on your host via uv) or the entire stack in Docker:
- Option 1 — Run DB/Cache in Docker & API on Host (Recommended for local dev):
``bash docker compose -f docker-compose.open.yaml up -d open-postgres open-valkey ``
- Option 2 — Run the Full Stack (Postgres, Valkey, Open-API, Open-Worker) in Docker:
``bash docker compose -f docker-compose.open.yaml up -d ``
Step 3: Seed a Fresh Admin Org, Support User & Client Workspace
Navigate to apps/open-api and run app/seed.py. This initializes valstorm_directory, provisions the dedicated PostgreSQL databases for both the Admin and Client organizations, compiles the foundational Base App tables/schemas, attaches the Universal Support User, and flushes Valkey (FLUSHDB):
cd apps/open-api
uv syncChoose one of the three seeding modes:
Option A: Default Valstorm Seed (Fastest)
uv run python app/seed.py| Role | Password | Organization ID | Dedicated Postgres DB | |
|---|---|---|---|---|
| Super Admin | [email protected] | valstorm_admin_password | org_AwmQ8vSogMavWkw9 | org_awmq8vsogmavwkw9 |
| Support User | [email protected] | valstorm_support_password | (Attached to all orgs) | (Both Admin & Client DBs) |
| Client Admin | [email protected] | valstorm_client_password | org_dSnPMRjS1ZkkdYQ2 | org_dsnpmrjs1zkkdyq2 |
Option B: Interactive Setup Wizard (Custom Names, Emails & Passwords)
uv run python app/seed.py --interactiveOption C: Custom CLI Flags
uv run python app/seed.py \
--admin-org-name 'System Administration' \
--admin-user-name 'Super Admin' \
--admin-email '[email protected]' \
--admin-password 'AdminSecret123!' \
--support-email '[email protected]' \
--support-password 'SupportSecret123!' \
--client-org-name 'Test Client Org' \
--client-user-name 'Client Tester' \
--client-email '[email protected]' \
--client-password 'ClientSecret123!'Step 4: Start the Open API Server
If you selected Option 1 in Step 2 (running the API on your host machine):
cd apps/open-api
uv run uvicorn app.main:app --port 8010 --reload- API Base URL:
http://localhost:8010 - Interactive Swagger Docs:
http://localhost:8010/docs
Step 5: Migrating Existing MongoDB Tenants to PostgreSQL (1-Click ETL)
To migrate existing Valstorm organizations from MongoDB (apps/api + apps/worker-go) into dedicated Open Valstorm PostgreSQL databases (apps/open-api + apps/open-worker):
# Migrate a single tenant organization (with row-count + checksum verification)
uv run --project scripting python scripting/database-admin/migrate_mongo_to_postgres.py --org org_dSnPMRjS1ZkkdYQ2 --verify
# Migrate all tenant organizations discovered in MongoDB
uv run --project scripting python scripting/database-admin/migrate_mongo_to_postgres.py --all-orgs --verify
# Clean re-migration (drops & recreates target tenant databases before loading)
uv run --project scripting python scripting/database-admin/migrate_mongo_to_postgres.py --all-orgs --flush --verifyWhat the migration pipeline automatically handles:
- Global Directory (
valstorm_directory): Syncsorganization,users,app(filtering deprecated monolithic apps converted to/plugins), andexternal_account_routing(Twilio, Telnyx, Stripe, OAuth). - Schema & Plugin DDL Compilation: Compiles all MongoDB
schemas, merges foundationalbase_app.json+ built-in plugin schemas (user_ai_memory,user_asset_affinity,personal_access_token), hydrates picklist/multi-select options fromtag, and guarantees zero prefix collisions andSchemaService.get_sync_status() == True. - Encrypted Credentials & BYOK: Decrypts legacy AES-256-CBC
auth_credentialandenvironment_configurationenvelopes (including double-encrypted or Python dict repr payloads) and re-encrypts them as RFC 8259 JSON under the Open Valstorm encryption key. - AI Working Memory & VFS Paths: Consolidates
user_asset_affinity(uaaf_) records intouser_ai_memory.pinned_assets(uaim_) forvalstorm-plugin-aiand computes hierarchicalvault_pathsacrossvaultandfile.
