diff --git a/server/dev-server.mjs b/server/dev-server.mjs index e7eb48a..05ba0c0 100644 --- a/server/dev-server.mjs +++ b/server/dev-server.mjs @@ -1,6 +1,6 @@ import express from "express"; import { createServer as createHttpServer } from "node:http"; -import { randomBytes, randomUUID, createHash, timingSafeEqual } from "node:crypto"; +import { randomBytes, randomUUID, createHash } from "node:crypto"; import { existsSync, readFileSync } from "node:fs"; import { mkdir, writeFile } from "node:fs/promises"; import { dirname, extname, isAbsolute, join, resolve } from "node:path"; @@ -8,6 +8,11 @@ import { fileURLToPath } from "node:url"; import { createRemoteJWKSet, jwtVerify } from "jose"; import { createAuthentikSyncClient, resolveRequiredGroups } from "./authentik-sync.mjs"; import { createControlPlaneStore } from "./control-plane-store.mjs"; +import { resolveDeviceCoreSessionAccess } from "./device-core-session-access.mjs"; +import { + isInternalRequestTokenAuthorized, + isInternalRequestTokenConfigured, +} from "./internal-request-auth.mjs"; import { createNotificationCoreClient } from "./notification-core-client.mjs"; const serverRoot = dirname(fileURLToPath(import.meta.url)); @@ -68,6 +73,7 @@ app.get("/healthz", (_req, res) => { oidcConfigured: config.oidcConfigured, authentikApiConfigured: authentikSyncClient.isConfigured(), internalAccessApiConfigured: Boolean(config.internalAccessToken), + deviceCoreInternalAccessConfigured: Boolean(config.deviceCoreInternalAccessToken), notificationCoreConfigured: notificationCoreClient.isConfigured(), }); }); @@ -454,16 +460,17 @@ app.get("/api/services/:serviceSlug/launch", requireSession, (req, res) => { }); app.post("/api/internal/handoff/consume", (req, res) => { - if (!isInternalRequestAuthorized(req)) { - res.status(config.internalAccessToken ? 401 : 503).json({ + const serviceSlug = sanitizeServiceSlug(req.body?.serviceSlug); + if (!isInternalRequestAuthorized(req, { serviceSlug })) { + const configured = isInternalRequestConfigured(serviceSlug); + res.status(configured ? 401 : 503).json({ ok: false, - error: config.internalAccessToken ? "internal_handoff_unauthorized" : "internal_handoff_not_configured", + error: configured ? "internal_handoff_unauthorized" : "internal_handoff_not_configured", }); return; } const token = typeof req.body?.token === "string" ? req.body.token : ""; - const serviceSlug = sanitizeServiceSlug(req.body?.serviceSlug); const handoff = consumeServiceHandoff(token, serviceSlug); if (!handoff) { @@ -488,6 +495,7 @@ app.post("/api/internal/handoff/consume", (req, res) => { ok: true, serviceSlug, launcherSessionId: handoff.launcherSessionId ?? null, + access: resolveDeviceCoreSessionAccess(snapshot.data, user, serviceSlug), user: { id: user.id, email: user.email, @@ -501,16 +509,17 @@ app.post("/api/internal/handoff/consume", (req, res) => { }); app.post("/api/internal/session/validate", (req, res) => { - if (!isInternalRequestAuthorized(req)) { - res.status(config.internalAccessToken ? 401 : 503).json({ + const serviceSlug = sanitizeServiceSlug(req.body?.serviceSlug); + if (!isInternalRequestAuthorized(req, { serviceSlug })) { + const configured = isInternalRequestConfigured(serviceSlug); + res.status(configured ? 401 : 503).json({ ok: false, active: false, - error: config.internalAccessToken ? "internal_session_unauthorized" : "internal_session_not_configured", + error: configured ? "internal_session_unauthorized" : "internal_session_not_configured", }); return; } - const serviceSlug = sanitizeServiceSlug(req.body?.serviceSlug); const launcherSessionId = typeof req.body?.launcherSessionId === "string" ? req.body.launcherSessionId : ""; if (!launcherSessionId) { @@ -551,6 +560,7 @@ app.post("/api/internal/session/validate", (req, res) => { active: true, serviceSlug, launcherSessionId, + access: resolveDeviceCoreSessionAccess(snapshot.data, user, serviceSlug), user: { id: user.id, email: user.email, @@ -2531,6 +2541,9 @@ function readConfig() { process.env.NODEDC_INTERNAL_ACCESS_TOKEN ?? process.env.NODEDC_PLATFORM_SERVICE_TOKEN ?? "", + deviceCoreInternalAccessToken: readSecretFile( + process.env.NODEDC_DEVICE_CORE_INTERNAL_TOKEN_FILE, + ), taskLogoutUrl: process.env.TASK_LOGOUT_URL ?? `${(process.env.TASK_BASE_URL ?? `http://${process.env.TASK_DOMAIN ?? "task.local.nodedc"}`).replace(/\/$/, "")}/logout`, @@ -2549,6 +2562,13 @@ function readConfig() { }; } +function readSecretFile(value) { + const pathname = String(value || "").trim(); + if (!pathname) return ""; + const resolvedPath = isAbsolute(pathname) ? pathname : resolve(projectRoot, pathname); + return readFileSync(resolvedPath, "utf8").trim(); +} + function ensureOidcConfigured() { if (!config.oidcConfigured) { throw new Error("Launcher OIDC is not configured. Set LAUNCHER_OIDC_ISSUER, LAUNCHER_OIDC_CLIENT_ID and LAUNCHER_OIDC_CLIENT_SECRET."); @@ -4883,28 +4903,24 @@ function readRequestHeader(req, name) { return typeof value === "string" ? value.trim() : ""; } -function isInternalRequestAuthorized(req) { - if (!config.internalAccessToken) { - return false; - } - +function isInternalRequestAuthorized(req, { serviceSlug = "" } = {}) { const authorization = typeof req.headers.authorization === "string" ? req.headers.authorization : ""; - const bearerToken = authorization.match(/^Bearer\s+(.+)$/i)?.[1] ?? ""; const headerToken = typeof req.headers["x-nodedc-internal-token"] === "string" ? req.headers["x-nodedc-internal-token"] : ""; - const requestToken = bearerToken || headerToken; - - return safeTokenEquals(requestToken, config.internalAccessToken); + return isInternalRequestTokenAuthorized({ + authorization, + headerToken, + globalToken: config.internalAccessToken, + scopedToken: config.deviceCoreInternalAccessToken, + serviceSlug, + }); } -function safeTokenEquals(actual, expected) { - if (!actual || !expected) { - return false; - } - - const actualBuffer = Buffer.from(String(actual)); - const expectedBuffer = Buffer.from(String(expected)); - - return actualBuffer.length === expectedBuffer.length && timingSafeEqual(actualBuffer, expectedBuffer); +function isInternalRequestConfigured(serviceSlug = "") { + return isInternalRequestTokenConfigured({ + globalToken: config.internalAccessToken, + scopedToken: config.deviceCoreInternalAccessToken, + serviceSlug, + }); } function findInternalAccessUser(data, payload) { diff --git a/server/device-core-session-access.mjs b/server/device-core-session-access.mjs new file mode 100644 index 0000000..3eb34a6 --- /dev/null +++ b/server/device-core-session-access.mjs @@ -0,0 +1,102 @@ +const administrativeMembershipRoles = new Set(["client_owner", "client_admin"]); +const administrativeAppRoles = new Set(["owner", "admin"]); +const appRoleWeights = Object.freeze({ viewer: 10, member: 20, admin: 30, owner: 40 }); + +export function resolveDeviceCoreSessionAccess(data, user, serviceSlug = "device-core") { + const empty = Object.freeze({ allowed: false, hubRole: "viewer", ownerScopes: Object.freeze([]) }); + if (!data || !user || user.globalStatus !== "active") return empty; + + const service = data.services?.find((candidate) => candidate.slug === serviceSlug); + if (!service || service.status !== "active") return empty; + if (hasUserException(data, user.id, service.id, "deny")) return empty; + + const ownerScopes = []; + const roles = []; + const isRoot = user.id === "user_root"; + const directGrant = activeGrant(data, service.id, "user", user.id); + const explicitlyAllowed = hasUserException(data, user.id, service.id, "allow"); + + if (isRoot) { + roles.push("owner"); + } else if (explicitlyAllowed) { + roles.push("member"); + } else if (directGrant) { + roles.push(directGrant.appRole); + } + + for (const membership of data.memberships ?? []) { + if (membership.userId !== user.id || membership.status !== "active") continue; + const client = data.clients?.find((candidate) => candidate.id === membership.clientId); + if (!client || ["suspended", "expired"].includes(client.status)) continue; + + const clientGroupIds = new Set( + (data.groups ?? []) + .filter((group) => group.clientId === client.id && group.memberIds?.includes(user.id)) + .map((group) => group.id), + ); + const groupGrant = (data.grants ?? []).find((grant) => + grant.serviceId === service.id + && grant.targetType === "group" + && clientGroupIds.has(grant.targetId) + && grant.status === "active"); + const clientGrant = activeGrant(data, service.id, "client", client.id); + const scopedGrant = groupGrant || clientGrant; + + if (!explicitlyAllowed && scopedGrant) roles.push(scopedGrant.appRole); + if ( + client.type === "company" + && administrativeMembershipRoles.has(membership.role) + && (isRoot || (!explicitlyAllowed && administrativeAppRoles.has(scopedGrant?.appRole))) + ) { + ownerScopes.push({ + scopeKind: "company", + ownerRef: `client:${client.id}`, + displayName: String(client.name || client.legalName || client.id).trim().slice(0, 240), + }); + } + } + + const hubRole = strongestRole(roles); + if (!hubRole) return empty; + if (administrativeAppRoles.has(hubRole)) { + ownerScopes.push({ + scopeKind: "personal", + ownerRef: `user:${user.id}`, + displayName: String(user.name || user.email || user.id).trim().slice(0, 240), + }); + } + + return Object.freeze({ + allowed: true, + hubRole, + ownerScopes: Object.freeze(uniqueOwnerScopes(ownerScopes)), + }); +} + +function activeGrant(data, serviceId, targetType, targetId) { + return (data.grants ?? []).find((grant) => + grant.serviceId === serviceId + && grant.targetType === targetType + && grant.targetId === targetId + && grant.status === "active") ?? null; +} + +function hasUserException(data, userId, serviceId, type) { + return (data.exceptions ?? []).some((exception) => + exception.serviceId === serviceId + && exception.userId === userId + && exception.type === type); +} + +function strongestRole(roles) { + return roles + .filter((role) => Object.hasOwn(appRoleWeights, role)) + .sort((left, right) => appRoleWeights[right] - appRoleWeights[left])[0] ?? null; +} + +function uniqueOwnerScopes(scopes) { + const byIdentity = new Map(); + for (const scope of scopes) byIdentity.set(`${scope.scopeKind}\0${scope.ownerRef}`, scope); + return [...byIdentity.values()].sort((left, right) => + `${left.scopeKind}:${left.ownerRef}`.localeCompare(`${right.scopeKind}:${right.ownerRef}`)); +} diff --git a/server/device-core-session-access.test.mjs b/server/device-core-session-access.test.mjs new file mode 100644 index 0000000..1e64c81 --- /dev/null +++ b/server/device-core-session-access.test.mjs @@ -0,0 +1,124 @@ +import { describe, expect, it } from "vitest"; + +import { resolveDeviceCoreSessionAccess } from "./device-core-session-access.mjs"; + +const service = { + id: "service_device_core", + slug: "device-core", + status: "active", +}; +const user = { + id: "user_device_admin", + email: "admin@example.test", + name: "Device Admin", + globalStatus: "active", +}; +const company = { + id: "client_dctouch", + type: "company", + name: "DC Touch", + status: "active", +}; +const membership = { + id: "membership_device_admin", + clientId: company.id, + userId: user.id, + role: "client_admin", + status: "active", +}; + +function data(overrides = {}) { + return { + services: [service], + users: [user], + clients: [company], + memberships: [membership], + groups: [], + grants: [{ + id: "grant_device_core_dctouch", + serviceId: service.id, + targetType: "client", + targetId: company.id, + appRole: "admin", + status: "active", + }], + exceptions: [], + ...overrides, + }; +} + +describe("Device Core trusted session access", () => { + it("projects an administrative company scope only from an active scoped grant", () => { + expect(resolveDeviceCoreSessionAccess(data(), user)).toEqual({ + allowed: true, + hubRole: "admin", + ownerScopes: [ + { + scopeKind: "company", + ownerRef: "client:client_dctouch", + displayName: "DC Touch", + }, + { + scopeKind: "personal", + ownerRef: "user:user_device_admin", + displayName: "Device Admin", + }, + ], + }); + }); + + it("does not turn company membership alone into a Device Core owner claim", () => { + const access = resolveDeviceCoreSessionAccess(data({ grants: [] }), user); + expect(access).toEqual({ allowed: false, hubRole: "viewer", ownerScopes: [] }); + }); + + it("keeps member and viewer grants out of administrative owner scopes", () => { + for (const appRole of ["member", "viewer"]) { + const access = resolveDeviceCoreSessionAccess(data({ + grants: [{ + id: `grant_${appRole}`, + serviceId: service.id, + targetType: "client", + targetId: company.id, + appRole, + status: "active", + }], + }), user); + expect(access.allowed).toBe(true); + expect(access.hubRole).toBe(appRole); + expect(access.ownerScopes).toEqual([]); + } + }); + + it("fails closed on a deny exception even when grants exist", () => { + expect(resolveDeviceCoreSessionAccess(data({ + exceptions: [{ + id: "deny_device_core", + serviceId: service.id, + userId: user.id, + type: "deny", + }], + }), user)).toEqual({ allowed: false, hubRole: "viewer", ownerScopes: [] }); + }); + + it("keeps an individual allow exception at member privilege", () => { + expect(resolveDeviceCoreSessionAccess(data({ + exceptions: [{ + id: "allow_device_core", + serviceId: service.id, + userId: user.id, + type: "allow", + }], + }), user)).toEqual({ allowed: true, hubRole: "member", ownerScopes: [] }); + }); + + it("does not leak a grant from one company into another company scope", () => { + const secondCompany = { ...company, id: "client_other", name: "Other Company" }; + const secondMembership = { ...membership, id: "membership_other", clientId: secondCompany.id }; + const access = resolveDeviceCoreSessionAccess(data({ + clients: [company, secondCompany], + memberships: [membership, secondMembership], + }), user); + expect(access.ownerScopes.some((scope) => scope.ownerRef === "client:client_other")).toBe(false); + }); +}); diff --git a/server/internal-request-auth.mjs b/server/internal-request-auth.mjs new file mode 100644 index 0000000..3db3f6e --- /dev/null +++ b/server/internal-request-auth.mjs @@ -0,0 +1,33 @@ +import { timingSafeEqual } from "node:crypto"; + +export function isInternalRequestTokenAuthorized({ + authorization = "", + headerToken = "", + globalToken = "", + scopedToken = "", + serviceSlug = "", + scopedServiceSlug = "device-core", +} = {}) { + const bearerToken = String(authorization).match(/^Bearer\s+(.+)$/i)?.[1] ?? ""; + const requestToken = bearerToken || String(headerToken || ""); + if (safeTokenEquals(requestToken, globalToken)) return true; + return serviceSlug === scopedServiceSlug + && safeTokenEquals(requestToken, scopedToken); +} + +export function isInternalRequestTokenConfigured({ + globalToken = "", + scopedToken = "", + serviceSlug = "", + scopedServiceSlug = "device-core", +} = {}) { + return Boolean(globalToken || (serviceSlug === scopedServiceSlug && scopedToken)); +} + +function safeTokenEquals(actual, expected) { + if (!actual || !expected) return false; + const actualBuffer = Buffer.from(String(actual)); + const expectedBuffer = Buffer.from(String(expected)); + return actualBuffer.length === expectedBuffer.length + && timingSafeEqual(actualBuffer, expectedBuffer); +} diff --git a/server/internal-request-auth.test.mjs b/server/internal-request-auth.test.mjs new file mode 100644 index 0000000..207abef --- /dev/null +++ b/server/internal-request-auth.test.mjs @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; + +import { + isInternalRequestTokenAuthorized, + isInternalRequestTokenConfigured, +} from "./internal-request-auth.mjs"; + +describe("scoped internal request authorization", () => { + it("accepts the Device Core key only for Device Core handoff calls", () => { + const base = { + authorization: "Bearer device-core-file-token", + globalToken: "broad-platform-token", + scopedToken: "device-core-file-token", + }; + expect(isInternalRequestTokenAuthorized({ ...base, serviceSlug: "device-core" })).toBe(true); + expect(isInternalRequestTokenAuthorized({ ...base, serviceSlug: "module-foundry" })).toBe(false); + expect(isInternalRequestTokenAuthorized(base)).toBe(false); + }); + + it("keeps the existing global token valid for existing internal callers", () => { + expect(isInternalRequestTokenAuthorized({ + authorization: "Bearer broad-platform-token", + globalToken: "broad-platform-token", + scopedToken: "device-core-file-token", + serviceSlug: "module-foundry", + })).toBe(true); + }); + + it("reports scoped configuration only for the bound service", () => { + expect(isInternalRequestTokenConfigured({ + scopedToken: "device-core-file-token", + serviceSlug: "device-core", + })).toBe(true); + expect(isInternalRequestTokenConfigured({ + scopedToken: "device-core-file-token", + serviceSlug: "operational-core", + })).toBe(false); + }); +});