Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 72 additions & 0 deletions apps/mesh/migrations/051-org-sso.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { type Kysely, sql } from "kysely";

export async function up(db: Kysely<unknown>): Promise<void> {
// SSO provider configuration per organization
await db.schema
.createTable("org_sso_config")
.addColumn("id", "text", (col) => col.primaryKey())
.addColumn("organization_id", "text", (col) =>
col.notNull().references("organization.id").onDelete("cascade"),
)
.addColumn("issuer", "text", (col) => col.notNull())
.addColumn("client_id", "text", (col) => col.notNull())
.addColumn("client_secret", "text", (col) => col.notNull()) // encrypted
.addColumn("discovery_endpoint", "text")
.addColumn("scopes", "text", (col) =>
col.notNull().defaultTo('["openid","email","profile"]'),
)
.addColumn("domain", "text", (col) => col.notNull())
.addColumn("enforced", "integer", (col) => col.notNull().defaultTo(0))
.addColumn("created_at", "text", (col) =>
col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`),
)
.addColumn("updated_at", "text", (col) =>
col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`),
)
.execute();

// One SSO config per organization
await db.schema
.createIndex("idx_org_sso_config_org_id")
.unique()
.on("org_sso_config")
.column("organization_id")
.execute();

// Lookup by email domain
await db.schema
.createIndex("idx_org_sso_config_domain")
.on("org_sso_config")
.column("domain")
.execute();

// Tracks per-user SSO authentication per organization
await db.schema
.createTable("org_sso_sessions")
.addColumn("id", "text", (col) => col.primaryKey())
.addColumn("user_id", "text", (col) =>
col.notNull().references("user.id").onDelete("cascade"),
)
.addColumn("organization_id", "text", (col) =>
col.notNull().references("organization.id").onDelete("cascade"),
)
.addColumn("authenticated_at", "text", (col) => col.notNull())
.addColumn("expires_at", "text", (col) => col.notNull())
.addColumn("created_at", "text", (col) =>
col.notNull().defaultTo(sql`CURRENT_TIMESTAMP`),
)
.execute();

// One active session per user per org
await db.schema
.createIndex("idx_org_sso_sessions_user_org")
.unique()
.on("org_sso_sessions")
.columns(["user_id", "organization_id"])
.execute();
}

export async function down(db: Kysely<unknown>): Promise<void> {
await db.schema.dropTable("org_sso_sessions").execute();
await db.schema.dropTable("org_sso_config").execute();
}
2 changes: 2 additions & 0 deletions apps/mesh/migrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import * as migration047addnextrunat from "./047-add-next-run-at.ts";
import * as migration048mergeprojectsagents from "./048-merge-projects-agents.ts";
import * as migration049removeorgadminprojects from "./049-remove-org-admin-projects.ts";
import * as migration050durableagentruns from "./050-durable-agent-runs.ts";
import * as migration051orgsso from "./051-org-sso.ts";

/**
* Core migrations for the Mesh application.
Expand Down Expand Up @@ -112,6 +113,7 @@ const migrations: Record<string, Migration> = {
"048-merge-projects-agents": migration048mergeprojectsagents,
"049-remove-org-admin-projects": migration049removeorgadminprojects,
"050-durable-agent-runs": migration050durableagentruns,
"051-org-sso": migration051orgsso,
};

export default migrations;
48 changes: 48 additions & 0 deletions apps/mesh/src/api/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
tracingMiddleware,
} from "../observability";
import authRoutes from "./routes/auth";
import orgSsoRoutes from "./routes/org-sso";
import { createDecopilotRoutes } from "./routes/decopilot";
import downstreamTokenRoutes from "./routes/downstream-token";
import decoSitesRoutes from "./routes/deco-sites";
Expand Down Expand Up @@ -988,6 +989,53 @@ export async function createApp(options: CreateAppOptions = {}) {
return next();
});

// ============================================================================
// Server-side SSO Enforcement Middleware
// ============================================================================
// When an org has SSO enforcement enabled, block API requests from users
// who haven't completed the SSO flow. Exempt paths: SSO routes themselves,
// auth routes, and non-org-scoped endpoints.
app.use("*", async (c, next) => {
const path = c.req.path;
// Skip SSO enforcement for SSO routes, auth routes, and public endpoints
if (
path.startsWith("/api/org-sso/") ||
path.startsWith("/api/auth/") ||
path.startsWith("/api/tools/management") ||
path.startsWith("/oauth-proxy/")
) {
return next();
}

const ctx = c.get("meshContext") as MeshContext | undefined;
if (!ctx?.organization?.id || !ctx?.auth?.user?.id) {
return next();
}

const ssoConfig = await ctx.storage.orgSsoConfig.getByOrgId(
ctx.organization.id,
);
if (!ssoConfig?.enforced) {
return next();
}

const hasValidSession = await ctx.storage.orgSsoSessions.isValid(
ctx.auth.user.id,
ctx.organization.id,
);
if (!hasValidSession) {
return c.json(
{ error: "SSO authentication required for this organization" },
403,
);
}

return next();
});

// Organization-level SSO routes (must be after context middleware)
app.route("/api/org-sso", orgSsoRoutes);

// Get all management tools (for OAuth consent UI)
app.get("/api/tools/management", (c) => {
return c.json({
Expand Down
Loading
Loading