diff --git a/clients/python/README.md b/clients/python/README.md index 8c0b211a5..5dda26e09 100644 --- a/clients/python/README.md +++ b/clients/python/README.md @@ -249,7 +249,7 @@ treat differently from an absent field, so pass it only when you mean it. | --- | --- | | Session | `read_current_session`, `revoke_current_session` | | Credentials | `list_personal_api_keys`, `create_personal_api_key`, `replace_personal_api_key`, `revoke_personal_api_key` | -| Organizations | `list_organization_api_keys`, `list_organizations`, `create_organization`, `read_organization`, `update_organization`, `list_organization_members`, `put_organization_member`, `remove_organization_member`, `list_service_users`, `create_service_user`, `update_service_user` | +| Organizations | `list_organization_api_keys`, `list_organizations`, `enroll_organization`, `create_organization`, `read_organization`, `update_organization`, `list_organization_members`, `put_organization_member`, `remove_organization_member`, `list_service_users`, `create_service_user`, `update_service_user` | | Service-Users | `list_service_user_api_keys`, `create_service_user_api_key`, `replace_service_user_api_key`, `put_service_user_api_key`, `revoke_service_user_api_key` | | Settings | `list_platform_settings`, `put_platform_setting` | | Universes | `adopt_universe`, `create_universe`, `update_universe`, `list_universe_grants`, `put_universe_grant`, `remove_universe_grant`, `read_platform_universe`, `read_universe_access_policy`, `put_universe_access_policy` | diff --git a/clients/python/src/lightspeed_ai/_generated.py b/clients/python/src/lightspeed_ai/_generated.py index fd527bcb2..cc0dcae64 100644 --- a/clients/python/src/lightspeed_ai/_generated.py +++ b/clients/python/src/lightspeed_ai/_generated.py @@ -921,6 +921,9 @@ async def call(self, method: Literal['platform/settings/put'], params: Platform. async def call(self, method: Literal['platform/organizations/list'], params: Platform.PlatformOrganizationsListParams | None = None, *, headers: HeadersInput | None = None) -> Platform.PlatformOrganizationsListResult: ... @overload + async def call(self, method: Literal['platform/organizations/enroll'], params: Platform.PlatformOrganizationsEnrollParams, + *, headers: HeadersInput | None = None) -> Platform.PlatformOrganizationsEnrollResult: ... + @overload async def call(self, method: Literal['platform/organizations/create'], params: Platform.PlatformOrganizationsCreateParams, *, headers: HeadersInput | None = None) -> Platform.PlatformOrganizationsCreateResult: ... @overload diff --git a/clients/python/src/lightspeed_ai/_platform.py b/clients/python/src/lightspeed_ai/_platform.py index de8aee758..7b421846e 100644 --- a/clients/python/src/lightspeed_ai/_platform.py +++ b/clients/python/src/lightspeed_ai/_platform.py @@ -50,6 +50,9 @@ 'platform/organizations/list': {'method': 'GET', 'path': '/api/v1/platform/organizations', 'helper': {'name': 'listOrganizations'}}, + 'platform/organizations/enroll': {'method': 'POST', + 'path': '/api/v1/organizations/enroll', + 'helper': {'name': 'enrollOrganization'}}, 'platform/organizations/create': {'method': 'POST', 'path': '/api/v1/platform/organizations', 'helper': {'name': 'createOrganization'}}, @@ -158,6 +161,9 @@ async def put_platform_setting(self, params: Api.PlatformSettingsPutParams, *, h async def list_organizations(self, params: Api.PlatformOrganizationsListParams | None = None, *, headers: HeadersInput | None = None) -> Api.PlatformOrganizationsListResult: return cast(Api.PlatformOrganizationsListResult, await self._invoke('platform/organizations/list', dict(params or {}), headers)) + async def enroll_organization(self, params: Api.PlatformOrganizationsEnrollParams, *, headers: HeadersInput | None = None) -> Api.PlatformOrganizationsEnrollResult: + return cast(Api.PlatformOrganizationsEnrollResult, await self._invoke('platform/organizations/enroll', dict(params or {}), headers)) + async def create_organization(self, params: Api.PlatformOrganizationsCreateParams, *, headers: HeadersInput | None = None) -> Api.PlatformOrganizationsCreateResult: return cast(Api.PlatformOrganizationsCreateResult, await self._invoke('platform/organizations/create', dict(params or {}), headers)) diff --git a/clients/python/src/lightspeed_ai/platform_types.py b/clients/python/src/lightspeed_ai/platform_types.py index f54002fbc..342fc1d54 100644 --- a/clients/python/src/lightspeed_ai/platform_types.py +++ b/clients/python/src/lightspeed_ai/platform_types.py @@ -616,6 +616,19 @@ class PlatformOrganizationsListResult(TypedDict): canCreate: bool +class PlatformOrganizationsEnrollParams(TypedDict): + handle: str + name: str + + +class PlatformOrganizationsEnrollResult(TypedDict): + organizationId: str + enrolled: bool + """ + True when this request created the organization; false when the workload already belongs to it. + """ + + class PlatformOrganizationsCreateParams(TypedDict): name: str handle: str diff --git a/clients/typescript/README.md b/clients/typescript/README.md index b05ef08ac..f036f212e 100644 --- a/clients/typescript/README.md +++ b/clients/typescript/README.md @@ -249,7 +249,7 @@ Native Platform helpers use `client.platform` and typed parameter objects: | settings | `listPlatformSettings`, `putPlatformSetting` | | credentials | `listPersonalApiKeys`, `createPersonalApiKey`, `replacePersonalApiKey`, `revokePersonalApiKey` | | service-users | `listServiceUserApiKeys`, `createServiceUserApiKey`, `putServiceUserApiKey`, `replaceServiceUserApiKey`, `revokeServiceUserApiKey` | -| organizations | `listOrganizations`, `createOrganization`, `readOrganization`, `updateOrganization`, `listOrganizationMembers`, `putOrganizationMember`, `removeOrganizationMember`, `listOrganizationApiKeys`, `listServiceUsers`, `createServiceUser`, `updateServiceUser` | +| organizations | `listOrganizations`, `enrollOrganization`, `createOrganization`, `readOrganization`, `updateOrganization`, `listOrganizationMembers`, `putOrganizationMember`, `removeOrganizationMember`, `listOrganizationApiKeys`, `listServiceUsers`, `createServiceUser`, `updateServiceUser` | | universes | `adoptUniverse`, `createUniverse`, `readPlatformUniverse`, `updateUniverse`, `listUniverseGrants`, `putUniverseGrant`, `removeUniverseGrant`, `readUniverseAccessPolicy`, `putUniverseAccessPolicy` | Additional conveniences include `awaitRun`, `readBlobText`, `putBlob`, diff --git a/clients/typescript/schema/platform-http.json b/clients/typescript/schema/platform-http.json index ac9a5adf4..e4d4fbaad 100644 --- a/clients/typescript/schema/platform-http.json +++ b/clients/typescript/schema/platform-http.json @@ -150,6 +150,16 @@ "params": "PlatformOrganizationsListParams", "result": "PlatformOrganizationsListResult" }, + { + "operationId": "platform/organizations/enroll", + "helper": { + "name": "enrollOrganization" + }, + "method": "POST", + "path": "/api/v1/organizations/enroll", + "params": "PlatformOrganizationsEnrollParams", + "result": "PlatformOrganizationsEnrollResult" + }, { "operationId": "platform/organizations/create", "helper": { diff --git a/clients/typescript/schema/platform.schema.json b/clients/typescript/schema/platform.schema.json index da1780614..25bdd4ce6 100644 --- a/clients/typescript/schema/platform.schema.json +++ b/clients/typescript/schema/platform.schema.json @@ -2044,6 +2044,43 @@ ], "additionalProperties": false }, + "PlatformOrganizationsEnrollParams": { + "type": "object", + "properties": { + "handle": { + "type": "string", + "pattern": "^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 120 + } + }, + "required": [ + "handle", + "name" + ], + "additionalProperties": false + }, + "PlatformOrganizationsEnrollResult": { + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "minLength": 1 + }, + "enrolled": { + "type": "boolean", + "description": "True when this request created the organization; false when the workload already belongs to it." + } + }, + "required": [ + "organizationId", + "enrolled" + ], + "additionalProperties": false + }, "PlatformOrganizationsCreateParams": { "type": "object", "properties": { diff --git a/clients/typescript/src/generated/platform-helpers.ts b/clients/typescript/src/generated/platform-helpers.ts index fce98422e..5d9e4878d 100644 --- a/clients/typescript/src/generated/platform-helpers.ts +++ b/clients/typescript/src/generated/platform-helpers.ts @@ -18,6 +18,7 @@ export const PLATFORM_CLIENT_HELPERS = { "listPlatformSettings": "platform/settings/list", "putPlatformSetting": "platform/settings/put", "listOrganizations": "platform/organizations/list", + "enrollOrganization": "platform/organizations/enroll", "createOrganization": "platform/organizations/create", "readOrganization": "platform/organizations/read", "updateOrganization": "platform/organizations/update", @@ -84,6 +85,9 @@ export class PlatformHelpers { listOrganizations(params: PlatformOperationParams<"platform/organizations/list"> = {}, options: CallOptions = {}): Promise> { return this.client.call("platform/organizations/list", params, options); } + enrollOrganization(params: PlatformOperationParams<"platform/organizations/enroll">, options: CallOptions = {}): Promise> { + return this.client.call("platform/organizations/enroll", params, options); + } createOrganization(params: PlatformOperationParams<"platform/organizations/create">, options: CallOptions = {}): Promise> { return this.client.call("platform/organizations/create", params, options); } diff --git a/clients/typescript/src/generated/platform-types.ts b/clients/typescript/src/generated/platform-types.ts index 3e62cdfd1..ff5b5f53a 100644 --- a/clients/typescript/src/generated/platform-types.ts +++ b/clients/typescript/src/generated/platform-types.ts @@ -739,6 +739,25 @@ export interface PlatformOrganizationsListResult { }[]; canCreate: boolean; } +/** + * This interface was referenced by `PlatformApi`'s JSON-Schema + * via the `definition` "PlatformOrganizationsEnrollParams". + */ +export interface PlatformOrganizationsEnrollParams { + handle: string; + name: string; +} +/** + * This interface was referenced by `PlatformApi`'s JSON-Schema + * via the `definition` "PlatformOrganizationsEnrollResult". + */ +export interface PlatformOrganizationsEnrollResult { + organizationId: string; + /** + * True when this request created the organization; false when the workload already belongs to it. + */ + enrolled: boolean; +} /** * This interface was referenced by `PlatformApi`'s JSON-Schema * via the `definition` "PlatformOrganizationsCreateParams". diff --git a/clients/typescript/src/generated/platform.ts b/clients/typescript/src/generated/platform.ts index 4dab3b328..85fdd7101 100644 --- a/clients/typescript/src/generated/platform.ts +++ b/clients/typescript/src/generated/platform.ts @@ -16,6 +16,7 @@ export interface PlatformOperationMap { "platform/settings/list": { params: T.PlatformSettingsListParams; result: T.PlatformSettingsListResult }; "platform/settings/put": { params: T.PlatformSettingsPutParams; result: T.PlatformSettingsPutResult }; "platform/organizations/list": { params: T.PlatformOrganizationsListParams; result: T.PlatformOrganizationsListResult }; + "platform/organizations/enroll": { params: T.PlatformOrganizationsEnrollParams; result: T.PlatformOrganizationsEnrollResult }; "platform/organizations/create": { params: T.PlatformOrganizationsCreateParams; result: T.PlatformOrganizationsCreateResult }; "platform/organizations/read": { params: T.PlatformOrganizationsReadParams; result: T.PlatformOrganizationsReadResult }; "platform/organizations/update": { params: T.PlatformOrganizationsUpdateParams; result: T.PlatformOrganizationsUpdateResult }; @@ -99,6 +100,10 @@ export const PLATFORM_OPERATIONS = { "method": "GET", "path": "/api/v1/platform/organizations" }, + "platform/organizations/enroll": { + "method": "POST", + "path": "/api/v1/organizations/enroll" + }, "platform/organizations/create": { "method": "POST", "path": "/api/v1/platform/organizations" diff --git a/docs/documentation/deployment/configuration.md b/docs/documentation/deployment/configuration.md index c99405191..c3a98a6a5 100644 --- a/docs/documentation/deployment/configuration.md +++ b/docs/documentation/deployment/configuration.md @@ -60,6 +60,72 @@ and review [API keys and service access](../access-and-security/api-keys-and-ser The [Platform environment settings](../reference/environment-variables.md#platform-backend) cover sign-in, session lifetimes, and API key expiry. +## Enroll organizations with workload identity + +A pipeline can use a short-lived OIDC bearer token to create one shared +organization and act as its Admin service user. Mount a YAML file on each +Platform replica, set `LIGHTSPEED_PLATFORM_FEDERATION_FILE` to its path, +and restart Platform. Use the same file on every replica. Without this +setting, workload federation is off. + +This example allows the `apply` ServiceAccount in namespaces starting with +`team-` to enroll up to 50 organizations across the rule. Choose an audience +specific to this deployment and project it into the pipeline pod's token. +Restrict who can run workloads as those ServiceAccounts. + +```yaml +issuers: + - name: cluster + issuer: https://oidc.example.com/clusters/prod/ + audiences: [lightspeed-platform-prod] + algorithms: [RS256] + maxTokenLifetimeSeconds: 3600 + clockSkewSeconds: 60 + keys: + discoveryUrl: https://kubernetes.default.svc/.well-known/openid-configuration + jwksUrl: https://kubernetes.default.svc/openid/v1/jwks + caFile: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt + bearerTokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token +enrollment: + - issuer: cluster + subjectPattern: "system:serviceaccount:team-*:apply" + maxOrganizations: 50 + handlePattern: "^team-[a-z0-9-]+$" + organization: { universeQuota: null } + serviceUser: { name: deployer, role: admin } +``` + +Set `issuer` to the exact token `iss`, including any trailing slash. Omit +`keys` to use the issuer's public discovery document and its `jwks_uri`. +For offline verification, use `keys: { jwksFile: /etc/lightspeed/jwks.json }`. +For Kubernetes API discovery as shown above, Platform's own mounted token +must be accepted by the API server and have permission to read discovery +and signing keys. Platform rereads the CA and fetch credential on refresh. +Each replica caches keys for an hour, refreshes on an unknown key ID at most +once per 30 seconds, and accepts previously fetched keys during an outage +for up to 24 hours from their last successful refresh. + +Send the workload token as an `Authorization: Bearer` credential with +`POST /api/v1/organizations/enroll` and a JSON body such as +`{"handle":"team-research","name":"Research"}`. Platform uses the first rule +whose issuer and full subject match. In a subject pattern, `*` matches any +substring. The issuer and subject pattern identify the rule for quota +accounting. A null universe quota follows the shared organization default. + +| HTTP result | Meaning | +| --- | --- | +| `201` | Platform created the organization, its Admin service user, and the credential. The response contains `organizationId` and `enrolled: true`. | +| `200` | The workload already belongs to this organization. A retry returns the same ID and `enrolled: false`. | +| `401` | The workload token failed verification or the binding is inactive. | +| `403` | The workload or requested handle falls outside enrollment policy, or the credential's restrictions deny the operation. | +| `409` | The handle is taken, the workload already belongs to or enrolled another organization, or the rule is at capacity. | + +After enrollment, present a current workload token on ordinary Platform +API requests. Disabling the service user or removing its binding takes +effect on the next request. Its enrollment continues to occupy a rule slot +until the organization is deleted. The Platform audit records the issuer +and subject for enrollment and federated authentication. + ## Secure the Temporal connection Every runtime process opens its own connection to the diff --git a/docs/documentation/reference/environment-variables.md b/docs/documentation/reference/environment-variables.md index ba0f74046..e9a023494 100644 --- a/docs/documentation/reference/environment-variables.md +++ b/docs/documentation/reference/environment-variables.md @@ -382,6 +382,7 @@ acceptance checks, follow [Company sign-in (SSO)](../access-and-security/single- | `LIGHTSPEED_PLATFORM_API_KEY_MAX_EXPIRY_DAYS` | Unset | Maximum key lifetime. Unset means no maximum, and keys may be created without expiry when chosen explicitly; set, it also refuses keys without expiry. Both expiry settings accept 1–3650 days. | | `LIGHTSPEED_PLATFORM_SESSION_IDLE_DAYS` | `30` | Local browser and CLI session inactivity lifetime, from 1 to 365 days. | | `LIGHTSPEED_PLATFORM_SESSION_MAX_DAYS` | `90` | Absolute local browser and CLI session lifetime, from 1 to 3,650 days. Company sign-in uses its own admission window. | +| `LIGHTSPEED_PLATFORM_FEDERATION_FILE` | Unset | Path to the YAML [workload federation and enrollment policy](../deployment/configuration.md#enroll-organizations-with-workload-identity), read at Platform startup. | | `LIGHTSPEED_PLATFORM_OIDC_ISSUER` | Unset | Exact OIDC issuer. Setting any OIDC variable enables configuration validation; incomplete configuration fails startup. HTTPS is required except loopback HTTP for development. | | `LIGHTSPEED_PLATFORM_OIDC_DISCOVERY_URL` | `/.well-known/openid-configuration` | Metadata URL override, including providers with a separate discovery path. Must describe the exact issuer. HTTPS except loopback HTTP. | | `LIGHTSPEED_PLATFORM_OIDC_CLIENT_ID` | Required with OIDC | Confidential application client ID. | diff --git a/platform/backend/src/api.ts b/platform/backend/src/api.ts index 68d7ee4c7..40633e51b 100644 --- a/platform/backend/src/api.ts +++ b/platform/backend/src/api.ts @@ -1,6 +1,7 @@ import { runtimeHttpRoutes, problem } from "./runtime-http.js"; import type { MiddlewareHandler } from "hono"; import { authenticateRequest, CredentialRateLimit } from "./authentication.js"; +import { enrollmentRoutes } from "./routes/enrollment.js"; import { platformRoutes } from "./routes/platform.js"; import { credentialRoutes } from "./credential-routes.js"; import { sessionRoutes } from "./session-routes.js"; @@ -41,6 +42,8 @@ export function buildApp(ctx: AppContext) { // bearer tokens). app.on(["GET", "POST"], "/api/auth/*", (c) => ctx.auth.handler(c.req.raw)); + if (ctx.env.federation) app.route("/", enrollmentRoutes(ctx.db, ctx.env.federation)); + const authenticated: MiddlewareHandler<{ Variables: ApiVariables }> = async (c, next) => { const admission = await authenticateRequest(ctx, c.req.raw); const browserOnly = c.req.path.startsWith("/api/ui/"); diff --git a/platform/backend/src/routes/enrollment.integration.test.ts b/platform/backend/src/routes/enrollment.integration.test.ts new file mode 100644 index 000000000..05df2ecc8 --- /dev/null +++ b/platform/backend/src/routes/enrollment.integration.test.ts @@ -0,0 +1,103 @@ +import { afterAll, beforeAll, expect, it } from "vitest"; +import pg from "pg"; +import { eq } from "drizzle-orm"; +import { createDb, migrateDb, schema } from "@lightspeed-ai/platform-db"; +import { identityEnv, identityFixture, identityTestApp, responseCookies } from "../../test/identity-fixture.js"; +import { workloadIssuer } from "../../test/workload-issuer.js"; +import { federationConfig } from "../federation-config.js"; +import { WorkloadFederation } from "../federation.js"; + +let source: Awaited>; +let fixture: Awaited>; +let closeDatabase: (() => Promise) | undefined; +beforeAll(async () => { + source = await workloadIssuer(); + const rules = [ + { subjectPattern: "system:serviceaccount:team-*:apply", maxOrganizations: 10, handlePattern: "^team-", organization: { universeQuota: 2 } }, + { subjectPattern: "limited-*", maxOrganizations: 1 }, + { subjectPattern: "exact", maxOrganizations: 1 }, + ].map(rule => ({ ...rule, issuer: "cluster" })); + const federation = new WorkloadFederation(federationConfig.parse({ issuers: [source.trusted], enrollment: rules })); + const env = { ...identityEnv, federation }; + const url = process.env.LIGHTSPEED_PLATFORM_MIGRATION_TEST_URL; + if (url) { + // The CI PostgreSQL service exercises simultaneous transactions on independent connections. + const admin = new pg.Client({ connectionString: url }); + await admin.connect(); + const database = "enrollment_" + crypto.randomUUID().replaceAll("-", ""); + await admin.query(`CREATE DATABASE "${database}"`); + const scratch = new URL(url); + scratch.pathname = "/" + database; + const handle = createDb(scratch.href); + closeDatabase = async () => { + await handle.pool.end(); + try { await admin.query(`DROP DATABASE "${database}"`); } finally { await admin.end(); } + }; + await migrateDb(handle); + fixture = await identityTestApp(handle.db, env); + } else { + const local = await identityFixture(env); + fixture = local; + closeDatabase = () => local.postgres.close(); + } +}, 30_000); +afterAll(async () => { await closeDatabase?.(); await source?.close(); }); + +const endpoint = "/api/v1/organizations/enroll"; +function enroll(token: string, handle: string, extra: object = {}) { + return fixture.app.request(endpoint, { method: "POST", headers: { authorization: `Bearer ${token}`, "content-type": "application/json" }, + body: JSON.stringify({ handle, name: handle, ...extra }) }); +} + +it("admits only verified workloads and applies server-owned policy before creating anything", async () => { + const cookie = responseCookies(await fixture.request("/api/auth/sign-in/email", { email: identityEnv.adminEmail, password: identityEnv.adminPassword })); + expect((await fixture.request(endpoint, { name: "Human", handle: "human" }, cookie)).status).toBe(401); + const response = await fixture.request("/api/v1/platform/credentials", { name: "Existing key" }, cookie); + expect(response.status).toBe(201); + const { secret } = await response.json() as { secret: string }; + expect((await enroll(secret, "from-key")).status).toBe(401); + const subject = "system:serviceaccount:team-validation:apply"; + const token = await source.mint({ sub: subject }); + expect((await enroll(token, "team-valid", { universeQuota: 10000 })).status).toBe(400); + expect((await enroll(token, "wrong-handle")).status).toBe(403); + expect((await enroll(await source.mint({ sub: "exact-extra" }), "team-other")).status).toBe(403); + expect((await enroll(await source.mint({ sub: "system:serviceaccount:team-a:other" }), "team-other")).status).toBe(403); + await fixture.db.insert(schema.organization).values({ id: crypto.randomUUID(), slug: "team-existing", name: "Existing", createdAt: new Date() }); + expect((await enroll(token, "team-existing")).status).toBe(409); + expect(await fixture.db.select().from(schema.organizationEnrollments).where(eq(schema.organizationEnrollments.subject, subject))).toHaveLength(0); +}); + +it("creates one ordinary organization, one admin binding and one enrollment audit, then resolves retries", async () => { + const token = await source.mint(); + const responses = await Promise.all([enroll(token, "team-first"), enroll(token, "team-first")]); + expect(responses.map(r => r.status).sort()).toEqual([200, 201]); + const [first, retry] = await Promise.all(responses.sort((a, b) => b.status - a.status).map(r => r.json())) as [{ organizationId: string; enrolled: boolean }, unknown]; + expect(first.enrolled).toBe(true); + expect(retry).toEqual({ organizationId: first.organizationId, enrolled: false }); + expect((await enroll(token, "team-second")).status).toBe(409); + const [org] = await fixture.db.select().from(schema.organization).where(eq(schema.organization.id, first.organizationId)); + expect(org).toMatchObject({ slug: "team-first", personalUserId: null, universeQuota: 2, defaultProtected: true }); + const users = await fixture.db.select().from(schema.serviceUsers).where(eq(schema.serviceUsers.organizationId, first.organizationId)); + expect(users).toMatchObject([{ name: "deployer", role: "admin", enabled: true }]); + const audit = await fixture.db.select().from(schema.identityAudit).where(eq(schema.identityAudit.action, "organization.enrolled")); + expect(audit.filter(e => e.targetId === first.organizationId)).toMatchObject([{ actorId: `serviceUser:${users[0]!.id}`, + details: { issuer: source.issuer, subject: source.subject, credentialKind: "federated" } }]); + const result = await fixture.app.request("/api/v1/platform/organizations", { headers: { authorization: `Bearer ${token}` } }); + expect(await result.json()).toMatchObject({ canCreate: false, organizations: [{ id: first.organizationId, role: "admin" }] }); + await fixture.db.update(schema.serviceUsers).set({ enabled: false }).where(eq(schema.serviceUsers.id, users[0]!.id)); + expect((await enroll(token, "team-first")).status).toBe(401); + await fixture.db.delete(schema.federatedCredentials).where(eq(schema.federatedCredentials.serviceUserId, users[0]!.id)); + expect((await enroll(token, "team-second")).status).toBe(409); + await fixture.db.delete(schema.organization).where(eq(schema.organization.id, first.organizationId)); + expect((await enroll(token, "team-first")).status).toBe(201); +}); + +it("awards the last rule slot once and rolls back the losing enrollment", async () => { + const requests = await Promise.all(["a", "b"].map(async id => enroll(await source.mint({ sub: "limited-" + id }), "limited-" + id))); + expect(requests.map(r => r.status).sort()).toEqual([201, 409]); + const enrolled = await fixture.db.select().from(schema.organizationEnrollments).where(eq(schema.organizationEnrollments.subjectPattern, "limited-*")); + expect(enrolled).toHaveLength(1); + const loser = requests[0]!.status === 409 ? "limited-a" : "limited-b"; + expect(await fixture.db.select().from(schema.organization).where(eq(schema.organization.slug, loser))).toHaveLength(0); + expect(await fixture.db.select().from(schema.federatedCredentials).where(eq(schema.federatedCredentials.subject, loser))).toHaveLength(0); +}); diff --git a/platform/backend/src/routes/enrollment.ts b/platform/backend/src/routes/enrollment.ts new file mode 100644 index 000000000..98dc3fe66 --- /dev/null +++ b/platform/backend/src/routes/enrollment.ts @@ -0,0 +1,89 @@ +import { Hono } from "hono"; +import { bodyLimit } from "hono/body-limit"; +import { HTTPException } from "hono/http-exception"; +import { and, eq, sql } from "drizzle-orm"; +import { schema, type Db } from "@lightspeed-ai/platform-db"; +import { PLATFORM_OPERATIONS, type PlatformOperationParams } from "@lightspeed-ai/platform-shared"; +import { enforceRestrictions } from "../auth-context.js"; +import { resolveFederatedBinding } from "../federated-binding.js"; +import type { WorkloadFederation, WorkloadIdentity } from "../federation.js"; +import { auditIdentity } from "../identity-audit.js"; +import { problem } from "../runtime-http.js"; + +const operation = "platform/organizations/enroll"; +const spec = PLATFORM_OPERATIONS[operation]; + +/** Match the full subject. Only '*' is special, and all other characters are literal. */ +function matchesSubject(pattern: string, subject: string) { + const [prefix, ...parts] = pattern.split("*"); + if (!parts.length) return subject === prefix; + const suffix = parts.pop()!; + if (!subject.startsWith(prefix!) || !subject.endsWith(suffix)) return false; + let offset = prefix!.length; + for (const part of parts) { + const index = subject.indexOf(part, offset); + if (index < 0) return false; + offset = index + part.length; + } + return offset <= subject.length - suffix.length; +} + +async function enroll(db: Db, federation: WorkloadFederation, identity: WorkloadIdentity, input: PlatformOperationParams) { + const { organization, organizationEnrollments, serviceUsers, federatedCredentials } = schema; + const { issuer, subject } = identity; + return db.transaction(async tx => { + // Serialize first contact across replicas before checking either the binding or the remaining quota. + await tx.execute(sql`SELECT pg_advisory_xact_lock(hashtextextended(${issuer}, 731845920115))`); + const binding = await resolveFederatedBinding(tx, identity); + if (binding) { + if (!binding.auth) throw new HTTPException(401, { message: "Workload credential is inactive" }); + if (binding.handle !== input.handle) throw new HTTPException(409, { message: "Workload is bound to another organization" }); + enforceRestrictions(binding.auth, { operation, organizationId: binding.organizationId }); + return { organizationId: binding.organizationId, enrolled: false }; + } + + const issuerName = federation.config.issuers.find(i => i.issuer === issuer)?.name; + const rule = federation.config.enrollment.find(r => r.issuer === issuerName && matchesSubject(r.subjectPattern, subject)); + if (!rule) throw new HTTPException(403, { message: "No enrollment rule matches this workload" }); + if (rule.handlePattern && !rule.handlePattern.test(input.handle)) throw new HTTPException(403, { message: "Handle is outside the enrollment rule" }); + const [previous] = await tx.select({ id: organizationEnrollments.organizationId }).from(organizationEnrollments) + .where(and(eq(organizationEnrollments.issuer, issuer), eq(organizationEnrollments.subject, subject))); + if (previous) throw new HTTPException(409, { message: "Workload already enrolled an organization" }); + const total = await tx.$count(organizationEnrollments, + and(eq(organizationEnrollments.issuer, issuer), eq(organizationEnrollments.subjectPattern, rule.subjectPattern))); + if (total >= rule.maxOrganizations) throw new HTTPException(409, { message: "Enrollment rule has reached its organization limit" }); + + const organizationId = crypto.randomUUID(); + const [created] = await tx.insert(organization).values({ id: organizationId, name: input.name, slug: input.handle, + createdAt: new Date(), universeQuota: rule.organization.universeQuota }).onConflictDoNothing({ target: organization.slug }).returning({ id: organization.id }); + if (!created) throw new HTTPException(409, { message: "Organization handle is taken" }); + const [user] = await tx.insert(serviceUsers).values({ organizationId, ...rule.serviceUser }).returning({ id: serviceUsers.id }); + const [credential] = await tx.insert(federatedCredentials).values({ issuer, subject, serviceUserId: user!.id, lastUsedAt: new Date() }) + .onConflictDoNothing({ target: [federatedCredentials.issuer, federatedCredentials.subject] }).returning({ id: federatedCredentials.id }); + if (!credential) throw new HTTPException(409, { message: "Workload already has a credential binding" }); + await tx.insert(organizationEnrollments).values({ organizationId, issuer, subject, subjectPattern: rule.subjectPattern }); + await auditIdentity(tx, { action: "organization.enrolled", targetId: organizationId, actorId: `serviceUser:${user!.id}`, + details: { issuer, subject, subjectPattern: rule.subjectPattern, credentialKind: "federated", credentialId: credential.id } }); + return { organizationId, enrolled: true }; + }); +} + +/** Only this route accepts a verified identity that has no Platform principal yet. */ +export function enrollmentRoutes(db: Db, federation: WorkloadFederation) { + const app = new Hono(); + app.onError((error, c) => { + if (!(error instanceof HTTPException)) throw error; + const kind = { 400: "invalidRequest", 401: "unauthenticated", 403: "forbidden", 409: "conflict" }[error.status as number]; + return problem(c, error.status, kind ?? "invalidRequest", error.message); + }); + app.post(spec.path, bodyLimit({ maxSize: 16 * 1024, onError: c => problem(c, 413, "invalidRequest", "Enrollment body too large") }), async c => { + const token = /^Bearer ([^\s,]+)$/i.exec(c.req.header("authorization") ?? "")?.[1]; + const identity = token && await federation.verify(token); + if (!identity) return problem(c, 401, "unauthenticated", "Verified workload token required"); + const input = spec.params.safeParse(await c.req.json().catch(() => null)); + if (!input.success) return problem(c, 400, "invalidRequest", "A valid organization handle and name are required"); + const result = await enroll(db, federation, identity, input.data); + return c.json(result, result.enrolled ? 201 : 200); + }); + return app; +} diff --git a/platform/backend/src/routes/platform.ts b/platform/backend/src/routes/platform.ts index 8cd3ecfac..b88eb3c07 100644 --- a/platform/backend/src/routes/platform.ts +++ b/platform/backend/src/routes/platform.ts @@ -37,6 +37,7 @@ export function platformRoutes(ctx: AppContext) { console.error("Platform API failed", error); return problem(c, 500, "internal", "Platform request failed"); }); for (const [operation, spec] of Object.entries(PLATFORM_OPERATIONS)) { + if (!spec.path.startsWith("/api/v1/platform/")) continue; if (operation.startsWith("platform/session/") || operation.startsWith("platform/credentials/") || operation.includes("/credentials/")) continue; const path = spec.path.replace(/^\/api\/v1\/platform/, "").replace(/\{([^}]+)\}/g, ":$1"); app.on(spec.method, path, async c => { diff --git a/platform/backend/test/identity-fixture.ts b/platform/backend/test/identity-fixture.ts index e64bb1dd5..a64d8771a 100644 --- a/platform/backend/test/identity-fixture.ts +++ b/platform/backend/test/identity-fixture.ts @@ -57,6 +57,10 @@ function pooled(instance: PGlite): PGlite { export async function identityFixture(env: ServerEnv = identityEnv) { const postgres = pooled(await migratedDatabase()); const db = drizzle(postgres, { schema, casing: "snake_case" }) as unknown as Db; + return { postgres, ...await identityTestApp(db, env) }; +} + +export async function identityTestApp(db: Db, env: ServerEnv) { await bootstrapAdmin(db, env); const auth = createAuth(db, env); const app = buildApp({ db, auth, env, pool: {} as never }); @@ -64,7 +68,7 @@ export async function identityFixture(env: ServerEnv = identityEnv) { method, headers: { origin: env.baseUrl, cookie, ...(body === undefined ? {} : { "content-type": "application/json" }) }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), })); - return { db, postgres, auth, app, request, env }; + return { db, auth, app, request, env }; } export function responseCookies(response: Response): string { diff --git a/platform/db/migrations/0002_organization_enrollment.sql b/platform/db/migrations/0002_organization_enrollment.sql new file mode 100644 index 000000000..1133786db --- /dev/null +++ b/platform/db/migrations/0002_organization_enrollment.sql @@ -0,0 +1,11 @@ +CREATE TABLE "organization_enrollments" ( + "organization_id" text PRIMARY KEY NOT NULL, + "issuer" text NOT NULL, + "subject" text NOT NULL, + "subject_pattern" text NOT NULL, + "created_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "organization_enrollments" ADD CONSTRAINT "organization_enrollments_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "organization_enrollments_identity_idx" ON "organization_enrollments" USING btree ("issuer","subject");--> statement-breakpoint +CREATE INDEX "organization_enrollments_rule_idx" ON "organization_enrollments" USING btree ("issuer","subject_pattern"); \ No newline at end of file diff --git a/platform/db/migrations/meta/0002_snapshot.json b/platform/db/migrations/meta/0002_snapshot.json new file mode 100644 index 000000000..2fa2b67eb --- /dev/null +++ b/platform/db/migrations/meta/0002_snapshot.json @@ -0,0 +1,2052 @@ +{ + "id": "425ab2fc-44fe-4a67-a08a-f4827a5c1d2e", + "prevId": "9e7ea8f0-5ff2-48cb-97cf-9d22578bea56", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "account_userId_idx": { + "name": "account_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.apikey": { + "name": "apikey", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "config_id": { + "name": "config_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "start": { + "name": "start", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reference_id": { + "name": "reference_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "prefix": { + "name": "prefix", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refill_interval": { + "name": "refill_interval", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "refill_amount": { + "name": "refill_amount", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_refill_at": { + "name": "last_refill_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "rate_limit_enabled": { + "name": "rate_limit_enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "rate_limit_time_window": { + "name": "rate_limit_time_window", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 86400000 + }, + "rate_limit_max": { + "name": "rate_limit_max", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 10 + }, + "request_count": { + "name": "request_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "remaining": { + "name": "remaining", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "last_request": { + "name": "last_request", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "permissions": { + "name": "permissions", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "apikey_config_idx": { + "name": "apikey_config_idx", + "columns": [ + { + "expression": "config_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "apikey_reference_idx": { + "name": "apikey_reference_idx", + "columns": [ + { + "expression": "reference_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "apikey_key_idx": { + "name": "apikey_key_idx", + "columns": [ + { + "expression": "key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.device_code": { + "name": "device_code", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "device_code": { + "name": "device_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_code": { + "name": "user_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_polled_at": { + "name": "last_polled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "polling_interval": { + "name": "polling_interval", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "client_id": { + "name": "client_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "approval_access_version": { + "name": "approval_access_version", + "type": "integer", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "device_code_device_code_idx": { + "name": "device_code_device_code_idx", + "columns": [ + { + "expression": "device_code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "device_code_user_code_idx": { + "name": "device_code_user_code_idx", + "columns": [ + { + "expression": "user_code", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "device_code_user_id_user_id_fk": { + "name": "device_code_user_id_user_id_fk", + "tableFrom": "device_code", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.invitation": { + "name": "invitation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "inviter_id": { + "name": "inviter_id", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "invitation_organizationId_idx": { + "name": "invitation_organizationId_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "invitation_email_idx": { + "name": "invitation_email_idx", + "columns": [ + { + "expression": "email", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "invitation_organization_id_organization_id_fk": { + "name": "invitation_organization_id_organization_id_fk", + "tableFrom": "invitation", + "tableTo": "organization", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "invitation_inviter_id_user_id_fk": { + "name": "invitation_inviter_id_user_id_fk", + "tableFrom": "invitation", + "tableTo": "user", + "columnsFrom": [ + "inviter_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.member": { + "name": "member", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "member_organizationId_idx": { + "name": "member_organizationId_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_userId_idx": { + "name": "member_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "member_organization_user_idx": { + "name": "member_organization_user_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "member_organization_id_organization_id_fk": { + "name": "member_organization_id_organization_id_fk", + "tableFrom": "member", + "tableTo": "organization", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "member_user_id_user_id_fk": { + "name": "member_user_id_user_id_fk", + "tableFrom": "member", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization": { + "name": "organization", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "metadata": { + "name": "metadata", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "personal_user_id": { + "name": "personal_user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "universe_quota": { + "name": "universe_quota", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "base_universe_role": { + "name": "base_universe_role", + "type": "text", + "primaryKey": false, + "notNull": false, + "default": "'viewer'" + }, + "default_protected": { + "name": "default_protected", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "require_protected": { + "name": "require_protected", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "membership_policy": { + "name": "membership_policy", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + } + }, + "indexes": { + "organization_slug_uidx": { + "name": "organization_slug_uidx", + "columns": [ + { + "expression": "slug", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_personal_user_id_user_id_fk": { + "name": "organization_personal_user_id_user_id_fk", + "tableFrom": "organization", + "tableTo": "user", + "columnsFrom": [ + "personal_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "organization_slug_unique": { + "name": "organization_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "organization_personal_user_id_unique": { + "name": "organization_personal_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "personal_user_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "active_organization_id": { + "name": "active_organization_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_version": { + "name": "access_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "session_kind": { + "name": "session_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'browser'" + } + }, + "indexes": { + "session_userId_idx": { + "name": "session_userId_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "identity_source": { + "name": "identity_source", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'local'" + }, + "oidc_issuer": { + "name": "oidc_issuer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "oidc_subject": { + "name": "oidc_subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "directory_groups": { + "name": "directory_groups", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "company_admitted": { + "name": "company_admitted", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "provider_checked_at": { + "name": "provider_checked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "emergency_admin": { + "name": "emergency_admin", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "access_version": { + "name": "access_version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + } + }, + "indexes": { + "user_oidc_identity_idx": { + "name": "user_oidc_identity_idx", + "columns": [ + { + "expression": "oidc_issuer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "oidc_subject", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "verification_identifier_idx": { + "name": "verification_identifier_idx", + "columns": [ + { + "expression": "identifier", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.credential_bindings": { + "name": "credential_bindings", + "schema": "", + "columns": { + "key_id": { + "name": "key_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "service_user_id": { + "name": "service_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "restrictions": { + "name": "restrictions", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "credential_bindings_user_idx": { + "name": "credential_bindings_user_idx", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "credential_bindings_service_user_idx": { + "name": "credential_bindings_service_user_idx", + "columns": [ + { + "expression": "service_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "credential_bindings_key_id_apikey_id_fk": { + "name": "credential_bindings_key_id_apikey_id_fk", + "tableFrom": "credential_bindings", + "tableTo": "apikey", + "columnsFrom": [ + "key_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_bindings_user_id_user_id_fk": { + "name": "credential_bindings_user_id_user_id_fk", + "tableFrom": "credential_bindings", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "credential_bindings_service_user_id_service_users_id_fk": { + "name": "credential_bindings_service_user_id_service_users_id_fk", + "tableFrom": "credential_bindings", + "tableTo": "service_users", + "columnsFrom": [ + "service_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "credential_bindings_one_principal": { + "name": "credential_bindings_one_principal", + "value": "(\"credential_bindings\".\"user_id\" IS NOT NULL) <> (\"credential_bindings\".\"service_user_id\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.federated_credentials": { + "name": "federated_credentials", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "service_user_id": { + "name": "service_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "service_account_uid": { + "name": "service_account_uid", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "restrictions": { + "name": "restrictions", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "last_used_at": { + "name": "last_used_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "federated_credentials_identity_idx": { + "name": "federated_credentials_identity_idx", + "columns": [ + { + "expression": "issuer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "federated_credentials_service_user_idx": { + "name": "federated_credentials_service_user_idx", + "columns": [ + { + "expression": "service_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "federated_credentials_service_user_id_service_users_id_fk": { + "name": "federated_credentials_service_user_id_service_users_id_fk", + "tableFrom": "federated_credentials", + "tableTo": "service_users", + "columnsFrom": [ + "service_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.identity_audit": { + "name": "identity_audit", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "actor_id": { + "name": "actor_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "universe_id": { + "name": "universe_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "details": { + "name": "details", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + } + }, + "indexes": { + "identity_audit_created_idx": { + "name": "identity_audit_created_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.organization_enrollments": { + "name": "organization_enrollments", + "schema": "", + "columns": { + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "issuer": { + "name": "issuer", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject_pattern": { + "name": "subject_pattern", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "organization_enrollments_identity_idx": { + "name": "organization_enrollments_identity_idx", + "columns": [ + { + "expression": "issuer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "organization_enrollments_rule_idx": { + "name": "organization_enrollments_rule_idx", + "columns": [ + { + "expression": "issuer", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "subject_pattern", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "organization_enrollments_organization_id_organization_id_fk": { + "name": "organization_enrollments_organization_id_organization_id_fk", + "tableFrom": "organization_enrollments", + "tableTo": "organization", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.platform_settings": { + "name": "platform_settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.service_users": { + "name": "service_users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'member'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "service_users_organization_idx": { + "name": "service_users_organization_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "service_users_organization_name_idx": { + "name": "service_users_organization_name_idx", + "columns": [ + { + "expression": "organization_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "name", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "service_users_organization_id_organization_id_fk": { + "name": "service_users_organization_id_organization_id_fk", + "tableFrom": "service_users", + "tableTo": "organization", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.universe_grants": { + "name": "universe_grants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "universe_id": { + "name": "universe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "service_user_id": { + "name": "service_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "universe_grants_user_idx": { + "name": "universe_grants_user_idx", + "columns": [ + { + "expression": "universe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "universe_grants_service_user_idx": { + "name": "universe_grants_service_user_idx", + "columns": [ + { + "expression": "universe_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "service_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "universe_grants_universe_id_universes_id_fk": { + "name": "universe_grants_universe_id_universes_id_fk", + "tableFrom": "universe_grants", + "tableTo": "universes", + "columnsFrom": [ + "universe_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "universe_grants_user_id_user_id_fk": { + "name": "universe_grants_user_id_user_id_fk", + "tableFrom": "universe_grants", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "universe_grants_service_user_id_service_users_id_fk": { + "name": "universe_grants_service_user_id_service_users_id_fk", + "tableFrom": "universe_grants", + "tableTo": "service_users", + "columnsFrom": [ + "service_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "universe_grants_one_principal": { + "name": "universe_grants_one_principal", + "value": "(\"universe_grants\".\"user_id\" IS NOT NULL) <> (\"universe_grants\".\"service_user_id\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.universes": { + "name": "universes", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "organization_id": { + "name": "organization_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "lightspeed_universe_id": { + "name": "lightspeed_universe_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "handle": { + "name": "handle", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_policy": { + "name": "access_policy", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "runtime_configuration": { + "name": "runtime_configuration", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'orbit'" + }, + "icon_color": { + "name": "icon_color", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'default'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "features": { + "name": "features", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "universes_organization_id_organization_id_fk": { + "name": "universes_organization_id_organization_id_fk", + "tableFrom": "universes", + "tableTo": "organization", + "columnsFrom": [ + "organization_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "universes_lightspeed_universe_id_unique": { + "name": "universes_lightspeed_universe_id_unique", + "nullsNotDistinct": false, + "columns": [ + "lightspeed_universe_id" + ] + }, + "universes_handle_unique": { + "name": "universes_handle_unique", + "nullsNotDistinct": false, + "columns": [ + "handle" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/platform/db/migrations/meta/_journal.json b/platform/db/migrations/meta/_journal.json index d1c282273..62c5fae0c 100644 --- a/platform/db/migrations/meta/_journal.json +++ b/platform/db/migrations/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1795096286064, "tag": "0001_federated_credentials", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1795096426457, + "tag": "0002_organization_enrollment", + "breakpoints": true } ] } \ No newline at end of file diff --git a/platform/db/scripts/check-migrations.ts b/platform/db/scripts/check-migrations.ts index 93d3bbe17..2d42aacef 100644 --- a/platform/db/scripts/check-migrations.ts +++ b/platform/db/scripts/check-migrations.ts @@ -113,7 +113,7 @@ async function requirePlatformShape(pool: pg.Pool): Promise { await requireTable(pool, "member"); await requireTable(pool, "identity_audit"); await requireTable(pool, "platform_settings"); - for (const table of ["apikey", "service_users", "credential_bindings", "federated_credentials", "universe_grants", "device_code"]) { + for (const table of ["apikey", "service_users", "credential_bindings", "federated_credentials", "organization_enrollments", "universe_grants", "device_code"]) { await requireTable(pool, table); } await requireColumn(pool, "user", "oidc_subject"); diff --git a/platform/db/src/schema/platform.ts b/platform/db/src/schema/platform.ts index 6a17a30b0..5af541404 100644 --- a/platform/db/src/schema/platform.ts +++ b/platform/db/src/schema/platform.ts @@ -127,6 +127,18 @@ export const federatedCredentials = pgTable("federated_credentials", { index("federated_credentials_service_user_idx").on(table.serviceUserId), ]); +/** The enrollment outlives credential rotation and is released with its organization. */ +export const organizationEnrollments = pgTable("organization_enrollments", { + organizationId: text("organization_id").primaryKey().references(() => organization.id, { onDelete: "cascade" }), + issuer: text("issuer").notNull(), + subject: text("subject").notNull(), + subjectPattern: text("subject_pattern").notNull(), + createdAt: createdAt(), +}, table => [ + uniqueIndex("organization_enrollments_identity_idx").on(table.issuer, table.subject), + index("organization_enrollments_rule_idx").on(table.issuer, table.subjectPattern), +]); + export const universesRelations = relations(universes, ({ one }) => ({ organization: one(organization, { fields: [universes.organizationId], diff --git a/platform/shared/contract/http.json b/platform/shared/contract/http.json index ac9a5adf4..e4d4fbaad 100644 --- a/platform/shared/contract/http.json +++ b/platform/shared/contract/http.json @@ -150,6 +150,16 @@ "params": "PlatformOrganizationsListParams", "result": "PlatformOrganizationsListResult" }, + { + "operationId": "platform/organizations/enroll", + "helper": { + "name": "enrollOrganization" + }, + "method": "POST", + "path": "/api/v1/organizations/enroll", + "params": "PlatformOrganizationsEnrollParams", + "result": "PlatformOrganizationsEnrollResult" + }, { "operationId": "platform/organizations/create", "helper": { diff --git a/platform/shared/contract/platform.schema.json b/platform/shared/contract/platform.schema.json index da1780614..25bdd4ce6 100644 --- a/platform/shared/contract/platform.schema.json +++ b/platform/shared/contract/platform.schema.json @@ -2044,6 +2044,43 @@ ], "additionalProperties": false }, + "PlatformOrganizationsEnrollParams": { + "type": "object", + "properties": { + "handle": { + "type": "string", + "pattern": "^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$" + }, + "name": { + "type": "string", + "minLength": 1, + "maxLength": 120 + } + }, + "required": [ + "handle", + "name" + ], + "additionalProperties": false + }, + "PlatformOrganizationsEnrollResult": { + "type": "object", + "properties": { + "organizationId": { + "type": "string", + "minLength": 1 + }, + "enrolled": { + "type": "boolean", + "description": "True when this request created the organization; false when the workload already belongs to it." + } + }, + "required": [ + "organizationId", + "enrolled" + ], + "additionalProperties": false + }, "PlatformOrganizationsCreateParams": { "type": "object", "properties": { diff --git a/platform/shared/src/platform-api.ts b/platform/shared/src/platform-api.ts index 6c1c038ec..a6e48d66e 100644 --- a/platform/shared/src/platform-api.ts +++ b/platform/shared/src/platform-api.ts @@ -96,6 +96,9 @@ export const PLATFORM_OPERATIONS = { "platform/settings/list": { helper: { name: "listPlatformSettings" }, method: "GET", path: "/api/v1/platform/settings", params: z.object({}).strict(), result: z.object({ settings: z.array(platformSettingViewSchema) }) }, "platform/settings/put": { helper: { name: "putPlatformSetting" }, method: "PUT", path: "/api/v1/platform/settings/{key}", params: platformSettingPutSchema, result: z.object({ setting: platformSettingViewSchema }) }, "platform/organizations/list": { helper: { name: "listOrganizations" }, method: "GET", path: "/api/v1/platform/organizations", params: z.object({}).strict(), result: z.object({ organizations: z.array(organizationViewSchema), canCreate: z.boolean() }) }, + "platform/organizations/enroll": { helper: { name: "enrollOrganization" }, method: "POST", path: "/api/v1/organizations/enroll", + params: organizationCreateSchema.pick({ handle: true, name: true }), + result: z.object({ organizationId: id, enrolled: z.boolean().describe("True when this request created the organization; false when the workload already belongs to it.") }) }, "platform/organizations/create": { helper: { name: "createOrganization" }, method: "POST", path: "/api/v1/platform/organizations", params: organizationCreateSchema, result: z.object({ organization: organizationViewSchema }) }, "platform/organizations/read": { helper: { name: "readOrganization" }, method: "GET", path: "/api/v1/platform/organizations/{organizationId}", params: z.object(organizationPath).strict(), result: z.object({ organization: organizationViewSchema }) }, "platform/organizations/update": { helper: { name: "updateOrganization" }, method: "PATCH", path: "/api/v1/platform/organizations/{organizationId}", params: organizationUpdateSchema.extend(organizationPath), result: z.object({ organization: organizationViewSchema }) }, diff --git a/release/metadata.env b/release/metadata.env index d5118e02f..7893abf0e 100644 --- a/release/metadata.env +++ b/release/metadata.env @@ -19,5 +19,5 @@ LIGHTSPEED_CONTROLLER_PROTOCOL_VERSION=4 LIGHTSPEED_SCHEMA_REVISION=7 # Drizzle journal length and the oldest platform migration boundary accepted by # the current release's automated upgrade gate. -LIGHTSPEED_PLATFORM_SCHEMA_REVISION=2 +LIGHTSPEED_PLATFORM_SCHEMA_REVISION=3 LIGHTSPEED_PLATFORM_UPGRADE_FROM=0000_initial_platform