feat(hub): add idempotent service registration
This commit is contained in:
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
+166
-29
@@ -2001,9 +2001,16 @@ export function createControlPlaneStore({ projectRoot }) {
|
|||||||
const data = readData();
|
const data = readData();
|
||||||
const actor = resolveActor(data, identity);
|
const actor = resolveActor(data, identity);
|
||||||
const service = findById(data.services, serviceId, "service");
|
const service = findById(data.services, serviceId, "service");
|
||||||
|
const candidate = syncServiceLaunchLink({
|
||||||
|
...service,
|
||||||
|
...sanitizeServicePatch(payload, service),
|
||||||
|
});
|
||||||
|
|
||||||
Object.assign(service, sanitizeServicePatch(payload, service));
|
candidate.slug = normalizeServiceSlug(candidate.slug);
|
||||||
Object.assign(service, syncServiceLaunchLink(service));
|
candidate.authHandoffPath = normalizeServiceHandoffPath(candidate.authHandoffPath);
|
||||||
|
assertServiceIdentityAvailable(data, candidate, service.id);
|
||||||
|
|
||||||
|
Object.assign(service, candidate);
|
||||||
service.updatedAt = isoNow();
|
service.updatedAt = isoNow();
|
||||||
|
|
||||||
addAuditEvent(data, actor, {
|
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) {
|
async function reorderServices(payload, identity) {
|
||||||
const data = readData();
|
const data = readData();
|
||||||
const actor = resolveActor(data, identity);
|
const actor = resolveActor(data, identity);
|
||||||
@@ -2044,37 +2096,13 @@ export function createControlPlaneStore({ projectRoot }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function createService(payload, identity) {
|
async function createService(payload, identity) {
|
||||||
|
return enqueueMutation(async () => {
|
||||||
const data = readData();
|
const data = readData();
|
||||||
const actor = resolveActor(data, identity);
|
const actor = resolveActor(data, identity);
|
||||||
const now = isoNow();
|
const now = isoNow();
|
||||||
const nextIndex = data.services.length + 1;
|
const service = createServiceRecord(data, payload, now);
|
||||||
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,
|
|
||||||
});
|
|
||||||
|
|
||||||
|
assertServiceIdentityAvailable(data, service);
|
||||||
data.services.push(service);
|
data.services.push(service);
|
||||||
addAuditEvent(data, actor, {
|
addAuditEvent(data, actor, {
|
||||||
action: "Создан сервис",
|
action: "Создан сервис",
|
||||||
@@ -2086,6 +2114,7 @@ export function createControlPlaneStore({ projectRoot }) {
|
|||||||
|
|
||||||
await writeData(data);
|
await writeData(data);
|
||||||
return { service, data };
|
return { service, data };
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteService(serviceId, identity) {
|
async function deleteService(serviceId, identity) {
|
||||||
@@ -2307,6 +2336,7 @@ export function createControlPlaneStore({ projectRoot }) {
|
|||||||
getLoginAccountStatus,
|
getLoginAccountStatus,
|
||||||
getSnapshot,
|
getSnapshot,
|
||||||
ensureTaskerInvitePlatformInvite,
|
ensureTaskerInvitePlatformInvite,
|
||||||
|
ensureService,
|
||||||
prepareInviteRegistration,
|
prepareInviteRegistration,
|
||||||
readData,
|
readData,
|
||||||
replaceData,
|
replaceData,
|
||||||
@@ -3811,6 +3841,113 @@ function sanitizeServicePatch(payload, service) {
|
|||||||
return patch;
|
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) {
|
function syncServiceLaunchLink(service) {
|
||||||
const launchLink = String(service.launchUrl || service.url || "").trim();
|
const launchLink = String(service.launchUrl || service.url || "").trim();
|
||||||
|
|
||||||
|
|||||||
@@ -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");
|
||||||
|
});
|
||||||
|
});
|
||||||
+11
-1
@@ -2199,6 +2199,14 @@ app.post("/api/admin/services", requireLauncherAdmin, requireRootLauncherAdmin,
|
|||||||
res.status(201).json(result);
|
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) => {
|
app.patch("/api/admin/services/reorder", requireLauncherAdmin, requireRootLauncherAdmin, asyncRoute(async (req, res) => {
|
||||||
const result = await controlPlaneStore.reorderServices(req.body, req.nodedcSession.user);
|
const result = await controlPlaneStore.reorderServices(req.body, req.nodedcSession.user);
|
||||||
publishControlPlaneEvent("admin.service.reordered");
|
publishControlPlaneEvent("admin.service.reordered");
|
||||||
@@ -2243,6 +2251,7 @@ app.post("/api/admin/access/grants", requireLauncherAdmin, asyncRoute(async (req
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
await sendAdminIdempotentJson(req, res, async () => {
|
||||||
const result = await controlPlaneStore.upsertGrant(req.body, req.nodedcSession.user);
|
const result = await controlPlaneStore.upsertGrant(req.body, req.nodedcSession.user);
|
||||||
const syncResult = await syncUsersToAuthentik(
|
const syncResult = await syncUsersToAuthentik(
|
||||||
result.data,
|
result.data,
|
||||||
@@ -2250,7 +2259,8 @@ app.post("/api/admin/access/grants", requireLauncherAdmin, asyncRoute(async (req
|
|||||||
req.nodedcSession.user
|
req.nodedcSession.user
|
||||||
);
|
);
|
||||||
publishControlPlaneEvent("admin.access.grant.updated", syncResult.userIds);
|
publishControlPlaneEvent("admin.access.grant.updated", syncResult.userIds);
|
||||||
res.json(scopeAdminMutationResult(req, { ...result, data: syncResult.data }));
|
return scopeAdminMutationResult(req, { ...result, data: syncResult.data });
|
||||||
|
});
|
||||||
}));
|
}));
|
||||||
|
|
||||||
app.post("/api/admin/access/exceptions", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
app.post("/api/admin/access/exceptions", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||||
|
|||||||
@@ -122,6 +122,71 @@ describe("computeEffectiveAccess", () => {
|
|||||||
expect(result.source).toBe("user");
|
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", () => {
|
it("deny exception overrides user grant", () => {
|
||||||
const result = computeEffectiveAccess({
|
const result = computeEffectiveAccess({
|
||||||
...baseInput,
|
...baseInput,
|
||||||
@@ -133,6 +198,26 @@ describe("computeEffectiveAccess", () => {
|
|||||||
expect(result.source).toBe("exception");
|
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", () => {
|
it("maintenance service is visible but openEnabled is false", () => {
|
||||||
const result = computeEffectiveAccess({
|
const result = computeEffectiveAccess({
|
||||||
...baseInput,
|
...baseInput,
|
||||||
|
|||||||
@@ -81,6 +81,28 @@ describe("assistant-ready Launcher admin routes", () => {
|
|||||||
expect(block).toContain("scopeAdminMutationResult");
|
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", () => {
|
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"');
|
const userDeleteBlock = sourceBlock('app.delete("/api/admin/users/:userId"', 'app.post("/api/admin/users/:userId/provision-authentik"');
|
||||||
|
|
||||||
|
|||||||
@@ -334,6 +334,21 @@ export async function createAdminService(payload: Partial<Service> = {}): Promis
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function registerAdminService(
|
||||||
|
serviceSlug: string,
|
||||||
|
payload: Partial<Service>,
|
||||||
|
idempotencyKey: string
|
||||||
|
): Promise<ControlPlaneMutationResult & { created: boolean; service: Service }> {
|
||||||
|
return requestJson<ControlPlaneMutationResult & { created: boolean; service: Service }>(
|
||||||
|
`/api/admin/services/registrations/${encodeURIComponent(serviceSlug)}`,
|
||||||
|
{
|
||||||
|
method: "PUT",
|
||||||
|
headers: { "Idempotency-Key": idempotencyKey },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export async function updateAdminService(serviceId: string, patch: Partial<Service>): Promise<ControlPlaneMutationResult> {
|
export async function updateAdminService(serviceId: string, patch: Partial<Service>): Promise<ControlPlaneMutationResult> {
|
||||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/services/${encodeURIComponent(serviceId)}`, {
|
return requestJson<ControlPlaneMutationResult>(`/api/admin/services/${encodeURIComponent(serviceId)}`, {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
@@ -478,9 +493,10 @@ export async function setAdminServiceModuleEntitlement(payload: {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function upsertAdminGrant(payload: Partial<ServiceGrant>): Promise<ControlPlaneMutationResult> {
|
export async function upsertAdminGrant(payload: Partial<ServiceGrant>, idempotencyKey?: string): Promise<ControlPlaneMutationResult> {
|
||||||
return requestJson<ControlPlaneMutationResult>("/api/admin/access/grants", {
|
return requestJson<ControlPlaneMutationResult>("/api/admin/access/grants", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
|
headers: idempotencyKey ? { "Idempotency-Key": idempotencyKey } : undefined,
|
||||||
body: JSON.stringify(payload),
|
body: JSON.stringify(payload),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user