Skip to content

Tenancy

Internals of the Tenancy domain. For the public API, see Tenancy API.

The domain lives in domain/tenancy in CoreAPI. It holds two independent configuration surfaces that share a package and do not reference each other:

  • The legacy ticketing general record (routes under /api/settings), handled in domain/tenancy/routes/routes_ticketing.go.
  • The platform hierarchy of organizations, workspaces, teams, roles and integration profiles (routes under /api/v1/tenancy), handled in domain/tenancy/routes/routes.go.

Related pages: Auth, identity and RBAC, Identity internals, Testing email integrations, Authentication internals.

Organizations

An organization is the top-level tenant boundary. Organizations are split across two systems:

  • AuthAPI owns the Zitadel org, the user's login identity, and the invite and password-reset magic links. company_code, hosting_type and license keys are owned entirely by AuthAPI. CoreAPI proxies them in its responses and does not persist them.
  • CoreAPI owns the organizations, organization_members and org_app_access tables that this domain manages.

A special platform organization (00000000-0000-0000-0000-000000000001) represents PlayTelly staff. Platform-scope roles (PLATFORM_OWNER, PLATFORM_ADMIN and similar) are assigned there. Its app access is hardcoded to all apps, and PUT .../app-access returns 403 for it.

graph LR
    Applicant["Self-signup applicant (public)"]
    AdminPortal["Platform / org admin portal"]
    AuthAPI["AuthAPI (Zitadel + auth slice,\ncompany code + licensing)"]
    CoreAPI["CoreAPI (tenancy: orgs)"]
    CoreDB["CoreAPI DB\n(organizations, organization_members,\norg_app_access, email_verification_codes)"]
    Redis["Redis\n(token blocklist)"]
    Zoho["Zoho Mail\n(verification + welcome emails)"]

    Applicant -->|verify-email, self-signup| CoreAPI
    AdminPortal -->|POST /tenancy/organizations| CoreAPI
    AdminPortal -->|invitations, roles, app-access, status| CoreAPI
    CoreAPI -->|create org + admin/invited user,\nhosting_type + company_code| AuthAPI
    CoreAPI --> CoreDB
    CoreAPI -->|blocklist on role/status change| Redis
    CoreAPI -->|verification code, welcome email| Zoho
    AuthAPI -->|internal sync: unknown org/user| CoreAPI

CoreAPI never talks to Zitadel directly. Every identity operation (creating the org, creating or inviting a user, issuing invite and password-reset magic links) is delegated to AuthAPI over an internal, PSK-signed HTTP call, and CoreAPI mirrors the result into its own tables so org, workspace and app-access queries stay local. When AuthAPI meets an org or user CoreAPI has no row for (for example during self-signup) it calls back into the internal routes below.

Data model

erDiagram
    Organization {
        string id
        string name
        string legalName
        string website
        string timezone
        string status
        string tierId
        string defaultAppId
        timestamp trialExpiresAt
    }

    OrganizationMember {
        string organizationId
        string userId
        string roleId
        string role
    }

    User {
        string id
        string organizationId
        string email
        string firstName
        string lastName
        string username
        timestamp onboardingCompletedAt
    }

    Role {
        string id
        string organizationId "null for system roles"
        string scope
        string name
        string description
        bool isSystem
    }

    RolePermission {
        string roleId
        string permission
    }

    OrgAppAccess {
        string organizationId
        string appId
    }

    EmailVerificationCode {
        string id
        string email
        string codeHash
        timestamp expiresAt
        timestamp verifiedAt
    }

    Organization ||--o{ OrganizationMember : has
    User ||--o{ OrganizationMember : "is a"
    OrganizationMember }o--|| Role : "role_id references"
    Role ||--o{ RolePermission : grants
    Organization ||--o{ OrgAppAccess : "app access"
    Organization ||--o{ Role : "owns (custom roles only)"

roles is one table shared across scopes (platform, organization, workspace). System roles (is_system = true) have organization_id = null and are assignable everywhere. Custom roles always carry the calling org's ID and are unique per (organization_id, scope, name). PATCH .../users/:userId/role accepts a system organization-scope role or a custom organization-scope role owned by that org. email_verification_codes is keyed by email, not by user or org, because self-signup applicants have no account yet. It is used once by the self-signup flow.

Behavior details

  • Self-signup stages the org as pending with a row in the applications table (reference format APL- plus 16 Crockford base32 characters, a bearer secret for the public status page, rate limited per IP). The org's app access is granted immediately. No Zitadel org or admin user is created until a platform admin approves, or an approval token approves it at sign-up. The email-verification record is single-use and valid 30 minutes after confirmation. Codes are valid 10 minutes, confirmation links 60 minutes.
  • Approval of a pending org (PUT .../status to active) creates the admin user and ORG_ADMIN membership from AuthAPI's response (which carries a one-time temporary password), creates the Default workspace, and emails the admin the login details. The email is best-effort.
  • Rejection deletes the org (freeing its company code) and keeps the application row.
  • Invitations are magic links. AuthAPI creates the user in invited state with a random internal password and hands CoreAPI a one-time link token. CoreAPI sends the link through the org's user_invite email profile. If the org has no profile mapped to user_invite or fallback, the call fails with 400 before AuthAPI is called. Reinviting invalidates the earlier link.
  • Role and status changes blocklist the target user's tokens in Redis for the access-token lifetime so the next JWT carries the new role. The blocklist TTL comes from the AuthAPI access-token expiry setting.
  • Org deletion removes CoreAPI data first, then asks AuthAPI to delete its slice. An AuthAPI failure is logged and not returned.
  • Trial expiry is a daily scheduler (runTrialExpiryScheduler) that disables orgs whose trial_expires_at has passed.
  • Approval tokens are pre-approvals for a group of sign-ups (an event, a partner, a campaign). They are staff-only routes under /api/v1/tenancy/organizations/approval-tokens.

Internal routes (PSK-protected, called by AuthAPI)

Mounted at /api/v1/internal and gated by RequireInternalToken(), a pre-shared key in the X-Internal-Token header. The key is kept in the service's secret store and is not repeated here.

Route Purpose
POST /api/v1/internal/organizations Upsert an org (ON CONFLICT DO NOTHING, safe to retry). Body {org_id, name}. Returns 201.
POST /api/v1/internal/users Create the local users row and an ORG_MEMBER membership in one transaction. Body {user_id, org_id, email, first_name, last_name, username}.
GET /api/v1/internal/users/:userId/roles Called at login so AuthAPI can embed the org role in the JWT's single org claim. Returns {org_role, app_roles: []}, with an empty role when the user has no row. It reads organization_members with LIMIT 1 and no org_id filter. That is fine while membership is 1:1 and would need an org_id parameter otherwise.
PUT /api/v1/internal/users/:userId/roles Set a user's org role directly. Skips the self-role-change and system-role checks of the public PATCH. Body {org_id, role}. 404 if there is no membership.
POST /api/v1/internal/email/password-reset Send a forgot-password email through the org's password_reset email profile. Body {org_id, email, reset_link, expiry_minutes}. 204 on success, 422 when no active profile is mapped.
GET /api/v1/internal/legacy-scope Counters of the legacy header-scope guard.

Workspaces

A workspace is a sub-unit inside an organization. Workspaces are entirely CoreAPI-local: unlike organization creation there is no AuthAPI round trip. A user must already be an org member to be added to a workspace, and org membership alone grants no workspace access.

erDiagram
    Workspace {
        string id
        string organizationId
        string name
        string workspaceSlug
        string description
        string workspaceType
        string createdBy
    }

    WorkspaceMember {
        string workspaceId
        string userId
        string role
    }

    WorkspaceAppAccess {
        string workspaceId
        string appId
    }

    WorkspaceLocation {
        string workspaceId
        string locationId
    }

    WorkspaceChannel {
        string workspaceId
        string channelId
    }

    Organization ||--o{ Workspace : contains
    Workspace ||--o{ WorkspaceMember : has
    Workspace ||--o{ WorkspaceAppAccess : "app access"
    Workspace ||--o{ WorkspaceLocation : "spaces"
    Workspace ||--o{ WorkspaceChannel : channels
  • Workspace roles rank WORKSPACE_ADMIN > WORKSPACE_MEMBER > VIEWER. Custom workspace-scope roles of the org are also assignable.
  • Deleting a workspace deletes rows in workspace_members, team_workspace_roles, workspace_app_access, workspace_channels, workspace_locations and workspace_settings in one transaction.
  • The workspace name rule is the regex ^[a-zA-Z0-9]+(?: [a-zA-Z0-9]+)*$. Slugs are lowercased with non-alphanumerics collapsed to single dashes (Slugify), and the slug is unique per org.
  • POST .../locations and .../channels insert with ON CONFLICT DO NOTHING, so a repeat is a no-op. They do not check that the location or channel exists in the org.

Default workspace creation

Every org gets a workspace named Default (slug default, type Custom) as a side effect, not through an explicit API call. It carries the org's current app access and makes the org's new admin its WORKSPACE_ADMIN. It is fired from two places:

  1. POST /tenancy/organizations (direct creation), right after the admin user is created, for cloud orgs only. on_prem orgs never get one because they have no local admin user or app access to seed it with.
  2. PUT /tenancy/organizations/:orgId/status on the pending to active transition of a self-signup org, using the app access as granted at approval time.

There is no flag to skip it. Creation is best-effort: it runs the same validation as a manual POST .../workspaces, so it can fail, and a failure is logged without failing the surrounding request.

Teams

A team is an org-scoped group of users that holds one role on a workspace as a unit. Teams are CoreAPI-local like workspaces.

erDiagram
    Team {
        string id
        string organizationId
        string name
        string description
        string leadUserId "unused by the API"
    }

    TeamMember {
        string teamId
        string userId
    }

    TeamWorkspaceRole {
        string teamId
        string workspaceId
        string roleId
    }

    Organization ||--o{ Team : owns
    Team ||--o{ TeamMember : has
    Team ||--o{ TeamWorkspaceRole : "holds role on"
    Workspace ||--o{ TeamWorkspaceRole : "role granted by"
  • (team_id, workspace_id) is the primary key of team_workspace_roles, so a team holds at most one role per workspace.
  • Team.LeadUserID is a column that no endpoint exposes or sets.
  • WorkspaceHasPermission unions direct workspace_members rows with team-derived roles (team_workspace_roles joined through team_members) and takes the higher-weight role if both somehow apply. Write-time checks (adding a direct member, adding a team member, granting a team a role) are meant to keep the two paths from overlapping. ORG_OWNER and ORG_ADMIN always pass the workspace check.
  • Team names follow the same regex as workspace names.

General settings (ticketing)

The general table holds ticketing tenant settings: site branding, legal content pages in three languages, third-party API credentials and email server configuration. It used to be a single global row. Since 2026-09-14 it is one row per workspace, created lazily with zero-value defaults the first time a workspace's settings are read or written.

graph LR
    CustomerApp["Customer app (public reads)"]
    AdminPortal["Admin portal (workspace:general-settings:manage writes)"]
    CoreAPI["CoreAPI (tenancy handlers)"]
    DB["Ticketing DB\n(general: one row per workspace)"]

    CustomerApp -->|GET /api/settings/privacyPolicy etc.| CoreAPI
    AdminPortal -->|GET and PUT /api/settings/:workspaceId/general| CoreAPI
    AdminPortal -->|PUT /api/settings/:workspaceId/integration| CoreAPI
    CoreAPI --> DB
  • The public content GETs resolve through the single pinned workspace from the SPATIO_TICKETING_WORKSPACE_ID environment variable, because the customer app has no per-request workspace concept.
  • The general record also holds integration credentials (Zoo API, JohorPay gateway, SMTP). GET .../general returns them in clear text, which is why the route is gated by workspace:general-settings:manage. The newer per-organization integration profiles replace this record for new work (see below).
  • Content pages are stored as raw HTML and served verbatim.
erDiagram
    General {
        uint generalId
        string organizationId
        string workspaceId
        string contactEmail
        string timeZone
        string envKey
        string envValue
        string privacyPolicyContentEn
        string privacyPolicyContentBm
        string privacyPolicyContentCn
        string termsOfPurchaseContentEn
        string termsOfServiceContentEn
        string faqContentEn
        string contactUsContentEn
        string refundPolicyContentEn
        string zooApiBaseUrl
        string jpGatewayUrl
        string emailHost
        int emailPort
    }

Integration profiles

The email, payment and POS profile handlers, services and repositories live in domain/tenancy. They are org-owned, can be narrowed to one workspace, and store credentials encrypted with AES-256-GCM using a key from the secrets-encryption setting. Credentials never come back in a response. The public reference is Integration profiles. For a hands-on test with a sandbox, see Testing email integrations.

Notes from reading the code:

  • Three .../:profileId/credentials routes (email, payment, POS) return decrypted credentials. They are only mounted when COREAPI_ALLOW_SECRET_REVEAL=true and the service logs a warning at start. Never enable this in production.
  • Only user_invite, password_reset and ticket_delivery or fallback usage types are resolved by any code path. order_confirmation can be assigned and stored but nothing sends through it.
  • A missing secrets-encryption key makes profile create return 500 with a message that names the environment variable. That leaks an env var name to clients.
  • Payment and POS test-connection return 502 with the raw error text for anything unmapped, including decryption failures.
  • Payment and POS create accept any workspaceId: it is a text column and nothing checks it belongs to the org.
  • Email PATCH with isActive: false is allowed while the profile is mapped or linked, although a code comment says mapped profiles cannot be deactivated. Sends then fail and do not fall through to fallback.
  • Email profiles have a WorkspaceID column that no API can set.
  • test-send and validate do not check to. A bad address surfaces as a 502 from the provider.
  • The name-uniqueness check runs before the insert, so two concurrent creates could reach the database constraint and return 500. Not verified.
  • 400 bodies are inconsistent. The payment ticket-group routes return {"success": false, "error": "Bad Request"} for a bad ticketGroupId, while the email and POS ones return {"error": "invalid ticketGroupId"}. POS create returns {"error": "name and provider are required"} while email and payment create return the generic body.
  • DELETE on a ticket group's email or POS profile returns 404 with a misleading message when nothing was linked. DELETE on a usage mapping returns 200 even when nothing was mapped.

Routes in the code that the public reference does not cover

Routes Why
POST, GET .../organizations/approval-tokens, POST .../approval-tokens/:id/revoke Platform staff tooling for pre-approved sign-ups.
Venue and place routes (venues.Register) and hotel outlet and menu routes (hotelinfo.RegisterOrgRoutes) mounted on the org group Owned by the spatial and concierge domains.
The three .../credentials routes Development only (see above).
Everything under /api/v1/internal Service to service.

Change history

Date Change
2026-06-23 Initial tenancy domain documentation.
2026-07-22 Organizations and Workspaces pages added, with OpenAPI specs.
2026-08-07 Documentation audit. Org creation takes hosting_type and a required company_code. Self-signup with email verification and deferred provisioning. Platform org list and status endpoints. Custom roles can be updated and deleted, and a role's members listed. The permissions catalog endpoint. Permission names namespaced (org:users:manage, platform:org:create). Default workspace auto-created. Teams added. The JWT claim documentation was corrected from orgs[] to a single org object.
2026-08-13 Invitations rewritten to send a magic link by email instead of returning a code.
2026-09-14 general became one row per workspace. Admin writes need workspace:general-settings:manage.
2026-09-18 Email profile endpoints documented. Payment and POS profile endpoints added.
2026-09-24 The older Tenant domain page was marked outdated.