mirror of
https://github.com/different-ai/openwork.git
synced 2026-11-23 12:51:42 +08:00
fix(den-api): require SSO for sign-in, not for agent and key credentials (#7584)
Organization re-entry treated the synthetic session of a verified MCP principal as a persisted session, causing proof lookup to parse a non-TypeID and return 500. Carry a typed sign-in session ID from authentication and consult SSO proofs only for that session on re-entry. Keep interactive issuance checks and reject policy enablement without a sign-in session.
This commit is contained in:
13 files changed
+142
-38
No files matched your search
@@ -1937,7 +1937,7 @@ export const auth = betterAuth({
|
||||
|
||||
const referenceId = normalizeDenTypeId("organization", activeOrganizationId);
|
||||
// An organization that requires SSO grants MCP access only from a session signed in through its SSO.
|
||||
const ssoBlock = await findSsoAccessBlock({ sessionId: typeof session.id === "string" ? session.id : null, organizationId: referenceId });
|
||||
const ssoBlock = await findSsoAccessBlock({ sessionId: typeof session.id === "string" ? normalizeDenTypeId("session", session.id) : null, organizationId: referenceId });
|
||||
if (ssoBlock) {
|
||||
throw new APIError("FORBIDDEN", { message: SSO_REQUIRED_MESSAGE });
|
||||
}
|
||||
|
||||
@@ -202,6 +202,7 @@ export async function configRouteContext(ctx: ConfigAreaContext): Promise<Config
|
||||
const c = new Context<ConfigRouteEnv>(new Request("http://config-blobs.invalid/apply"))
|
||||
c.set("organizationContext", payload)
|
||||
c.set("apiKey", null)
|
||||
c.set("signInSessionId", null)
|
||||
c.set("session", {
|
||||
id: CONFIG_APPLY_SESSION_ID,
|
||||
token: CONFIG_APPLY_SESSION_ID,
|
||||
|
||||
@@ -83,8 +83,10 @@ export async function isLocalDeploymentOperatorUserId(userId: string): Promise<b
|
||||
return isPlatformAdminUserId(userId)
|
||||
}
|
||||
|
||||
type DeploymentPrincipal = Pick<AuthContextVariables, "apiKey" | "session" | "user">
|
||||
|
||||
/** A genuine Better Auth user session (not an API key or MCP token) of an allowlisted local operator. */
|
||||
export async function hasLocalDeploymentOperatorSessionAuthority(principal: AuthContextVariables): Promise<boolean> {
|
||||
export async function hasLocalDeploymentOperatorSessionAuthority(principal: DeploymentPrincipal): Promise<boolean> {
|
||||
if (principal.apiKey || !principal.user?.id || !principal.session?.id || !principal.session.token) return false
|
||||
try {
|
||||
normalizeDenTypeId("session", principal.session.id)
|
||||
@@ -101,7 +103,7 @@ export async function hasLocalDeploymentOperatorSessionAuthority(principal: Auth
|
||||
* counts; organization roles, permissions and ownership never do. Always false
|
||||
* on hosted Den, before any lookup.
|
||||
*/
|
||||
export async function isLocalDeploymentOperator(principal: AuthContextVariables): Promise<boolean> {
|
||||
export async function isLocalDeploymentOperator(principal: DeploymentPrincipal): Promise<boolean> {
|
||||
if (env.features.deployment !== "self_hosted") return false
|
||||
const apiKey = principal.apiKey
|
||||
if (!apiKey) return hasLocalDeploymentOperatorSessionAuthority(principal)
|
||||
@@ -119,7 +121,7 @@ export async function isLocalDeploymentOperator(principal: AuthContextVariables)
|
||||
* Caller-specific hint for GET /v1/org: the same authority the installation
|
||||
* diagnostics enforce. Advisory: lookup failures answer false, never block core.
|
||||
*/
|
||||
export async function canManageDeploymentServices(principal: AuthContextVariables): Promise<boolean> {
|
||||
export async function canManageDeploymentServices(principal: DeploymentPrincipal): Promise<boolean> {
|
||||
try {
|
||||
return await isLocalDeploymentOperator(principal)
|
||||
} catch {
|
||||
|
||||
@@ -97,11 +97,9 @@ export const resolveOrganizationContextMiddleware: MiddlewareHandler<{
|
||||
return c.json({ error: "organization_not_found" }, 404) as never
|
||||
}
|
||||
|
||||
// an organization that requires SSO opens only from a
|
||||
// session signed in through its SSO. API keys are issued from such a
|
||||
// session (POST /v1/api-keys runs behind this check), so they are not re-checked.
|
||||
if (!apiKey) {
|
||||
const ssoBlock = await findSsoAccessBlock({ sessionId: session?.id ?? null, organizationId: normalizedOrganizationId })
|
||||
const signInSessionId = c.get("signInSessionId")
|
||||
if (signInSessionId) {
|
||||
const ssoBlock = await findSsoAccessBlock({ sessionId: signInSessionId, organizationId: normalizedOrganizationId })
|
||||
if (ssoBlock) {
|
||||
return c.json(ssoRequiredErrorBody(ssoBlock), 403) as never
|
||||
}
|
||||
|
||||
@@ -87,12 +87,11 @@ export const resolveUserOrganizationsMiddleware: MiddlewareHandler<{
|
||||
? scopedOrgs[0]?.slug ?? null
|
||||
: resolved.activeOrgSlug
|
||||
|
||||
// never act in an organization that requires SSO from a
|
||||
// session that did not sign in through it. Fall back to the first
|
||||
// organization the session may open; the list itself stays complete so the
|
||||
// person can still choose it (and be sent through its SSO).
|
||||
if (!apiKey && activeOrganizationId) {
|
||||
const blocked = await findSsoBlockedOrganizations({ sessionId: session?.id ?? null, organizationIds: scopedOrgs.map((org) => org.id) })
|
||||
// For a sign-in session, fall back to the first organization it may open.
|
||||
// Keep the list complete so the person can still choose an SSO organization.
|
||||
const signInSessionId = c.get("signInSessionId")
|
||||
if (signInSessionId && activeOrganizationId) {
|
||||
const blocked = await findSsoBlockedOrganizations({ sessionId: signInSessionId, organizationIds: scopedOrgs.map((org) => org.id) })
|
||||
if (blocked.has(activeOrganizationId)) {
|
||||
const fallback = scopedOrganizationId ? null : scopedOrgs.find((org) => !blocked.has(org.id)) ?? null
|
||||
activeOrganizationId = fallback?.id ?? null
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
SsoConnectionTable,
|
||||
SsoProviderTable,
|
||||
} from "@openwork-ee/den-db/schema"
|
||||
import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
|
||||
import { normalizeDenTypeId, type DenTypeId } from "@openwork-ee/utils/typeid"
|
||||
import { db } from "./db.js"
|
||||
import { env } from "./env.js"
|
||||
import { ssoConnectionDisplayName, ssoDomainColumnCovers, ssoDomainsCover } from "./sso-domains.js"
|
||||
@@ -265,21 +265,21 @@ async function readSsoRequiredOrganizations(organizationIds: readonly string[]):
|
||||
}
|
||||
|
||||
/** When this session proved each organization's SSO (the identity provider's authentication time). */
|
||||
async function readSessionSsoProofs(sessionId: string): Promise<Map<string, Date>> {
|
||||
async function readSessionSsoProofs(sessionId: DenTypeId<"session">): Promise<Map<string, Date>> {
|
||||
// primary: the rows are written by the SSO callback that created the session.
|
||||
const rows = await db.$primary
|
||||
.select({ organizationId: SessionSsoProofTable.organizationId, authenticatedAt: SessionSsoProofTable.authenticatedAt })
|
||||
.from(SessionSsoProofTable)
|
||||
.where(eq(SessionSsoProofTable.sessionId, normalizeDenTypeId("session", sessionId)))
|
||||
.where(eq(SessionSsoProofTable.sessionId, sessionId))
|
||||
return new Map(rows.map((row) => [row.organizationId, row.authenticatedAt]))
|
||||
}
|
||||
|
||||
/**
|
||||
* Organizations among `organizationIds` this session may not open until it
|
||||
* signs in through their SSO. A request without a session (an API key,
|
||||
* an MCP token) is checked where that credential was issued instead.
|
||||
* Organizations among `organizationIds` this sign-in session may not open
|
||||
* until it signs in through their SSO. A missing session ID on a sign-in flow
|
||||
* has no proof. Agent and API key credentials do not call this gate on re-entry.
|
||||
*/
|
||||
export async function findSsoBlockedOrganizations(input: { sessionId: string | null; organizationIds: readonly string[] }): Promise<Map<string, SsoAccessBlock>> {
|
||||
export async function findSsoBlockedOrganizations(input: { sessionId: DenTypeId<"session"> | null; organizationIds: readonly string[] }): Promise<Map<string, SsoAccessBlock>> {
|
||||
const required = await readSsoRequiredOrganizations(input.organizationIds)
|
||||
const result = new Map<string, SsoAccessBlock>()
|
||||
if (required.size === 0) return result
|
||||
@@ -292,22 +292,21 @@ export async function findSsoBlockedOrganizations(input: { sessionId: string | n
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this session may turn on "Require SSO" (or restrict the domain) for
|
||||
* the organization without losing access to it: the organization has no
|
||||
* enabled SSO on a verified domain yet (nothing is enforced), or the session
|
||||
* has signed in through it.
|
||||
* Only a sign-in session may turn on "Require SSO" (or restrict the domain).
|
||||
* If SSO is already enabled on a verified domain, the session must have
|
||||
* signed in through it so the person won't lose access.
|
||||
*/
|
||||
export async function sessionCanRequireOrganizationSso(input: { sessionId: string | null; organizationId: string }) {
|
||||
export async function sessionCanRequireOrganizationSso(input: { sessionId: DenTypeId<"session"> | null; organizationId: string }) {
|
||||
if (!input.sessionId) return false
|
||||
const organizationId = normalizeDenTypeId("organization", input.organizationId)
|
||||
if (!(await readSsoPerOrganization([organizationId])).get(organizationId)) return true
|
||||
const rows = await readSsoOrganizations(eq(OrganizationTable.id, organizationId))
|
||||
const row = rows[0]
|
||||
if (!row) return true
|
||||
if (!input.sessionId) return false
|
||||
return (await readSessionSsoProofs(input.sessionId)).has(organizationId)
|
||||
}
|
||||
|
||||
export async function findSsoAccessBlock(input: { sessionId: string | null; organizationId: string | null | undefined }): Promise<SsoAccessBlock | null> {
|
||||
export async function findSsoAccessBlock(input: { sessionId: DenTypeId<"session"> | null; organizationId: string | null | undefined }): Promise<SsoAccessBlock | null> {
|
||||
if (!input.organizationId) return null
|
||||
const organizationId = normalizeDenTypeId("organization", input.organizationId)
|
||||
const blocked = await findSsoBlockedOrganizations({ sessionId: input.sessionId, organizationIds: [organizationId] })
|
||||
|
||||
@@ -509,7 +509,7 @@ export function registerDesktopAuthRoutes<T extends { Variables: AuthContextVari
|
||||
|
||||
// never hand a session to the desktop inside an
|
||||
// organization that requires SSO unless the session signed in through it.
|
||||
const ssoBlock = await findSsoAccessBlock({ sessionId: session.id, organizationId: activateOrganizationId ?? session.activeOrganizationId })
|
||||
const ssoBlock = await findSsoAccessBlock({ sessionId: c.get("signInSessionId"), organizationId: activateOrganizationId ?? session.activeOrganizationId })
|
||||
if (ssoBlock) {
|
||||
return c.json(ssoRequiredErrorBody(ssoBlock), 403)
|
||||
}
|
||||
|
||||
@@ -97,7 +97,7 @@ export function registerDeviceAuthRoutes<T extends { Variables: AuthContextVaria
|
||||
if (input.decision === "approve" && input.organizationId) {
|
||||
// the device session inherits this approval, so an
|
||||
// organization that requires SSO is approved only from an SSO session.
|
||||
const ssoBlock = await findSsoAccessBlock({ sessionId: c.get("session")?.id ?? null, organizationId: input.organizationId })
|
||||
const ssoBlock = await findSsoAccessBlock({ sessionId: c.get("signInSessionId"), organizationId: input.organizationId })
|
||||
if (ssoBlock) {
|
||||
return c.json(ssoRequiredErrorBody(ssoBlock), 403)
|
||||
}
|
||||
|
||||
@@ -347,8 +347,7 @@ export async function updateOrganizationAction(c: ResourceActionContext, payload
|
||||
// Requiring SSO takes effect at once for every member, the admin too:
|
||||
// only an admin signed in through it can turn it on, so nobody locks
|
||||
// themselves out of the organization by mistake.
|
||||
const session = c.get("session")
|
||||
if (!await sessionCanRequireOrganizationSso({ sessionId: session?.id ?? null, organizationId: payload.organization.id })) {
|
||||
if (!await sessionCanRequireOrganizationSso({ sessionId: c.get("signInSessionId") ?? null, organizationId: payload.organization.id })) {
|
||||
const signInPath = `/sso/${encodeURIComponent(payload.organization.slug)}`
|
||||
return c.json({
|
||||
error: "sso_session_required",
|
||||
|
||||
@@ -36,6 +36,6 @@ export function isDuplicateEntry(error: unknown): boolean {
|
||||
}
|
||||
|
||||
export type ResourceActionContext = Pick<Context, "json" | "body"> & {
|
||||
get: <K extends "apiKey" | "organizationContext" | "session">(key: K) => OrgRouteVariables[K]
|
||||
get: <K extends "apiKey" | "organizationContext" | "session" | "signInSessionId">(key: K) => OrgRouteVariables[K]
|
||||
}
|
||||
export type ResourceOrganizationContext = NonNullable<OrgRouteVariables["organizationContext"]>
|
||||
@@ -14,6 +14,7 @@ import { appLogger } from "./observability/logger.js"
|
||||
import { sessionRefreshDue } from "./session-security-settings.js"
|
||||
|
||||
type AuthSessionValue = {
|
||||
signInSessionId: CachedAuthSession["session"]["id"] | null
|
||||
user: CachedAuthSession["user"]
|
||||
session: Omit<CachedAuthSession["session"], "id" | "token"> & {
|
||||
id: string
|
||||
@@ -33,6 +34,8 @@ type SessionRequestContext = {
|
||||
}
|
||||
|
||||
export type AuthContextVariables = {
|
||||
/** Set only when authentication resolved a persisted Den sign-in session. */
|
||||
signInSessionId: AuthSessionValue["signInSessionId"]
|
||||
user: AuthSessionValue["user"] | null
|
||||
session: AuthSessionValue["session"] | null
|
||||
apiKey: DenApiKeySession | null
|
||||
@@ -225,6 +228,7 @@ async function getSessionFromInternalMcpPrincipal(headers: Headers): Promise<(Au
|
||||
...user,
|
||||
id: normalizeDenTypeId("user", user.id),
|
||||
},
|
||||
signInSessionId: null,
|
||||
session: {
|
||||
id: "mcp_internal",
|
||||
token: "mcp_internal",
|
||||
@@ -258,6 +262,7 @@ function readBearerToken(headers: Headers): string | null {
|
||||
|
||||
function bearerSessionValue(row: CachedAuthSession): AuthSessionValue {
|
||||
return {
|
||||
signInSessionId: row.session.id,
|
||||
session: row.session,
|
||||
user: {
|
||||
...row.user,
|
||||
@@ -481,10 +486,11 @@ export const sessionMiddleware: MiddlewareHandler<{ Variables: AuthContextVariab
|
||||
? null
|
||||
: await getSessionFromApiKey(c.req.raw.headers)
|
||||
const resolved = apiKeyResolution
|
||||
? { user: apiKeyResolution.user, session: null }
|
||||
? { user: apiKeyResolution.user, session: null, signInSessionId: null }
|
||||
: (skipRequestSession
|
||||
? null
|
||||
: await getRequestSession(c.req.raw.headers, c))
|
||||
c.set("signInSessionId", resolved?.signInSessionId ?? null)
|
||||
c.set("user", resolved?.user ?? null)
|
||||
c.set("session", resolved?.session ?? null)
|
||||
const activeOrganizationId = apiKeyResolution?.activeOrganizationId ?? resolved?.session?.activeOrganizationId
|
||||
|
||||
@@ -11,11 +11,12 @@
|
||||
* On multi-organization deployments, the organization's own settings decide:
|
||||
* - SSO set up, nothing required: SSO is offered first, the usual methods stay
|
||||
* available, and people on the domain can join other organizations.
|
||||
* - "Require SSO" (`requireSso`): the organization itself can only be opened
|
||||
* from a session signed in through its SSO. Sign-in is not blocked, so the
|
||||
* same person can still use other organizations.
|
||||
* - "Require SSO" (`requireSso`): a sign-in session can only open the
|
||||
* organization if it signed in through the organization's SSO. The same
|
||||
* person can still sign in another way to use other organizations.
|
||||
* - "Restrict this domain to our SSO" (`restrictDomainToSso`): the strict
|
||||
* behavior again, for every email on the verified domain, invitation or not.
|
||||
* Agent and API key credentials are governed by their own access controls.
|
||||
*/
|
||||
|
||||
export type OrganizationSsoPolicy = {
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
import assert from "node:assert/strict"
|
||||
import { after, before, test } from "node:test"
|
||||
import { eq } from "@openwork-ee/den-db/drizzle"
|
||||
import { OrganizationTable } from "@openwork-ee/den-db/schema"
|
||||
import { normalizeDenTypeId } from "@openwork-ee/utils/typeid"
|
||||
import { bootDen, field, summary, text, type Member } from "./harness.js"
|
||||
|
||||
const den = await bootDen()
|
||||
const { db } = await import("../../src/db.js")
|
||||
const { createInternalMcpPrincipalHeader } = await import("../../src/session.js")
|
||||
const { mintHeadlessRunMcpToken } = await import("../../src/mcp/headless-run-token-mint.js")
|
||||
after(() => den.close())
|
||||
|
||||
let owner: Member
|
||||
let orgId: string
|
||||
let desktopToken: string
|
||||
let apiKey: string
|
||||
|
||||
function internalHeaders() {
|
||||
return { "x-den-internal-mcp-principal": createInternalMcpPrincipalHeader({ userId: owner.userId, organizationId: orgId }) }
|
||||
}
|
||||
|
||||
before(async () => {
|
||||
const created = await den.createOrg(await den.signUp("SSO owner"), "SSO workspace")
|
||||
owner = created.owner
|
||||
orgId = created.orgId
|
||||
desktopToken = await den.mintMcpToken(owner, orgId)
|
||||
const key = await den.as(owner, orgId)("POST", "/v1/api-keys", { name: "Existing key" })
|
||||
assert.equal(key.status, 201, summary(key))
|
||||
apiKey = text(field(key.body, "key"), "API key")
|
||||
|
||||
const saml = await den.as(owner, orgId)("POST", "/v1/sso/saml", {
|
||||
issuer: `http://127.0.0.1/idp/${den.stamp}`,
|
||||
domain: `sso-${den.stamp}.test`,
|
||||
entryPoint: "https://login.example.test/saml2",
|
||||
cert: "idp-test-signing-certificate",
|
||||
audience: "http://127.0.0.1:8790",
|
||||
})
|
||||
assert.equal(saml.status, 201, summary(saml))
|
||||
await den.arrangeSsoConnectionEnabled(orgId)
|
||||
})
|
||||
|
||||
test("an agent cannot enable Require SSO without a real SSO session", async () => {
|
||||
const result = await den.request(null, "PATCH", "/v1/org", { headers: internalHeaders(), body: { requireSso: true } })
|
||||
assert.equal(result.status, 409, summary(result))
|
||||
assert.equal(field(result.body, "error"), "sso_session_required")
|
||||
})
|
||||
|
||||
test("Require SSO blocks interactive sessions without proof, not existing agent or key credentials", async (t) => {
|
||||
// Arrange a policy enabled by an SSO-signed-in owner; this fixture has no IdP.
|
||||
await db.update(OrganizationTable).set({ metadata: JSON.stringify({ requireSso: true }) })
|
||||
.where(eq(OrganizationTable.id, normalizeDenTypeId("organization", orgId)))
|
||||
|
||||
await t.test("browser session cannot open the organization or mint new sign-in credentials", async () => {
|
||||
const headers = { cookie: owner.cookie }
|
||||
const results = [
|
||||
await den.request(null, "GET", "/v1/org", { orgId, headers }),
|
||||
await den.request(null, "POST", "/v1/me/active-organization", { headers, body: { organizationId: orgId } }),
|
||||
await den.request(null, "POST", "/v1/auth/desktop-handoff", { headers, body: {} }),
|
||||
await den.request(null, "POST", "/v1/mcp/token", { orgId, headers, body: { scopes: ["mcp:read"] } }),
|
||||
]
|
||||
for (const result of results) {
|
||||
assert.equal(result.status, 403, summary(result))
|
||||
assert.equal(field(result.body, "error"), "sso_required")
|
||||
}
|
||||
})
|
||||
|
||||
await t.test("first-party MCP token reaches the organization", async () => {
|
||||
const result = await den.callMcpTool(desktopToken, "execute_capability", { name: "getOrg" })
|
||||
assert.equal(result.status, 200, result.raw)
|
||||
assert.equal(result.rpcError, null, result.raw)
|
||||
assert.equal(result.isError, false, result.raw)
|
||||
assert.equal(field(result.body, "organization", "id"), orgId, result.raw)
|
||||
})
|
||||
|
||||
await t.test("headless run token used by Workbot reaches the organization", async () => {
|
||||
const { token } = await mintHeadlessRunMcpToken({ userId: owner.userId, organizationId: orgId, readOnly: true })
|
||||
const result = await den.callMcpTool(token, "execute_capability", { name: "getOrg" })
|
||||
assert.equal(result.status, 200, result.raw)
|
||||
assert.equal(result.rpcError, null, result.raw)
|
||||
assert.equal(result.isError, false, result.raw)
|
||||
assert.equal(field(result.body, "organization", "id"), orgId, result.raw)
|
||||
})
|
||||
|
||||
for (const [label, headers] of Object.entries({ "Internal principal": internalHeaders(), "API key": { "x-api-key": apiKey } })) {
|
||||
await t.test(`${label} can open and list its organization`, async (t) => {
|
||||
await t.test("opens the organization", async () => {
|
||||
const org = await den.request(null, "GET", "/v1/org", { headers })
|
||||
assert.equal(org.status, 200, summary(org))
|
||||
assert.equal(field(org.body, "organization", "id"), orgId)
|
||||
})
|
||||
await t.test("keeps the organization active in the list", async () => {
|
||||
const orgs = await den.request(null, "GET", "/v1/me/orgs", { headers })
|
||||
assert.equal(orgs.status, 200, summary(orgs))
|
||||
assert.equal(field(orgs.body, "activeOrgId"), orgId)
|
||||
})
|
||||
})
|
||||
}
|
||||
})
|
||||
Reference in new issue
Block a user