commit f6c02605054acc8f99aa81699f505bbf2e610634
parent 639051eceba34bb7f930902fdb7566a2bccd0dd4
Author: finwo <finwo@pm.me>
Date: Wed, 21 Oct 2026 00:50:35 +0200
Add global client-to-realm mapping and realm-free OIDC routing
Diffstat:
10 files changed, 288 insertions(+), 64 deletions(-)
diff --git a/server/migrations/sqlite/system/004_client_mapping.sql b/server/migrations/sqlite/system/004_client_mapping.sql
@@ -0,0 +1,27 @@
+CREATE TABLE client_realms (
+ client_id TEXT PRIMARY KEY,
+ realm_id TEXT REFERENCES realms(id) ON DELETE CASCADE,
+ created_at INTEGER NOT NULL
+);
+
+CREATE INDEX client_realms_realm ON client_realms(realm_id);
+
+INSERT INTO client_realms (client_id, realm_id, created_at)
+SELECT client_id, realm_id, created_at
+ FROM oidc_client_hosts;
+
+CREATE TABLE oidc_client_hosts_new (
+ host TEXT PRIMARY KEY,
+ client_id TEXT NOT NULL REFERENCES client_realms(client_id) ON DELETE CASCADE,
+ created_at INTEGER NOT NULL
+);
+
+INSERT INTO oidc_client_hosts_new (host, client_id, created_at)
+SELECT host, client_id, created_at
+ FROM oidc_client_hosts;
+
+DROP TABLE oidc_client_hosts;
+
+ALTER TABLE oidc_client_hosts_new RENAME TO oidc_client_hosts;
+
+CREATE INDEX oidc_client_hosts_client ON oidc_client_hosts(client_id);
diff --git a/server/scripts/seed-demo.js b/server/scripts/seed-demo.js
@@ -3,10 +3,12 @@ import { loadConfig } from '../src/lib/config.js';
import { hashPassword } from '../src/lib/password.js';
import { hashClientSecret } from '../src/lib/oidc/clients.js';
import {
+ addClientRealm,
addOidcClientHost,
addRealmEmailDomain,
closeRealms,
createRealm,
+ findClientRealm,
findRealmBySlug,
getSystemDatabase,
initRealms,
@@ -119,6 +121,7 @@ async function ensureProviderDomain(db, domain, providerId) {
}
async function ensureClient(
+ realm,
db,
{
clientId,
@@ -133,6 +136,11 @@ async function ensureClient(
requirePkce = true,
}
) {
+ const mapping = await findClientRealm(clientId);
+ if (mapping && mapping.realm_id !== realm.id) {
+ throw new Error(`client id is already assigned: ${clientId}`);
+ }
+
let client = await db.get('SELECT id FROM oidc_clients WHERE client_id = {clientId}', { clientId });
if (!client) {
const now = Date.now();
@@ -163,6 +171,8 @@ async function ensureClient(
);
}
+ await addClientRealm(clientId, realm.id);
+
for (const slug of roles) {
const role = await db.get('SELECT id FROM roles WHERE slug = {slug}', { slug });
if (!role) continue;
@@ -245,26 +255,26 @@ const providerId = await ensureProvider(acmeDb, {
});
await ensureProviderDomain(acmeDb, 'sso.acme.test', providerId);
-await ensureClient(acmeDb, {
+await ensureClient(acme, acmeDb, {
clientId: 'internal-app',
name: 'Internal App',
accessMode: 'internal',
redirectUris: [`${clientOrigin('app.acme.localhost')}/callback`],
postLogoutRedirectUris: [`${clientOrigin('app.acme.localhost')}/`],
});
-await ensureClient(acmeDb, {
- clientId: 'members-app',
- name: 'Members App',
+await ensureClient(acme, acmeDb, {
+ clientId: 'acme-members-app',
+ name: 'Acme Members App',
accessMode: 'members',
redirectUris: [`${clientOrigin('members.localhost')}/callback`],
});
-await ensureClient(acmeDb, {
- clientId: 'public-app',
- name: 'Public App',
+await ensureClient(acme, acmeDb, {
+ clientId: 'acme-public-app',
+ name: 'Acme Public App',
accessMode: 'public',
redirectUris: [`${clientOrigin('public.localhost')}/callback`],
});
-await ensureClient(acmeDb, {
+await ensureClient(acme, acmeDb, {
clientId: 'confidential-app',
name: 'Confidential App',
accessMode: 'members',
@@ -274,27 +284,30 @@ await ensureClient(acmeDb, {
});
const globexDb = await openRealmDatabase(globex);
-await ensureClient(globexDb, {
- clientId: 'members-app',
- name: 'Members App',
+await ensureClient(globex, globexDb, {
+ clientId: 'globex-members-app',
+ name: 'Globex Members App',
accessMode: 'members',
redirectUris: [`${clientOrigin('members.localhost')}/callback`],
});
-await ensureClient(globexDb, {
- clientId: 'public-app',
- name: 'Public App',
+await ensureClient(globex, globexDb, {
+ clientId: 'globex-public-app',
+ name: 'Globex Public App',
accessMode: 'public',
redirectUris: [`${clientOrigin('public.localhost')}/callback`],
});
-await addOidcClientHost(acme.id, 'internal-app', 'app.acme.localhost');
+await addOidcClientHost('internal-app', 'app.acme.localhost');
console.log('seeded realms acme and globex');
console.log('password for all demo users: demo');
console.log('home users: alice@acme.test, it@acme.test, admin@system.test (system admin)');
console.log('guest users: guest@personal.test (acme), contractor@personal.test (globex realm-admin)');
console.log('upstream mapping: sso.acme.test -> Example SSO');
-console.log('clients: internal-app, members-app, public-app, confidential-app');
+console.log(
+ 'clients: internal-app, acme-members-app, acme-public-app, confidential-app, ' +
+ 'globex-members-app, globex-public-app'
+);
console.log('client host: app.acme.localhost -> acme/internal-app');
console.log('virtual clients: admin, account');
diff --git a/server/src/controller/oidc.js b/server/src/controller/oidc.js
@@ -461,7 +461,9 @@ export default {
name: 'oidc',
async handler(req, res, next) {
try {
- const context = await resolveOidcContext(req);
+ const context = await resolveOidcContext(req, {
+ publicUrl: app.config.server.public_url,
+ });
if (context.action === 'login' || context.action === 'callback') {
next();
return;
diff --git a/server/src/lib/oidc/context.js b/server/src/lib/oidc/context.js
@@ -1,8 +1,10 @@
import { HttpError } from '../http/http-error.js';
+import { isVirtualClient } from './clients.js';
import {
+ findClientRealm,
findOidcClientHost,
- findRealmBySlug,
findRealmHost,
+ normalizeHost,
} from '../realm.js';
export function requestOrigin(req) {
@@ -26,7 +28,7 @@ function pathSegments(req) {
.map((segment) => decodeURIComponent(segment));
}
-export async function resolveOidcContext(req) {
+export async function resolveOidcContext(req, { publicUrl } = {}) {
const segments = pathSegments(req);
const origin = requestOrigin(req);
@@ -50,34 +52,54 @@ export async function resolveOidcContext(req) {
const realmHost = await findRealmHost(req.headers.host);
if (realmHost) {
if (segments.length !== 2) throw new HttpError(404, 'not_found', 'Not found');
+ const clientId = segments[0];
+ if (!isVirtualClient(clientId)) {
+ const mapping = await findClientRealm(clientId);
+ if (!mapping || mapping.realm_id !== realmHost.id) {
+ throw new HttpError(404, 'unknown_client', 'Unknown client');
+ }
+ }
return {
mode: 'realm',
origin,
realm: realmHost,
- clientId: segments[0],
+ clientId,
action: segments[1],
};
}
- if (segments.length !== 3) throw new HttpError(404, 'not_found', 'Not found');
- const realm = await findRealmBySlug(segments[0]);
- if (!realm) throw new HttpError(404, 'unknown_realm', 'Unknown realm');
+ if (segments.length !== 2) throw new HttpError(404, 'not_found', 'Not found');
+
+ if (publicUrl) {
+ const canonicalHost = normalizeHost(new URL(publicUrl).host);
+ if (normalizeHost(req.headers.host) !== canonicalHost) {
+ throw new HttpError(404, 'not_found', 'Not found');
+ }
+ }
+
+ const clientId = segments[0];
+ const mapping = await findClientRealm(clientId);
+ if (!mapping || !mapping.realm_id) {
+ throw new HttpError(404, 'unknown_client', 'Unknown client');
+ }
return {
mode: 'canonical',
origin,
- realm,
- clientId: segments[1],
- action: segments[2],
+ realm: {
+ id: mapping.realm_id,
+ slug: mapping.slug,
+ db_file: mapping.db_file,
+ owner_user_id: mapping.owner_user_id,
+ },
+ clientId,
+ action: segments[1],
};
}
export function endpointBase(context) {
if (context.mode === 'client') return `${context.origin}/oidc`;
- if (context.mode === 'realm') return `${context.origin}/oidc/${encodeURIComponent(context.clientId)}`;
- return `${context.origin}/oidc/${encodeURIComponent(context.realm.slug)}/${encodeURIComponent(
- context.clientId
- )}`;
+ return `${context.origin}/oidc/${encodeURIComponent(context.clientId)}`;
}
export function endpointUrls(context) {
diff --git a/server/src/lib/realm.js b/server/src/lib/realm.js
@@ -173,7 +173,8 @@ export async function resolveRealm({ host, slug } = {}) {
const byClientHost = await systemDb.get(
`SELECT r.id, r.slug, r.db_file, r.owner_user_id
FROM oidc_client_hosts h
- JOIN realms r ON r.id = h.realm_id
+ JOIN client_realms cr ON cr.client_id = h.client_id
+ JOIN realms r ON r.id = cr.realm_id
WHERE h.host = {host}`,
{ host: normalizedHost }
);
@@ -280,16 +281,49 @@ export async function addRealmHost(realmId, host) {
);
}
-export async function addOidcClientHost(realmId, clientId, host) {
+export async function addClientRealm(clientId, realmId) {
+ if (!systemDb) throw new Error('realm registry is not initialized');
+ const value = String(clientId || '').trim();
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(value)) {
+ throw new Error(`invalid client id: ${JSON.stringify(clientId)}`);
+ }
+ const existing = await findClientRealm(value);
+ if (existing) {
+ if (existing.realm_id === realmId) return existing;
+ throw new Error(`client id is already assigned: ${value}`);
+ }
+ await systemDb.run(
+ 'INSERT INTO client_realms (client_id, realm_id, created_at) VALUES ({clientId}, {realmId}, {createdAt})',
+ { clientId: value, realmId, createdAt: Date.now() }
+ );
+ return findClientRealm(value);
+}
+
+export async function findClientRealm(clientId) {
+ if (!systemDb) throw new Error('realm registry is not initialized');
+ return systemDb.get(
+ `SELECT cr.client_id, cr.realm_id, r.slug, r.db_file, r.owner_user_id
+ FROM client_realms cr
+ LEFT JOIN realms r ON r.id = cr.realm_id
+ WHERE cr.client_id = {clientId}`,
+ { clientId }
+ );
+}
+
+export async function addOidcClientHost(clientId, host) {
if (!systemDb) throw new Error('realm registry is not initialized');
const normalized = normalizeHost(host);
if (!normalized || normalized !== String(host).trim().toLowerCase()) {
throw new Error(`invalid client hostname: ${JSON.stringify(host)}`);
}
+ const mapping = await findClientRealm(clientId);
+ if (!mapping || !mapping.realm_id) {
+ throw new Error(`unknown client: ${clientId}`);
+ }
await systemDb.run(
- `INSERT INTO oidc_client_hosts (host, realm_id, client_id, created_at)
- VALUES ({host}, {realmId}, {clientId}, {createdAt})`,
- { host: normalized, realmId, clientId, createdAt: Date.now() }
+ `INSERT INTO oidc_client_hosts (host, client_id, created_at)
+ VALUES ({host}, {clientId}, {createdAt})`,
+ { host: normalized, clientId, createdAt: Date.now() }
);
}
@@ -298,9 +332,10 @@ export async function findOidcClientHost(host) {
const normalized = normalizeHost(host);
if (!normalized) return null;
return systemDb.get(
- `SELECT h.host, h.realm_id, h.client_id, r.slug, r.db_file, r.owner_user_id
+ `SELECT h.host, h.client_id, cr.realm_id, r.slug, r.db_file, r.owner_user_id
FROM oidc_client_hosts h
- JOIN realms r ON r.id = h.realm_id
+ JOIN client_realms cr ON cr.client_id = h.client_id
+ JOIN realms r ON r.id = cr.realm_id
WHERE h.host = {host}`,
{ host: normalized }
);
diff --git a/server/test/http.test.js b/server/test/http.test.js
@@ -199,14 +199,14 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
await t.test('client discovery works on identity, realm and client hosts', async () => {
const canonical = await identity({
- path: '/oidc/acme/internal-app/openid-configuration',
+ path: '/oidc/internal-app/openid-configuration',
});
assert.equal(canonical.status, 200);
assert.equal(canonical.json.client_id, 'internal-app');
assert.equal(canonical.json.issuer, `${publicUrl}/oidc/acme`);
assert.equal(
canonical.json.authorization_endpoint,
- `${origin('identity.test')}/oidc/acme/internal-app/authorize`
+ `${origin('identity.test')}/oidc/internal-app/authorize`
);
const realmHost = await acme({ path: '/oidc/internal-app/openid-configuration' });
@@ -222,6 +222,36 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(clientHost.json.token_endpoint, `${origin('app.acme.localhost')}/oidc/token`);
});
+ await t.test('realm slugs are not accepted in OIDC paths', async () => {
+ const oldCanonical = await identity({
+ path: '/oidc/acme/internal-app/openid-configuration',
+ });
+ assert.equal(oldCanonical.status, 404);
+
+ const oldRealmHost = await acme({
+ path: '/oidc/acme/internal-app/openid-configuration',
+ });
+ assert.equal(oldRealmHost.status, 404);
+ });
+
+ await t.test('client-to-realm mappings enforce host and canonical routing', async () => {
+ const mismatch = await globex({ path: '/oidc/internal-app/openid-configuration' });
+ assert.equal(mismatch.status, 404);
+ assert.equal(mismatch.json.error.code, 'unknown_client');
+
+ const unknownCanonicalHost = await request(port, {
+ host: `unknown.test:${port}`,
+ path: '/oidc/internal-app/openid-configuration',
+ });
+ assert.equal(unknownCanonicalHost.status, 404);
+
+ const otherRealm = await identity({
+ path: '/oidc/globex-members-app/openid-configuration',
+ });
+ assert.equal(otherRealm.status, 200);
+ assert.equal(otherRealm.json.issuer, `${publicUrl}/oidc/globex`);
+ });
+
await t.test('virtual clients are discoverable', async () => {
const admin = await acme({ path: '/oidc/admin/openid-configuration' });
assert.equal(admin.status, 200);
@@ -298,14 +328,22 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
const denied = await acme({
method: 'POST',
path: '/api/v1/login/password',
- body: { client_id: 'members-app', identifier: 'contractor@personal.test', password: 'demo' },
+ body: {
+ client_id: 'acme-members-app',
+ identifier: 'contractor@personal.test',
+ password: 'demo',
+ },
});
assert.equal(denied.status, 401);
const allowed = await acme({
method: 'POST',
path: '/api/v1/login/password',
- body: { client_id: 'public-app', identifier: 'guest@personal.test', password: 'demo' },
+ body: {
+ client_id: 'acme-public-app',
+ identifier: 'guest@personal.test',
+ password: 'demo',
+ },
});
assert.equal(allowed.status, 200);
});
@@ -324,7 +362,11 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
const response = await globex({
method: 'POST',
path: '/api/v1/login/password',
- body: { client_id: 'members-app', identifier: 'contractor@personal.test', password: 'demo' },
+ body: {
+ client_id: 'globex-members-app',
+ identifier: 'contractor@personal.test',
+ password: 'demo',
+ },
});
assert.equal(response.status, 200);
const session = await globex({
@@ -413,11 +455,60 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(reuse.json.error, 'invalid_grant');
});
+ await t.test('canonical realm-client flow resolves the realm from its mapping', async () => {
+ const { verifier, challenge } = pkce();
+ const redirectUri = `${origin('app.acme.localhost')}/callback`;
+ const authorizePath =
+ `/oidc/internal-app/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
+ `&state=state-canonical&code_challenge=${challenge}&code_challenge_method=S256`;
+
+ const first = await identity({ path: authorizePath });
+ assert.equal(first.status, 302);
+ assert.equal(locationQuery(first).pathname, '/oidc/internal-app/login');
+ let jar = mergeCookies('', first);
+
+ const login = await identity({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: {
+ realm: 'acme',
+ client_id: 'internal-app',
+ identifier: 'alice@acme.test',
+ password: 'demo',
+ },
+ cookie: jar,
+ });
+ assert.equal(login.status, 200);
+ assert.equal(login.json.pending_auth_request, true);
+ jar = mergeCookies(jar, login);
+
+ const second = await identity({ path: authorizePath, cookie: jar });
+ assert.equal(second.status, 302);
+ const redirected = locationQuery(second);
+ assert.equal(redirected.searchParams.get('state'), 'state-canonical');
+ const code = redirected.searchParams.get('code');
+ assert.ok(code);
+
+ const tokenResponse = await identity({
+ method: 'POST',
+ path: '/oidc/internal-app/token',
+ form: {
+ grant_type: 'authorization_code',
+ code,
+ redirect_uri: redirectUri,
+ client_id: 'internal-app',
+ code_verifier: verifier,
+ },
+ });
+ assert.equal(tokenResponse.status, 200);
+ });
+
await t.test('public clients allow non-members through authorize', async () => {
const { verifier, challenge } = pkce();
const redirectUri = `${origin('public.localhost')}/callback`;
const authorizePath =
- `/oidc/public-app/authorize?response_type=code&client_id=public-app` +
+ `/oidc/acme-public-app/authorize?response_type=code&client_id=acme-public-app` +
`&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
`&state=state-2&code_challenge=${challenge}&code_challenge_method=S256`;
@@ -428,7 +519,11 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
const login = await acme({
method: 'POST',
path: '/api/v1/login/password',
- body: { client_id: 'public-app', identifier: 'contractor@personal.test', password: 'demo' },
+ body: {
+ client_id: 'acme-public-app',
+ identifier: 'contractor@personal.test',
+ password: 'demo',
+ },
cookie: jar,
});
assert.equal(login.status, 200);
@@ -442,12 +537,12 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
const tokenResponse = await acme({
method: 'POST',
- path: '/oidc/public-app/token',
+ path: '/oidc/acme-public-app/token',
form: {
grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
- client_id: 'public-app',
+ client_id: 'acme-public-app',
code_verifier: verifier,
},
});
@@ -541,7 +636,11 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
const globexLogin = await globex({
method: 'POST',
path: '/api/v1/login/password',
- body: { client_id: 'members-app', identifier: 'contractor@personal.test', password: 'demo' },
+ body: {
+ client_id: 'globex-members-app',
+ identifier: 'contractor@personal.test',
+ password: 'demo',
+ },
});
const globexCookie = mergeCookies('', globexLogin);
diff --git a/server/test/realm.test.js b/server/test/realm.test.js
@@ -6,9 +6,13 @@ import os from 'node:os';
import path from 'node:path';
import { findManagedProviderForUser, resolveLogin } from '../src/lib/login.js';
import {
+ addClientRealm,
+ addOidcClientHost,
addRealmEmailDomain,
closeRealms,
createRealm,
+ findClientRealm,
+ findOidcClientHost,
findRealmByEmailDomain,
getSystemDatabase,
initRealms,
@@ -65,6 +69,43 @@ test('realm resolution prefers hostname and rejects a mismatched slug', async ()
}
});
+test('client IDs are globally unique and client hosts resolve through mappings', async () => {
+ const { dir, cfg } = await tempConfig();
+ try {
+ await initRealms(cfg);
+ const acme = await createRealm({ slug: 'acme', displayName: 'Acme' });
+ const globex = await createRealm({ slug: 'globex', displayName: 'Globex' });
+
+ await addClientRealm('shared-app', acme.id);
+ const mapping = await findClientRealm('shared-app');
+ assert.equal(mapping.realm_id, acme.id);
+ assert.equal(mapping.slug, 'acme');
+
+ await assert.rejects(
+ () => addClientRealm('shared-app', globex.id),
+ /already assigned/
+ );
+ await assert.rejects(() => addClientRealm('Bad App', acme.id), /invalid client id/);
+
+ await addOidcClientHost('shared-app', 'app.acme.localhost');
+ const clientHost = await findOidcClientHost('app.acme.localhost:3000');
+ assert.equal(clientHost.client_id, 'shared-app');
+ assert.equal(clientHost.realm_id, acme.id);
+ assert.equal(clientHost.slug, 'acme');
+
+ const realm = await resolveRealm({ host: 'app.acme.localhost' });
+ assert.equal(realm.id, acme.id);
+
+ await assert.rejects(
+ () => addOidcClientHost('missing-app', 'app.missing.localhost'),
+ /unknown client/
+ );
+ } finally {
+ await closeRealms();
+ await fs.rm(dir, { recursive: true, force: true });
+ }
+});
+
test('owned email domains select their realm provider mapping', async () => {
const { dir, cfg } = await tempConfig();
try {
diff --git a/server/web/src/main.ts b/server/web/src/main.ts
@@ -3,13 +3,6 @@ import { Admin } from './screen/admin';
import { Login } from './screen/login';
const routes: m.RouteDefs = {
- '/oidc/:realm/:clientId/login': {
- render: (vnode) =>
- m(Login, {
- realm: (vnode.attrs as any).realm,
- clientId: (vnode.attrs as any).clientId,
- }),
- },
'/oidc/:clientId/login': {
render: (vnode) => m(Login, { clientId: (vnode.attrs as any).clientId }),
},
diff --git a/server/web/src/screen/login.tsx b/server/web/src/screen/login.tsx
@@ -64,7 +64,7 @@ export const Login: m.Component<{ realm?: string; clientId?: string }> = {
async loadClient(this: any) {
this.error = null;
try {
- const discovery = await getClientDiscovery(this.realmSlug, this.clientId);
+ const discovery = await getClientDiscovery(this.clientId);
this.discovery = discovery;
this.realmSlug = discovery.realm;
this.clientId = discovery.client_id;
diff --git a/server/web/src/util/api.ts b/server/web/src/util/api.ts
@@ -85,15 +85,7 @@ export function getRealm(realm?: string | null): Promise<RealmInfo> {
return request<RealmInfo>(`/api/v1/realm${query}`);
}
-export function getClientDiscovery(
- realm?: string | null,
- clientId?: string | null
-): Promise<ClientDiscovery> {
- if (realm && clientId) {
- return request<ClientDiscovery>(
- `/oidc/${encodeURIComponent(realm)}/${encodeURIComponent(clientId)}/openid-configuration`
- );
- }
+export function getClientDiscovery(clientId?: string | null): Promise<ClientDiscovery> {
if (clientId) {
return request<ClientDiscovery>(`/oidc/${encodeURIComponent(clientId)}/openid-configuration`);
}