Update hivegrid-cloud reference to latest main
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e98d38e716
commit
7b21524c86
3781 files changed
+373484
-225607
No files matched your search
@@ -0,0 +1,200 @@
|
||||
import type { IncomingMessage } from "node:http";
|
||||
|
||||
import { featureKeys, getDefaultProductBlueprint, getProductBlueprint, type ProductBlueprintId, type TenantFeatureOverride } from "@hivegrid/entitlements";
|
||||
import { findLegacyApiKeyByKey, type LegacyApiKeyReaderClient, type LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
|
||||
import { getReadDbClient } from "@hivegrid/db/client.server";
|
||||
import type { DbClient } from "@hivegrid/db/client.server";
|
||||
import { findActiveMcpOAuthAccessToken } from "@hivegrid/db/mcp-oauth.server";
|
||||
|
||||
import type { McpRuntimeConfig } from "./config.js";
|
||||
import { McpHttpError } from "./errors.js";
|
||||
import { getHeader } from "./http.js";
|
||||
import { checkMcpRateLimit } from "./rate-limit.js";
|
||||
import { normalizeMcpScopes } from "./scopes.js";
|
||||
|
||||
export type McpPrincipal = {
|
||||
apiKey?: LegacyApiKeySimple;
|
||||
credential: {
|
||||
kind: "oauth" | "api_key";
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
tenantId: string;
|
||||
tenantSlug: string;
|
||||
userId: string;
|
||||
scopes: readonly string[];
|
||||
permissions: readonly string[];
|
||||
};
|
||||
|
||||
export async function authenticateMcpRequest(
|
||||
req: IncomingMessage,
|
||||
config: McpRuntimeConfig,
|
||||
client: DbClient = getReadDbClient(),
|
||||
operationCount = 1,
|
||||
): Promise<McpPrincipal> {
|
||||
const token = parseBearerToken(getHeader(req, "authorization"));
|
||||
const authenticateHeader = authenticateChallenge(config);
|
||||
if (!token) {
|
||||
throw new McpHttpError(401, "missing_token", "MCP requests require a bearer access token.", {
|
||||
"WWW-Authenticate": authenticateHeader,
|
||||
});
|
||||
}
|
||||
|
||||
const oauthToken = await findActiveMcpOAuthAccessToken(token, config.oauth.tokenHashSecret);
|
||||
if (oauthToken) {
|
||||
if (oauthToken.resource !== config.oauth.resourceUrl) {
|
||||
throw new McpHttpError(401, "invalid_token", "OAuth token audience does not match this MCP resource.", {
|
||||
"WWW-Authenticate": `${authenticateHeader}, error="invalid_token"`,
|
||||
});
|
||||
}
|
||||
const rateLimit = await checkMcpRateLimit({ apiKeyId: oauthToken.id, tenantId: oauthToken.tenantId, weight: operationCount });
|
||||
if (!rateLimit.allowed) {
|
||||
throw new McpHttpError(rateLimit.status, rateLimit.code, rateLimit.message, rateLimit.headers);
|
||||
}
|
||||
const [permissions, moduleAllowed, tenant] = await Promise.all([
|
||||
getPermissionsByUser(client, oauthToken.userId, oauthToken.tenantId),
|
||||
tenantHasMcpModule(client, oauthToken.tenantId, oauthToken.userId),
|
||||
client.tenant.findUnique({ where: { id: oauthToken.tenantId }, select: { deactivatedReason: true } }),
|
||||
]);
|
||||
// Mirror the API-key branch: a deactivated tenant is an operator kill-switch
|
||||
// that must also cut off still-valid OAuth access tokens.
|
||||
if (tenant?.deactivatedReason) {
|
||||
throw new McpHttpError(401, "invalid_token", "Tenant is deactivated.", {
|
||||
"WWW-Authenticate": `${authenticateHeader}, error="invalid_token"`,
|
||||
});
|
||||
}
|
||||
if (!moduleAllowed) {
|
||||
throw new McpHttpError(403, "mcp_not_enabled", "MCP is not enabled for this tenant or OAuth user.");
|
||||
}
|
||||
return {
|
||||
credential: {
|
||||
kind: "oauth",
|
||||
id: oauthToken.id,
|
||||
name: oauthToken.clientName,
|
||||
},
|
||||
tenantId: oauthToken.tenantId,
|
||||
tenantSlug: oauthToken.tenantSlug,
|
||||
userId: oauthToken.userId,
|
||||
scopes: normalizeMcpScopes(oauthToken.scopes),
|
||||
permissions,
|
||||
};
|
||||
}
|
||||
|
||||
const apiKey = await findLegacyApiKeyByKey(token, client as unknown as LegacyApiKeyReaderClient, config.apiKeys.hashSecret, {
|
||||
allowPlaintextFallback: config.apiKeys.allowLegacyPlaintextFallback,
|
||||
});
|
||||
|
||||
if (!apiKey || !apiKey.active || apiKey.tenant.deactivatedReason) {
|
||||
throw new McpHttpError(401, "invalid_token", "API key is invalid or inactive.", {
|
||||
"WWW-Authenticate": `${authenticateHeader}, error="invalid_token"`,
|
||||
});
|
||||
}
|
||||
if (apiKey.expires && apiKey.expires.getTime() <= Date.now()) {
|
||||
throw new McpHttpError(401, "expired_token", "API key is expired.", {
|
||||
"WWW-Authenticate": `${authenticateHeader}, error="invalid_token"`,
|
||||
});
|
||||
}
|
||||
|
||||
const rateLimit = await checkMcpRateLimit({ apiKeyId: apiKey.id, tenantId: apiKey.tenantId, weight: operationCount });
|
||||
if (!rateLimit.allowed) {
|
||||
throw new McpHttpError(rateLimit.status, rateLimit.code, rateLimit.message, rateLimit.headers);
|
||||
}
|
||||
|
||||
const [permissions, moduleAllowed] = await Promise.all([
|
||||
getPermissionsByUser(client, apiKey.createdByUserId, apiKey.tenantId),
|
||||
tenantHasMcpModule(client, apiKey.tenantId, apiKey.createdByUserId),
|
||||
]);
|
||||
if (!moduleAllowed) {
|
||||
throw new McpHttpError(403, "mcp_not_enabled", "MCP is not enabled for this tenant or API-key user.");
|
||||
}
|
||||
|
||||
return {
|
||||
apiKey,
|
||||
credential: {
|
||||
kind: "api_key",
|
||||
id: apiKey.id,
|
||||
name: apiKey.alias,
|
||||
},
|
||||
tenantId: apiKey.tenantId,
|
||||
tenantSlug: apiKey.tenant.slug,
|
||||
userId: apiKey.createdByUserId,
|
||||
scopes: normalizeMcpScopes(apiKey.scopes),
|
||||
permissions,
|
||||
};
|
||||
}
|
||||
|
||||
function authenticateChallenge(config: McpRuntimeConfig): string {
|
||||
return `Bearer realm="HiveGrid MCP", resource_metadata="${config.oauth.resourceUrl}/.well-known/oauth-protected-resource"`;
|
||||
}
|
||||
|
||||
export function parseBearerToken(header: string | undefined): string | null {
|
||||
const match = header?.match(/^Bearer\s+(.+)$/i);
|
||||
const token = match?.[1]?.trim();
|
||||
return token ? token : null;
|
||||
}
|
||||
|
||||
async function getPermissionsByUser(client: DbClient, userId: string, tenantId: string): Promise<string[]> {
|
||||
const userRoles = await client.userRole.findMany({
|
||||
where: { userId, tenantId },
|
||||
include: { role: { include: { permissions: { include: { permission: { select: { name: true } } } } } } },
|
||||
});
|
||||
const names = new Set<string>();
|
||||
for (const assignment of userRoles) {
|
||||
for (const rolePermission of assignment.role.permissions) {
|
||||
names.add(rolePermission.permission.name);
|
||||
}
|
||||
}
|
||||
return [...names].sort();
|
||||
}
|
||||
|
||||
async function tenantHasMcpModule(client: DbClient, tenantId: string, userId: string): Promise<boolean> {
|
||||
const [configuration, override, subscription, permissions] = await Promise.all([
|
||||
client.tenantProductConfiguration.findUnique({
|
||||
where: { tenantId },
|
||||
select: { blueprintId: true },
|
||||
}),
|
||||
client.tenantFeatureOverride.findUnique({
|
||||
where: { tenantId_featureKey: { tenantId, featureKey: featureKeys.mcp } },
|
||||
select: { override: true },
|
||||
}),
|
||||
client.tenantSubscription.findUnique({
|
||||
where: { tenantId },
|
||||
include: {
|
||||
products: {
|
||||
where: { cancelledAt: null, endsAt: null },
|
||||
include: {
|
||||
subscriptionProduct: { include: { features: true } },
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
getPermissionsByUser(client, userId, tenantId),
|
||||
]);
|
||||
|
||||
const blueprintId = (configuration?.blueprintId as ProductBlueprintId | undefined) ?? getDefaultProductBlueprint().id;
|
||||
const blueprintFeature = getProductBlueprint(blueprintId)?.features.find((feature) => feature.featureKey === featureKeys.mcp);
|
||||
if (!blueprintFeature?.defaultEnabled) {
|
||||
return false;
|
||||
}
|
||||
const tenantOverride = normalizeTenantOverride(override?.override);
|
||||
if (tenantOverride === "disabled") {
|
||||
return false;
|
||||
}
|
||||
if (tenantOverride === "enabled" && blueprintFeature.tenantToggleable && hasRequiredPermission(blueprintFeature.requiresTenantRolePermission, permissions)) {
|
||||
return true;
|
||||
}
|
||||
const hasSubscriptionFeature = Boolean(
|
||||
subscription?.products?.some((product) =>
|
||||
product.subscriptionProduct.features.some((feature) => (feature.code ?? feature.name) === featureKeys.mcp && feature.type !== 0 && feature.value !== 0),
|
||||
),
|
||||
);
|
||||
return hasSubscriptionFeature && hasRequiredPermission(blueprintFeature.requiresTenantRolePermission, permissions);
|
||||
}
|
||||
|
||||
function hasRequiredPermission(requiredPermission: string | undefined, permissions: readonly string[]): boolean {
|
||||
return !requiredPermission || permissions.includes(requiredPermission);
|
||||
}
|
||||
|
||||
function normalizeTenantOverride(value: string | null | undefined): TenantFeatureOverride {
|
||||
return value === "enabled" || value === "disabled" || value === "inherit" ? value : "inherit";
|
||||
}
|
||||
Reference in new issue
Block a user