diff --git a/server/authentik-sync.service-groups.test.mjs b/server/authentik-sync.service-groups.test.mjs new file mode 100644 index 0000000..c38209d --- /dev/null +++ b/server/authentik-sync.service-groups.test.mjs @@ -0,0 +1,86 @@ +import { describe, expect, it } from "vitest"; +import { resolveRequiredGroups } from "./authentik-sync.mjs"; + +const user = { + id: "user_device_engineer", + email: "engineer@example.test", + name: "Device Engineer", + globalStatus: "active", +}; +const client = { id: "client_dctouch", status: "active" }; +const membership = { + id: "membership_device_engineer", + clientId: client.id, + userId: user.id, + role: "member", + status: "active", +}; +const service = { + id: "service_device_core_contract", + slug: "device-core", + status: "active", + authentikApplicationSlug: "device-core", + authentikGroupName: "nodedc:device-core:access", +}; + +function data(grants = [], exceptions = []) { + return { + users: [user], + clients: [client], + memberships: [membership], + groups: [], + services: [service], + grants, + exceptions, + }; +} + +describe("generic service Authentik group projection", () => { + it("projects the service group only after an effective grant", () => { + const withoutGrant = resolveRequiredGroups(data(), user); + const withGrant = resolveRequiredGroups( + data([ + { + id: "grant_device_core_dctouch", + serviceId: service.id, + targetType: "client", + targetId: client.id, + appRole: "admin", + status: "active", + }, + ]), + user + ); + + expect(withoutGrant).not.toContain("nodedc:device-core:access"); + expect(withGrant).toContain("nodedc:device-core:access"); + }); + + it("does not project the group when a deny exception wins", () => { + const groups = resolveRequiredGroups( + data( + [ + { + id: "grant_device_core_dctouch", + serviceId: service.id, + targetType: "client", + targetId: client.id, + appRole: "admin", + status: "active", + }, + ], + [ + { + id: "deny_device_core_engineer", + serviceId: service.id, + userId: user.id, + type: "deny", + }, + ] + ), + user + ); + + expect(groups).not.toContain("nodedc:device-core:access"); + }); +}); diff --git a/server/control-plane-store.mjs b/server/control-plane-store.mjs index d7ce42b..8dc80cc 100644 --- a/server/control-plane-store.mjs +++ b/server/control-plane-store.mjs @@ -2001,9 +2001,16 @@ export function createControlPlaneStore({ projectRoot }) { const data = readData(); const actor = resolveActor(data, identity); const service = findById(data.services, serviceId, "service"); + const candidate = syncServiceLaunchLink({ + ...service, + ...sanitizeServicePatch(payload, service), + }); - Object.assign(service, sanitizeServicePatch(payload, service)); - Object.assign(service, syncServiceLaunchLink(service)); + candidate.slug = normalizeServiceSlug(candidate.slug); + candidate.authHandoffPath = normalizeServiceHandoffPath(candidate.authHandoffPath); + assertServiceIdentityAvailable(data, candidate, service.id); + + Object.assign(service, candidate); service.updatedAt = isoNow(); addAuditEvent(data, actor, { @@ -2019,6 +2026,51 @@ export function createControlPlaneStore({ projectRoot }) { }); } + async function ensureService(serviceSlug, payload, identity) { + return enqueueMutation(async () => { + const data = readData(); + const actor = resolveActor(data, identity); + const now = isoNow(); + const normalizedSlug = normalizeServiceSlug(serviceSlug); + const payloadSlug = payload?.slug == null ? normalizedSlug : normalizeServiceSlug(payload.slug); + + if (payloadSlug !== normalizedSlug) { + throw new Error("service slug path and payload mismatch"); + } + + const existingService = data.services.find((service) => service.slug === normalizedSlug) ?? null; + const service = existingService + ? syncServiceLaunchLink({ + ...existingService, + ...sanitizeServicePatch({ ...payload, slug: normalizedSlug }, existingService), + }) + : createServiceRecord(data, { ...payload, slug: normalizedSlug }, now); + + service.slug = normalizedSlug; + service.authHandoffPath = normalizeServiceHandoffPath(service.authHandoffPath); + service.updatedAt = now; + assertServiceIdentityAvailable(data, service, existingService?.id ?? null); + + if (existingService) { + Object.assign(existingService, service); + } else { + data.services.push(service); + } + + addAuditEvent(data, actor, { + action: existingService ? "Обновлена регистрация сервиса" : "Зарегистрирован сервис", + objectType: "service", + objectName: service.title, + result: "success", + details: `Slug: ${service.slug}; Authentik group: ${service.authentikGroupName ?? "none"}`, + }); + markPendingSync(data, service, "service"); + + await writeData(data); + return { service, data, created: !existingService }; + }); + } + async function reorderServices(payload, identity) { const data = readData(); const actor = resolveActor(data, identity); @@ -2044,48 +2096,25 @@ export function createControlPlaneStore({ projectRoot }) { } async function createService(payload, identity) { - const data = readData(); - const actor = resolveActor(data, identity); - const now = isoNow(); - const nextIndex = data.services.length + 1; - const nextOrder = Math.max(0, ...data.services.map((service) => Number(service.order) || 0)) + 10; - const title = optionalString(payload?.title, "New Service"); - const service = syncServiceLaunchLink({ - id: uniqueId(data.services, "service", title), - slug: optionalString(payload?.slug, `new-service-${nextIndex}`), - title, - subtitle: nullableString(payload?.subtitle) ?? "Новый сервис", - description: optionalString(payload?.description, "Описание сервиса для витрины."), - fullDescription: nullableString(payload?.fullDescription) ?? "Заполните описание, медиа и ссылку запуска в редакторе контента.", - url: optionalString(payload?.url, "https://service.handhdc.ru/sso/launch"), - launchUrl: nullableString(payload?.launchUrl) ?? optionalString(payload?.url, "https://service.handhdc.ru/sso/launch"), - accentColor: nullableString(payload?.accentColor) ?? "#F7F8F4", - fallbackGradient: - nullableString(payload?.fallbackGradient) ?? - "linear-gradient(135deg, rgba(247, 248, 244, 0.72), rgba(36, 37, 42, 0.9) 52%, #090B0F 88%)", - coverMediaSource: nullableString(payload?.coverMediaSource) ?? "url", - coverMediaKind: nullableString(payload?.coverMediaKind) ?? "image", - ambientMediaSource: nullableString(payload?.ambientMediaSource) ?? "url", - ambientMediaKind: nullableString(payload?.ambientMediaKind) ?? "gif", - status: pickEnum(payload?.status, serviceStatuses, "hidden"), - order: nextOrder, - authentikApplicationSlug: nullableString(payload?.authentikApplicationSlug) ?? `new-service-${nextIndex}`, - authentikGroupName: nullableString(payload?.authentikGroupName) ?? `service-new-${nextIndex}`, - createdAt: now, - updatedAt: now, - }); + return enqueueMutation(async () => { + const data = readData(); + const actor = resolveActor(data, identity); + const now = isoNow(); + const service = createServiceRecord(data, payload, now); - data.services.push(service); - addAuditEvent(data, actor, { - action: "Создан сервис", - objectType: "service", - objectName: service.title, - result: "success", - }); - markPendingSync(data, service, "service"); + assertServiceIdentityAvailable(data, service); + data.services.push(service); + addAuditEvent(data, actor, { + action: "Создан сервис", + objectType: "service", + objectName: service.title, + result: "success", + }); + markPendingSync(data, service, "service"); - await writeData(data); - return { service, data }; + await writeData(data); + return { service, data }; + }); } async function deleteService(serviceId, identity) { @@ -2307,6 +2336,7 @@ export function createControlPlaneStore({ projectRoot }) { getLoginAccountStatus, getSnapshot, ensureTaskerInvitePlatformInvite, + ensureService, prepareInviteRegistration, readData, replaceData, @@ -3811,6 +3841,113 @@ function sanitizeServicePatch(payload, service) { return patch; } +function createServiceRecord(data, payload, now) { + const nextIndex = data.services.length + 1; + const nextOrder = Math.max(0, ...data.services.map((service) => Number(service.order) || 0)) + 10; + const title = optionalString(payload?.title, "New Service"); + const defaultUrl = optionalString(payload?.url, "https://service.handhdc.ru/sso/launch"); + const base = { + id: uniqueId(data.services, "service", title), + slug: optionalString(payload?.slug, `new-service-${nextIndex}`), + title, + subtitle: "Новый сервис", + description: "Описание сервиса для витрины.", + fullDescription: "Заполните описание, медиа и ссылку запуска в редакторе контента.", + url: defaultUrl, + launchUrl: defaultUrl, + logoutUrl: null, + loginSyncUrl: null, + iconUrl: null, + coverImageUrl: null, + coverMediaKind: "image", + coverMediaSource: "url", + coverMediaFileName: null, + previewVideoUrl: null, + ambientVideoUrl: null, + ambientMediaKind: "gif", + ambientMediaSource: "url", + ambientMediaFileName: null, + accentColor: "#F7F8F4", + fallbackGradient: "linear-gradient(135deg, rgba(247, 248, 244, 0.72), rgba(36, 37, 42, 0.9) 52%, #090B0F 88%)", + status: "hidden", + order: nextOrder, + authentikApplicationSlug: `new-service-${nextIndex}`, + authentikGroupName: `service-new-${nextIndex}`, + authHandoffPath: null, + isAvailableForAllNewClients: false, + createdAt: now, + updatedAt: now, + }; + const service = syncServiceLaunchLink({ + ...base, + ...sanitizeServicePatch(payload, base), + }); + + service.slug = normalizeServiceSlug(service.slug); + service.authHandoffPath = normalizeServiceHandoffPath(service.authHandoffPath); + return service; +} + +function normalizeServiceSlug(value) { + const slug = requireString(value, "service slug"); + + if (!/^[a-z][a-z0-9-]{1,62}$/.test(slug)) { + throw new Error("service slug must be 2-63 lowercase letters, digits or hyphens"); + } + + return slug; +} + +function normalizeServiceHandoffPath(value) { + const path = nullableString(value); + + if (path == null) { + return null; + } + + if (!path.startsWith("/") || path.startsWith("//") || path.includes("://") || path.includes("\\")) { + throw new Error("authHandoffPath must be a relative absolute-path reference"); + } + + return path; +} + +function assertServiceIdentityAvailable(data, candidate, ignoredServiceId = null) { + const duplicateSlug = data.services.find( + (service) => service.id !== ignoredServiceId && service.slug === candidate.slug + ); + + if (duplicateSlug) { + throw new Error(`service slug already exists: ${candidate.slug}`); + } + + if (candidate.authentikApplicationSlug) { + const duplicateApplication = data.services.find( + (service) => + service.id !== ignoredServiceId && + service.authentikApplicationSlug === candidate.authentikApplicationSlug + ); + + if (duplicateApplication) { + throw new Error(`Authentik application slug already exists: ${candidate.authentikApplicationSlug}`); + } + } + + if (!candidate.authentikGroupName) { + return; + } + + const duplicateGroup = data.services.find( + (service) => + service.id !== ignoredServiceId && + service.authentikGroupName === candidate.authentikGroupName + ); + + if (duplicateGroup) { + throw new Error(`Authentik group already exists: ${candidate.authentikGroupName}`); + } +} + function syncServiceLaunchLink(service) { const launchLink = String(service.launchUrl || service.url || "").trim(); diff --git a/server/control-plane-store.service-registration.test.mjs b/server/control-plane-store.service-registration.test.mjs new file mode 100644 index 0000000..a86e2ae --- /dev/null +++ b/server/control-plane-store.service-registration.test.mjs @@ -0,0 +1,87 @@ +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { createControlPlaneStore } from "./control-plane-store.mjs"; + +const temporaryRoots = []; +const actor = { sub: "phase1-contract", name: "Phase 1 contract test" }; + +afterEach(async () => { + await Promise.all(temporaryRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function createStore() { + const projectRoot = await mkdtemp(join(tmpdir(), "nodedc-launcher-service-registration-")); + temporaryRoots.push(projectRoot); + return createControlPlaneStore({ projectRoot }); +} + +function registration(overrides = {}) { + return { + slug: "device-core", + title: "DEVICE CORE", + subtitle: "Управление устройствами", + description: "Универсальный Device Manager NODE.DC.", + url: "https://device.nodedc.ru", + launchUrl: "https://device.nodedc.ru", + logoutUrl: "https://device.nodedc.ru/auth/logout", + loginSyncUrl: "https://device.nodedc.ru/auth/login-sync", + status: "active", + authentikApplicationSlug: "device-core", + authentikGroupName: "nodedc:device-core:access", + authHandoffPath: "/auth/nodedc/handoff", + isAvailableForAllNewClients: false, + ...overrides, + }; +} + +describe("generic Hub service registration", () => { + it("creates and then updates one service by slug without an implicit grant", async () => { + const store = await createStore(); + const first = await store.ensureService("device-core", registration(), actor); + + expect(first.created).toBe(true); + expect(first.service).toMatchObject({ + slug: "device-core", + authentikApplicationSlug: "device-core", + authentikGroupName: "nodedc:device-core:access", + authHandoffPath: "/auth/nodedc/handoff", + isAvailableForAllNewClients: false, + }); + expect(first.data.grants.some((grant) => grant.serviceId === first.service.id)).toBe(false); + + const second = await store.ensureService("device-core", registration({ title: "DEVICE CORE 2" }), actor); + const registered = second.data.services.filter((service) => service.slug === "device-core"); + + expect(second.created).toBe(false); + expect(second.service.id).toBe(first.service.id); + expect(second.service.title).toBe("DEVICE CORE 2"); + expect(registered).toHaveLength(1); + }); + + it("rejects slug mismatch, duplicate identities and unsafe handoff destinations", async () => { + const store = await createStore(); + await store.ensureService("device-core", registration(), actor); + + await expect(store.ensureService("device-core", registration({ slug: "another-service" }), actor)).rejects.toThrow( + "service slug path and payload mismatch" + ); + await expect( + store.createService(registration({ slug: "device-core-copy", authentikApplicationSlug: "device-core" }), actor) + ).rejects.toThrow("Authentik application slug already exists"); + await expect( + store.createService(registration({ + slug: "device-core-group-copy", + authentikApplicationSlug: "device-core-group-copy", + }), actor) + ).rejects.toThrow("Authentik group already exists"); + await expect( + store.ensureService("unsafe-handoff", registration({ + slug: "unsafe-handoff", + authentikApplicationSlug: "unsafe-handoff", + authHandoffPath: "https://attacker.example/handoff", + }), actor) + ).rejects.toThrow("authHandoffPath must be a relative absolute-path reference"); + }); +}); diff --git a/server/dev-server.mjs b/server/dev-server.mjs index d463f8d..e7eb48a 100644 --- a/server/dev-server.mjs +++ b/server/dev-server.mjs @@ -2199,6 +2199,14 @@ app.post("/api/admin/services", requireLauncherAdmin, requireRootLauncherAdmin, res.status(201).json(result); })); +app.put("/api/admin/services/registrations/:serviceSlug", requireLauncherAdmin, requireRootLauncherAdmin, asyncRoute(async (req, res) => { + await sendAdminIdempotentJson(req, res, async () => { + const result = await controlPlaneStore.ensureService(req.params.serviceSlug, req.body, req.nodedcSession.user); + publishControlPlaneEvent(result.created ? "admin.service.created" : "admin.service.updated"); + return result; + }); +})); + app.patch("/api/admin/services/reorder", requireLauncherAdmin, requireRootLauncherAdmin, asyncRoute(async (req, res) => { const result = await controlPlaneStore.reorderServices(req.body, req.nodedcSession.user); publishControlPlaneEvent("admin.service.reordered"); @@ -2243,14 +2251,16 @@ app.post("/api/admin/access/grants", requireLauncherAdmin, asyncRoute(async (req return; } - const result = await controlPlaneStore.upsertGrant(req.body, req.nodedcSession.user); - const syncResult = await syncUsersToAuthentik( - result.data, - resolveGrantTargetUserIds(result.data, result.grant.targetType, result.grant.targetId), - req.nodedcSession.user - ); - publishControlPlaneEvent("admin.access.grant.updated", syncResult.userIds); - res.json(scopeAdminMutationResult(req, { ...result, data: syncResult.data })); + await sendAdminIdempotentJson(req, res, async () => { + const result = await controlPlaneStore.upsertGrant(req.body, req.nodedcSession.user); + const syncResult = await syncUsersToAuthentik( + result.data, + resolveGrantTargetUserIds(result.data, result.grant.targetType, result.grant.targetId), + req.nodedcSession.user + ); + publishControlPlaneEvent("admin.access.grant.updated", syncResult.userIds); + return scopeAdminMutationResult(req, { ...result, data: syncResult.data }); + }); })); app.post("/api/admin/access/exceptions", requireLauncherAdmin, asyncRoute(async (req, res) => { diff --git a/src/entities/access/computeEffectiveAccess.test.ts b/src/entities/access/computeEffectiveAccess.test.ts index 0fdcba1..332e094 100644 --- a/src/entities/access/computeEffectiveAccess.test.ts +++ b/src/entities/access/computeEffectiveAccess.test.ts @@ -122,6 +122,71 @@ describe("computeEffectiveAccess", () => { expect(result.source).toBe("user"); }); + it("supports a personal client without making the service globally available", () => { + const personalClient: Client = { + ...client, + id: "client_personal_a", + type: "person", + name: "Личный контур пользователя", + }; + const personalMembership: ClientMembership = { + ...membership, + id: "membership_personal_a", + clientId: personalClient.id, + }; + const result = computeEffectiveAccess({ + ...baseInput, + client: personalClient, + membership: personalMembership, + userGroups: [], + grants: [grant("client", personalClient.id)], + }); + + expect(result.allowed).toBe(true); + expect(result.source).toBe("client"); + }); + + it("isolates an open-pool user grant from other users in the same pool", () => { + const publicPoolClient: Client = { + ...client, + id: "client_public_pool", + name: "Открытый контур", + }; + const publicPoolMembership: ClientMembership = { + ...membership, + id: "membership_public_pool_a", + clientId: publicPoolClient.id, + }; + const granted = computeEffectiveAccess({ + ...baseInput, + client: publicPoolClient, + membership: publicPoolMembership, + userGroups: [], + grants: [grant("user", user.id)], + }); + const otherUser: LauncherUser = { + ...user, + id: "user_b", + email: "other@example.ru", + }; + const isolated = computeEffectiveAccess({ + ...baseInput, + client: publicPoolClient, + user: otherUser, + membership: { + ...publicPoolMembership, + id: "membership_public_pool_b", + userId: otherUser.id, + }, + userGroups: [], + grants: [grant("user", user.id)], + }); + + expect(granted.allowed).toBe(true); + expect(granted.source).toBe("user"); + expect(isolated.allowed).toBe(false); + }); + it("deny exception overrides user grant", () => { const result = computeEffectiveAccess({ ...baseInput, @@ -133,6 +198,26 @@ describe("computeEffectiveAccess", () => { expect(result.source).toBe("exception"); }); + it.each(["hidden", "disabled"] as const)("blocks a %s service even when a grant exists", (status) => { + const result = computeEffectiveAccess({ + ...baseInput, + service: { ...service, status }, + grants: [grant("client", client.id)], + }); + + expect(result.allowed).toBe(false); + expect(result.visible).toBe(false); + }); + + it("ignores an inactive entitlement", () => { + const result = computeEffectiveAccess({ + ...baseInput, + grants: [{ ...grant("client", client.id), status: "disabled" }], + }); + + expect(result.allowed).toBe(false); + }); + it("maintenance service is visible but openEnabled is false", () => { const result = computeEffectiveAccess({ ...baseInput, diff --git a/src/entities/user/assistantAdminRoutes.contract.test.ts b/src/entities/user/assistantAdminRoutes.contract.test.ts index 3ab4204..e967772 100644 --- a/src/entities/user/assistantAdminRoutes.contract.test.ts +++ b/src/entities/user/assistantAdminRoutes.contract.test.ts @@ -81,6 +81,28 @@ describe("assistant-ready Launcher admin routes", () => { expect(block).toContain("scopeAdminMutationResult"); }); + it("keeps generic service registration root-guarded and idempotent", () => { + const block = sourceBlock( + 'app.put("/api/admin/services/registrations/:serviceSlug"', + 'app.patch("/api/admin/services/reorder"' + ); + + expect(block).toContain("requireLauncherAdmin"); + expect(block).toContain("requireRootLauncherAdmin"); + expect(block).toContain("sendAdminIdempotentJson"); + expect(block).toContain("controlPlaneStore.ensureService"); + }); + + it("keeps service grants idempotent and outside the assistant gateway allowlist", () => { + const block = sourceBlock('app.post("/api/admin/access/grants"', 'app.post("/api/admin/access/exceptions"'); + const allowlistBlock = sourceBlock("const assistantGatewayAdminRouteAllowlist = [", "];",); + + expect(block).toContain("sendAdminIdempotentJson"); + expect(block).toContain("controlPlaneStore.upsertGrant"); + expect(allowlistBlock).not.toContain("/api/admin/services/registrations"); + expect(allowlistBlock).not.toContain("/api/admin/access/grants"); + }); + it("keeps hard delete routes outside assistant-ready routes and root-guarded where available", () => { const userDeleteBlock = sourceBlock('app.delete("/api/admin/users/:userId"', 'app.post("/api/admin/users/:userId/provision-authentik"'); diff --git a/src/shared/api/adminApi.ts b/src/shared/api/adminApi.ts index c57f6f8..a42d5b4 100644 --- a/src/shared/api/adminApi.ts +++ b/src/shared/api/adminApi.ts @@ -334,6 +334,21 @@ export async function createAdminService(payload: Partial = {}): Promis }); } +export async function registerAdminService( + serviceSlug: string, + payload: Partial, + idempotencyKey: string +): Promise { + return requestJson( + `/api/admin/services/registrations/${encodeURIComponent(serviceSlug)}`, + { + method: "PUT", + headers: { "Idempotency-Key": idempotencyKey }, + body: JSON.stringify(payload), + } + ); +} + export async function updateAdminService(serviceId: string, patch: Partial): Promise { return requestJson(`/api/admin/services/${encodeURIComponent(serviceId)}`, { method: "PATCH", @@ -478,9 +493,10 @@ export async function setAdminServiceModuleEntitlement(payload: { }); } -export async function upsertAdminGrant(payload: Partial): Promise { +export async function upsertAdminGrant(payload: Partial, idempotencyKey?: string): Promise { return requestJson("/api/admin/access/grants", { method: "POST", + headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined, body: JSON.stringify(payload), }); }