Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,342 @@
|
||||
/**
|
||||
* Phase 06 #22 — Plugin lifecycle API for a tenant.
|
||||
*
|
||||
* GET /api/tenants/:tenant/plugins → list installed plugins
|
||||
* POST /api/tenants/:tenant/plugins → install plugin (json body
|
||||
* { manifestJson, wasmSha256, signaturePublicKey })
|
||||
* POST /api/tenants/:tenant/plugins?id=<rowId>&op=enable → enable
|
||||
* POST /api/tenants/:tenant/plugins?id=<rowId>&op=disable → disable
|
||||
* POST /api/tenants/:tenant/plugins?op=revoke → revoke capability grants
|
||||
*
|
||||
* Read ops require `app.plugins.use`; mutating ops require
|
||||
* `app.plugins.manage` and audit-events are written by the service layer.
|
||||
*
|
||||
* Operator-only `wasmSha256` and `signaturePublicKey` are supplied by
|
||||
* the install-time pipeline (admin uploads a signed bundle through a
|
||||
* separate operator path that produces these values). We accept them
|
||||
* verbatim for the foundation; the full ZIP-parsing + signature
|
||||
* verification flow lands with the marketplace (#23).
|
||||
*/
|
||||
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
||||
import { createSlidingWindowRateLimiter } from "@toolctrl/shared-store";
|
||||
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
||||
import { verifyUserHasPermission } from "~/utils/helpers/.server/PermissionsService";
|
||||
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
||||
import { getUser } from "~/utils/db/users.db.server";
|
||||
import { getSharedStore } from "~/shared-store.server";
|
||||
import {
|
||||
parsePluginCapabilityGrantArray,
|
||||
parsePluginCapabilityNameArray,
|
||||
readPluginConsentJsonObject,
|
||||
} from "~/modules/plugins/utils/capabilityConsentPayload.server";
|
||||
import {
|
||||
PluginLifecycleError,
|
||||
disablePlugin,
|
||||
enablePlugin,
|
||||
grantPluginCapabilities,
|
||||
installPlugin,
|
||||
isCapabilityGrantScopeSatisfied,
|
||||
listPluginCapabilityGrants,
|
||||
listPlugins,
|
||||
revokePluginCapabilities,
|
||||
type PluginLifecycleActor,
|
||||
type PluginListItem,
|
||||
} from "~/modules/plugins/services/.server/PluginLifecycleService";
|
||||
import { getPluginConsentRequirements } from "~/modules/plugins/utils/pluginConsentRequirements";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
|
||||
const USE_PERMISSION = "app.plugins.use";
|
||||
const MANAGE_PERMISSION = "app.plugins.manage";
|
||||
|
||||
function areCapabilityNameSetsEqual(left: ReadonlyArray<string>, right: ReadonlyArray<string>): boolean {
|
||||
if (left.length !== right.length) return false;
|
||||
const rightNames = new Set(right);
|
||||
return left.every((name) => rightNames.has(name));
|
||||
}
|
||||
|
||||
async function createCapabilityReviewDigest(item: Pick<PluginListItem, "pluginId" | "version" | "manifest">, capabilityNames: ReadonlyArray<string>) {
|
||||
const { createCapabilityReviewDigest: createDigest } = await import("~/modules/plugins/utils/capabilityReviewDigest");
|
||||
return createDigest(item, capabilityNames);
|
||||
}
|
||||
|
||||
/**
|
||||
* F-011 — route-level rate limit on plugin installs.
|
||||
*
|
||||
* The permission gate already restricts WHO can install; the sliding-
|
||||
* window limit caps HOW OFTEN a single tenant can attempt installs, so
|
||||
* a compromised tenant-admin cookie can't be used to spray junk Plugin
|
||||
* rows + signature-verify CPU. The key is tenant-scoped so adversarial
|
||||
* activity on one tenant cannot starve another.
|
||||
*
|
||||
* Fail-open on infra error outside production (matches existing pattern in
|
||||
* api.leads.capture and api.embed.forms.$formKey.submit) — a flaky Redis
|
||||
* must not block legitimate staging/dev operator installs. Production always
|
||||
* fails closed for plugin writes.
|
||||
*/
|
||||
const INSTALL_RATE_LIMIT_PREFIX = "plugin-install-route:rl";
|
||||
|
||||
function shouldFailClosedOnRateLimitInfraFailure(): boolean {
|
||||
return process.env.NODE_ENV === "production";
|
||||
}
|
||||
|
||||
function resolveInstallRateLimitPerMin(): number {
|
||||
const raw = process.env.PLUGIN_INSTALL_RATE_LIMIT_PER_MIN;
|
||||
if (typeof raw !== "string" || raw.length === 0) return 5;
|
||||
const parsed = Number.parseInt(raw, 10);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) return 5;
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function invalidJsonResponse(t: (key: string, values?: Record<string, unknown>) => string, parsed: { ok: false; error?: string }): Response {
|
||||
if (parsed.error === "unsupported_media_type") {
|
||||
return Response.json({ error: "unsupported_media_type", message: t("api.plugins.errors.unsupportedMediaType") }, { status: 415 });
|
||||
}
|
||||
return Response.json({ error: "invalid_json", message: t("api.plugins.errors.invalidJsonBody") }, { status: 400 });
|
||||
}
|
||||
|
||||
function hasJsonContentType(request: Request): boolean {
|
||||
const contentType = request.headers.get("content-type")?.toLowerCase() ?? "";
|
||||
return contentType.split(";", 1)[0]?.trim() === "application/json";
|
||||
}
|
||||
|
||||
function getPluginLifecycleErrorStatus(code: PluginLifecycleError["code"]): number {
|
||||
if (
|
||||
code === "signature_key_not_trusted" ||
|
||||
code === "signature_key_mismatch" ||
|
||||
code === "binary_verification_failed" ||
|
||||
code === "capability_unavailable" ||
|
||||
code === "production_guard_violation"
|
||||
) {
|
||||
return 403;
|
||||
}
|
||||
if (code === "not_found" || code === "binary_not_found") {
|
||||
return 404;
|
||||
}
|
||||
if (code === "already_installed" || code === "capability_consent_missing") {
|
||||
return 409;
|
||||
}
|
||||
if (code === "tenant_install_limit_exceeded") {
|
||||
return 429;
|
||||
}
|
||||
return 400;
|
||||
}
|
||||
|
||||
export async function loader({ request, params }: LoaderFunctionArgs) {
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, USE_PERMISSION, tenantId);
|
||||
const items = await listPlugins({ tenantId });
|
||||
return Response.json({ items });
|
||||
}
|
||||
|
||||
export async function action({ request, params }: ActionFunctionArgs) {
|
||||
const { t } = await getTranslations(request);
|
||||
const tenantId = await getTenantIdFromUrl(params);
|
||||
await verifyUserHasPermission(request, MANAGE_PERMISSION, tenantId);
|
||||
if (!hasJsonContentType(request)) {
|
||||
return invalidJsonResponse(t, { ok: false, error: "unsupported_media_type" });
|
||||
}
|
||||
await validateCSRFToken(request, { headerOnly: true });
|
||||
|
||||
const url = new URL(request.url);
|
||||
const op = url.searchParams.get("op");
|
||||
const pluginRowId = url.searchParams.get("id");
|
||||
|
||||
try {
|
||||
if (op === "enable" && pluginRowId) {
|
||||
const parsed = await readPluginConsentJsonObject(request);
|
||||
if (!parsed.ok) {
|
||||
return invalidJsonResponse(t, parsed);
|
||||
}
|
||||
const actor = await resolveActor(request);
|
||||
const item = await enablePlugin({ tenantId, pluginRowId, actor });
|
||||
return Response.json({ item });
|
||||
}
|
||||
if (op === "disable" && pluginRowId) {
|
||||
const parsed = await readPluginConsentJsonObject(request);
|
||||
if (!parsed.ok) {
|
||||
return invalidJsonResponse(t, parsed);
|
||||
}
|
||||
const actor = await resolveActor(request);
|
||||
const item = await disablePlugin({ tenantId, pluginRowId, actor });
|
||||
return Response.json({ item });
|
||||
}
|
||||
// F-001 — grant capability consent. body: { pluginId, grants: [...] }
|
||||
if (op === "grant") {
|
||||
const parsed = await readPluginConsentJsonObject(request);
|
||||
if (!parsed.ok) {
|
||||
return invalidJsonResponse(t, parsed);
|
||||
}
|
||||
const body = parsed.value as {
|
||||
pluginId?: string;
|
||||
grants?: unknown;
|
||||
capabilitiesReviewed?: boolean;
|
||||
capabilityReviewDigest?: string;
|
||||
};
|
||||
const parsedGrants = parsePluginCapabilityGrantArray(body.grants);
|
||||
if (typeof body.pluginId !== "string" || !parsedGrants.ok) {
|
||||
return Response.json({ error: "missing_fields", message: t("api.plugins.errors.missingGrantFields") }, { status: 400 });
|
||||
}
|
||||
if (body.capabilitiesReviewed !== true) {
|
||||
return Response.json({ error: "capability_review_required", message: t("api.plugins.errors.missingCapabilityReview") }, { status: 400 });
|
||||
}
|
||||
const item = (await listPlugins({ tenantId })).find((row) => row.pluginId === body.pluginId);
|
||||
if (!item) {
|
||||
return Response.json({ error: "plugin_not_found", message: t("api.plugins.errors.pluginNotFound") }, { status: 404 });
|
||||
}
|
||||
const declaredCapabilities = new Map(getPluginConsentRequirements(item.manifest).map((requirement) => [requirement.name, requirement]));
|
||||
if (parsedGrants.grants.some((grant) => !declaredCapabilities.has(grant.capabilityName))) {
|
||||
return Response.json({ error: "missing_fields", message: t("api.plugins.errors.missingGrantFields") }, { status: 400 });
|
||||
}
|
||||
const requestedCapabilities = Array.from(
|
||||
new Set(
|
||||
parsedGrants.grants.flatMap((grant) => {
|
||||
const capability = declaredCapabilities.get(grant.capabilityName);
|
||||
return capability ? [capability.name] : [];
|
||||
})
|
||||
)
|
||||
);
|
||||
if (requestedCapabilities.length === 0) {
|
||||
return Response.json({ error: "missing_fields", message: t("api.plugins.errors.missingGrantFields") }, { status: 400 });
|
||||
}
|
||||
const existingGrants = await listPluginCapabilityGrants({ tenantId, pluginId: item.pluginId });
|
||||
const grantByCapability = new Map(existingGrants.map((grant) => [grant.capabilityName, grant]));
|
||||
const missingCapabilities = getPluginConsentRequirements(item.manifest)
|
||||
.filter((requirement) => {
|
||||
const grant = grantByCapability.get(requirement.name);
|
||||
return !grant || !isCapabilityGrantScopeSatisfied({ declaredScope: requirement.scope ?? null, grantedScopeJson: grant.scopeJson });
|
||||
})
|
||||
.map((requirement) => requirement.name);
|
||||
if (!areCapabilityNameSetsEqual(requestedCapabilities, missingCapabilities)) {
|
||||
return Response.json({ error: "stale_capability_review", message: t("api.plugins.errors.staleCapabilityReview") }, { status: 409 });
|
||||
}
|
||||
const expectedDigest = await createCapabilityReviewDigest(item, missingCapabilities);
|
||||
if (body.capabilityReviewDigest !== expectedDigest) {
|
||||
return Response.json({ error: "stale_capability_review", message: t("api.plugins.errors.staleCapabilityReview") }, { status: 409 });
|
||||
}
|
||||
const actor = await resolveActor(request);
|
||||
const rows = await grantPluginCapabilities({
|
||||
tenantId,
|
||||
pluginId: body.pluginId,
|
||||
grants: requestedCapabilities.map((name) => ({
|
||||
capabilityName: name,
|
||||
scopeJson: declaredCapabilities.get(name)?.scope ?? null,
|
||||
})),
|
||||
actor,
|
||||
capabilityReviewDigest: body.capabilityReviewDigest,
|
||||
});
|
||||
return Response.json({ grants: rows }, { status: 201 });
|
||||
}
|
||||
// F-001 — revoke capability consent. body: { pluginId, capabilityNames: [...] }
|
||||
if (op === "revoke") {
|
||||
const parsed = await readPluginConsentJsonObject(request);
|
||||
if (!parsed.ok) {
|
||||
return invalidJsonResponse(t, parsed);
|
||||
}
|
||||
const body = parsed.value as {
|
||||
pluginId?: string;
|
||||
capabilityNames?: readonly unknown[];
|
||||
};
|
||||
const parsedCapabilityNames = parsePluginCapabilityNameArray(body.capabilityNames);
|
||||
if (typeof body.pluginId !== "string" || !parsedCapabilityNames.ok) {
|
||||
return Response.json({ error: "missing_fields", message: t("api.plugins.errors.missingRevokeFields") }, { status: 400 });
|
||||
}
|
||||
const actor = await resolveActor(request);
|
||||
const result = await revokePluginCapabilities({
|
||||
tenantId,
|
||||
pluginId: body.pluginId,
|
||||
capabilityNames: parsedCapabilityNames.capabilityNames,
|
||||
actor,
|
||||
});
|
||||
return Response.json({ result });
|
||||
}
|
||||
// Default = install
|
||||
const parsed = await readPluginConsentJsonObject(request);
|
||||
if (!parsed.ok) {
|
||||
return invalidJsonResponse(t, parsed);
|
||||
}
|
||||
const body = parsed.value as {
|
||||
manifestJson?: unknown;
|
||||
wasmSha256?: string;
|
||||
signaturePublicKey?: string;
|
||||
};
|
||||
if (!body.manifestJson || typeof body.wasmSha256 !== "string" || typeof body.signaturePublicKey !== "string") {
|
||||
return Response.json({ error: "missing_fields", message: t("api.plugins.errors.missingInstallFields") }, { status: 400 });
|
||||
}
|
||||
|
||||
// F-011 — sliding-window rate limit before the lifecycle service
|
||||
// burns CPU verifying signatures. Keyed by tenant so adversarial
|
||||
// activity on one tenant cannot starve another; secondary IP key
|
||||
// catches a single attacker churning across credentials.
|
||||
try {
|
||||
const perMin = resolveInstallRateLimitPerMin();
|
||||
const store = getSharedStore();
|
||||
const limiter = createSlidingWindowRateLimiter({
|
||||
store,
|
||||
max: perMin,
|
||||
windowSeconds: 60,
|
||||
prefix: INSTALL_RATE_LIMIT_PREFIX,
|
||||
});
|
||||
const tenantDecision = await limiter.consume(`tenant:${tenantId}`);
|
||||
if (!tenantDecision.allowed) {
|
||||
return Response.json(
|
||||
{ error: "rate_limit_exceeded", message: t("api.plugins.errors.installRateLimitExceeded", { perMin }) },
|
||||
{ status: 429, headers: { "Retry-After": "60" } }
|
||||
);
|
||||
}
|
||||
const ip = getRequestIp(request);
|
||||
if (ip) {
|
||||
const ipDecision = await limiter.consume(`ip:${ip}`);
|
||||
if (!ipDecision.allowed) {
|
||||
return Response.json(
|
||||
{ error: "rate_limit_exceeded", message: t("api.plugins.errors.installRateLimitExceeded", { perMin }) },
|
||||
{ status: 429, headers: { "Retry-After": "60" } }
|
||||
);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (shouldFailClosedOnRateLimitInfraFailure()) {
|
||||
return Response.json(
|
||||
{ error: "rate_limit_unavailable", message: t("api.plugins.errors.rateLimitUnavailable") },
|
||||
{ status: 503, headers: { "Retry-After": "60" } }
|
||||
);
|
||||
}
|
||||
// Fail-open on infra error outside production — better than dropping
|
||||
// legitimate staging/dev installs while Redis is being restarted.
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn("[plugin-install] rate-limit infra failure; allowing install:", err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
|
||||
const actor = await resolveActor(request);
|
||||
const item = await installPlugin({
|
||||
tenantId,
|
||||
manifestJson: body.manifestJson,
|
||||
wasmSha256: body.wasmSha256,
|
||||
signaturePublicKey: body.signaturePublicKey,
|
||||
actor,
|
||||
});
|
||||
return Response.json({ item }, { status: 201 });
|
||||
} catch (err) {
|
||||
if (err instanceof PluginLifecycleError) {
|
||||
return Response.json(
|
||||
{ error: err.code, message: t(`settings.plugins.errors.lifecycle.${err.code}`) },
|
||||
{ status: getPluginLifecycleErrorStatus(err.code) }
|
||||
);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async function resolveActor(request: Request): Promise<PluginLifecycleActor> {
|
||||
const info = await getUserInfo(request);
|
||||
const user = info.userId ? await getUser(info.userId) : null;
|
||||
return {
|
||||
userId: info.userId ?? null,
|
||||
email: user?.email ?? null,
|
||||
ip: getRequestIp(request),
|
||||
};
|
||||
}
|
||||
|
||||
function getRequestIp(request: Request): string | null {
|
||||
return request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip")?.trim() || null;
|
||||
}
|
||||
Reference in new issue
Block a user