Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+109
-138
@@ -1,48 +1,36 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import {
|
||||
createUniqueLegacyTenantIpAddress,
|
||||
findLegacyTenantByIdOrSlug,
|
||||
getLegacyTenantMembershipsForUser,
|
||||
} from "@hivegrid/db/accounts.server";
|
||||
import { createUniqueLegacyTenantIpAddress, findLegacyTenantByIdOrSlug } from "@hivegrid/db/accounts.server";
|
||||
import {
|
||||
createLegacyApiKeyLog,
|
||||
findLegacyApiKeyByKey,
|
||||
findLegacyApiKeyByKeyWithRlsBootstrap,
|
||||
setLegacyApiKeyLogStatus as setApiKeyLogStatus,
|
||||
type LegacyApiKeySimple,
|
||||
} from "@hivegrid/db/api-keys.server";
|
||||
import type { ApiKeyLog } from "@hivegrid/db/prisma-browser";
|
||||
import { findLegacyUserWithoutPasswordById } from "@hivegrid/db/users.server";
|
||||
import { runWithRlsContext } from "@hivegrid/db/rls-context.server";
|
||||
import { Params } from "react-router";
|
||||
import { DefaultFeatures } from "~/application/dtos/shared/DefaultFeatures";
|
||||
import { getActiveTenantSubscriptions, getPlanFeatureUsage } from "./.server/subscriptionService";
|
||||
import { PlanFeatureUsageDto } from "~/application/dtos/subscriptions/PlanFeatureUsageDto";
|
||||
import { getClientIPAddress } from "../server/IpUtils";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { getTrustedClientIpOrNull } from "../server/IpUtils";
|
||||
import NotificationService from "~/modules/notifications/services/.server/NotificationService";
|
||||
import { getTranslations } from "~/locale/i18next.server";
|
||||
import { rateLimitByKey } from "./rateLimitService";
|
||||
import { cachified } from "../cache.server";
|
||||
import { loadApiConfig, loadRequiredWebConfig } from "@hivegrid/config";
|
||||
import { absoluteAppPath } from "../app/CrossHostUrls";
|
||||
import { getApiKeyLookupCacheKey, serializeApiLogSearchParams } from "../api/apiKeySecurity.server";
|
||||
import { loadCachedApiKeySnapshot } from "../api/api-key-auth-cache.server";
|
||||
import { loadTenantSecuritySnapshot } from "../db/tenant-cache.server";
|
||||
|
||||
type ApiKeyLogScope = { id: string; tenantId: string };
|
||||
|
||||
async function setApiError(request: Request, params: Params, error: string, status: number, apiKeyLogScope?: ApiKeyLogScope) {
|
||||
async function setApiError(_request: Request, _params: Params, error: string, status: number, apiKeyLogScope?: ApiKeyLogScope) {
|
||||
if (apiKeyLogScope) {
|
||||
await setApiKeyLogStatus(apiKeyLogScope, {
|
||||
error,
|
||||
status,
|
||||
startTime: null,
|
||||
});
|
||||
} else {
|
||||
await createApiKeyLog(request, {
|
||||
apiKeyId: null,
|
||||
tenantId: null,
|
||||
endpoint: new URL(request.url).pathname,
|
||||
error,
|
||||
status,
|
||||
});
|
||||
}
|
||||
throw Object.assign(new Error(error), {
|
||||
status,
|
||||
@@ -50,14 +38,6 @@ async function setApiError(request: Request, params: Params, error: string, stat
|
||||
});
|
||||
}
|
||||
|
||||
function getRequiredJwtSecret() {
|
||||
const jwtSecret = loadRequiredWebConfig().jwtSecret;
|
||||
if (!jwtSecret) {
|
||||
throw new Error("JWT_SECRET is required for API authorization.");
|
||||
}
|
||||
return jwtSecret;
|
||||
}
|
||||
|
||||
async function createApiKeyLog(
|
||||
request: Request,
|
||||
data: {
|
||||
@@ -68,7 +48,7 @@ async function createApiKeyLog(
|
||||
status?: number;
|
||||
alias?: string;
|
||||
tenantName?: string;
|
||||
},
|
||||
}
|
||||
) {
|
||||
return createLegacyApiKeyLog({
|
||||
tenantId: data.tenantId,
|
||||
@@ -78,22 +58,18 @@ async function createApiKeyLog(
|
||||
status: data.status,
|
||||
alias: data.alias,
|
||||
tenantName: data.tenantName,
|
||||
ip: getClientIPAddress(request) ?? "",
|
||||
ip: getTrustedClientIpOrNull(request) ?? "",
|
||||
method: request.method,
|
||||
params: serializeApiLogSearchParams(request),
|
||||
});
|
||||
}
|
||||
|
||||
async function getApiKeyFromHeader(key: string) {
|
||||
return cachified({
|
||||
key: getApiKeyLookupCacheKey(key),
|
||||
ttl: 1000 * 60 * 60,
|
||||
getFreshValue: () => {
|
||||
const { config } = loadApiConfig();
|
||||
return findLegacyApiKeyByKey(key, undefined, config.jwtSecret, {
|
||||
allowPlaintextFallback: config.apiKeys.allowLegacyPlaintextFallback,
|
||||
});
|
||||
},
|
||||
return loadCachedApiKeySnapshot(getApiKeyLookupCacheKey(key), () => {
|
||||
const { config } = loadApiConfig();
|
||||
return findLegacyApiKeyByKeyWithRlsBootstrap(key, undefined, config.jwtSecret, {
|
||||
allowPlaintextFallback: config.apiKeys.allowLegacyPlaintextFallback,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -130,11 +106,7 @@ function getServiceTenantScopeFromRequest(request: Request) {
|
||||
|
||||
function getTenantScopeOverridesFromRequest(request: Request) {
|
||||
const searchParams = new URL(request.url).searchParams;
|
||||
return [
|
||||
searchParams.get("tenantId"),
|
||||
request.headers.get("X-Tenant-Id"),
|
||||
request.headers.get("X-Account-Id"),
|
||||
]
|
||||
return [searchParams.get("tenantId"), request.headers.get("X-Tenant-Id"), request.headers.get("X-Account-Id")]
|
||||
.map((value) => value?.trim() ?? "")
|
||||
.filter((value) => value.length > 0);
|
||||
}
|
||||
@@ -155,51 +127,30 @@ export type ApiAccessValidation = {
|
||||
};
|
||||
|
||||
export async function validateApiKey(request: Request, params: Params): Promise<ApiAccessValidation> {
|
||||
const authorization = request.headers.get("Authorization");
|
||||
if (authorization && authorization.startsWith("Bearer ")) {
|
||||
const token = authorization.split(" ")[1];
|
||||
let userId = "";
|
||||
try {
|
||||
const decoded: any = jwt.verify(token, getRequiredJwtSecret());
|
||||
userId = decoded.userId;
|
||||
} catch (e: any) {
|
||||
throw Error("Invalid authorization token: " + e.message);
|
||||
}
|
||||
const user = await findLegacyUserWithoutPasswordById(userId);
|
||||
if (!user) {
|
||||
throw Error("Unauthorized");
|
||||
}
|
||||
let tenantId = request.headers.get("X-Account-Id") ?? request.headers.get("X-Tenant-Id");
|
||||
if (!tenantId) {
|
||||
if (!user.admin) {
|
||||
throw Error("No X-Account-Id provided");
|
||||
} else {
|
||||
tenantId = null;
|
||||
}
|
||||
}
|
||||
if (tenantId !== null) {
|
||||
const userTenants = await getLegacyTenantMembershipsForUser(user.id);
|
||||
if (!userTenants.find((t) => t.id === tenantId || t.slug === tenantId)) {
|
||||
throw Error("Unauthorized");
|
||||
}
|
||||
}
|
||||
const tenant = await findLegacyTenantByIdOrSlug(tenantId ?? "");
|
||||
return {
|
||||
userId,
|
||||
tenant: tenantId === null ? null : tenant,
|
||||
};
|
||||
const authorization = request.headers.get("Authorization")?.trim() ?? "";
|
||||
const hasBearerCredential = /^Bearer\s+/i.test(authorization);
|
||||
if (hasBearerCredential && !hasValidServiceAccessToken(request)) {
|
||||
// User/API JWTs belong to the dedicated API runtime. The web runtime only
|
||||
// accepts its exact service credential as Bearer auth; stored tenant keys
|
||||
// must use X-Api-Key so an HS256 token can never be mistaken for a session.
|
||||
throw Error("Bearer authentication is only supported for service access tokens");
|
||||
}
|
||||
|
||||
const apiKeyFromHeaders = request.headers.get("X-Api-Key") ?? "";
|
||||
if (!apiKeyFromHeaders) {
|
||||
if (!apiKeyFromHeaders && !hasBearerCredential) {
|
||||
throw Error("No X-API-Key header or Authorization token provided");
|
||||
}
|
||||
const apiAccessToken = loadRequiredWebConfig().apiAccessToken;
|
||||
if (apiAccessToken && apiKeyFromHeaders === apiAccessToken) {
|
||||
if (hasValidServiceAccessToken(request)) {
|
||||
const tenantId = getServiceTenantScopeFromRequest(request);
|
||||
if (!tenantId) {
|
||||
return { tenant: null };
|
||||
}
|
||||
const tenant = await findLegacyTenantByIdOrSlug(tenantId);
|
||||
const tenant = await runWithRlsContext({ tenantId }, () =>
|
||||
loadTenantSecuritySnapshot(tenantId, async () => {
|
||||
const current = await findLegacyTenantByIdOrSlug(tenantId);
|
||||
return current ? { id: current.id, name: current.name, slug: current.slug, deactivatedReason: current.deactivatedReason } : null;
|
||||
})
|
||||
);
|
||||
if (!tenant) {
|
||||
throw Error("Account not found: " + tenantId);
|
||||
}
|
||||
@@ -218,63 +169,73 @@ export async function validateTenantApiKey(request: Request, params: Params): Pr
|
||||
if (!apiKey) {
|
||||
throw await setApiError(request, params, "Invalid API Key", 401);
|
||||
}
|
||||
const tenantSubscription = await getActiveTenantSubscriptions(apiKey.tenantId);
|
||||
|
||||
const rateLimitResult = await rateLimitByKey({
|
||||
apiKey: apiKey.id,
|
||||
tenantId: apiKey.tenantId,
|
||||
tenantSubscription,
|
||||
});
|
||||
|
||||
const apiKeyLog = await createApiKeyLog(request, {
|
||||
apiKeyId: apiKey.id,
|
||||
tenantId: apiKey.tenantId,
|
||||
endpoint: new URL(request.url).pathname,
|
||||
});
|
||||
|
||||
if (rateLimitResult.error) {
|
||||
throw await setApiError(request, params, "Rate limit exceeded: " + rateLimitResult.error, 429, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
|
||||
createUniqueLegacyTenantIpAddress({
|
||||
ip: getClientIPAddress(request) ?? "Unknown",
|
||||
fromUrl: new URL(request.url).pathname,
|
||||
tenantId: apiKey.tenantId,
|
||||
apiKeyId: apiKey.id,
|
||||
});
|
||||
|
||||
if (apiKey.tenant.deactivatedReason) {
|
||||
throw await setApiError(request, params, "Account deactivated: " + apiKey.tenant.deactivatedReason, 403, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
if (!apiKey.active) {
|
||||
throw await setApiError(request, params, "Inactive API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
if (apiKey.expires && apiKey?.expires < new Date()) {
|
||||
throw await setApiError(request, params, "Expired API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
|
||||
const usage = await getPlanFeatureUsage(apiKey.tenantId, DefaultFeatures.API, tenantSubscription);
|
||||
if (usage && !usage.enabled) {
|
||||
await NotificationService.sendToRoles({
|
||||
channel: "admin-users",
|
||||
tenantId: null,
|
||||
notification: {
|
||||
message: `${apiKey.tenant.name} (${apiKey.tenant.slug}) API error. ${t(usage.message)}`,
|
||||
action: {
|
||||
url: absoluteAppPath(loadRequiredWebConfig().routing, apiKey.tenant.slug, "settings/api/keys"),
|
||||
},
|
||||
},
|
||||
return runWithRlsContext({ tenantId: apiKey.tenantId, userId: apiKey.createdByUserId }, async () => {
|
||||
const tenant = await loadTenantSecuritySnapshot(apiKey.tenantId, async () => {
|
||||
const current = await findLegacyTenantByIdOrSlug(apiKey.tenantId);
|
||||
return current ? { id: current.id, name: current.name, slug: current.slug, deactivatedReason: current.deactivatedReason } : null;
|
||||
});
|
||||
throw await setApiError(request, params, t(usage.message), 402, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
return {
|
||||
tenant: apiKey.tenant,
|
||||
tenantApiKey: {
|
||||
apiKey,
|
||||
apiKeyLog,
|
||||
usage,
|
||||
},
|
||||
};
|
||||
if (!tenant) {
|
||||
throw await setApiError(request, params, "Account not found", 401);
|
||||
}
|
||||
const tenantSubscription = await getActiveTenantSubscriptions(apiKey.tenantId);
|
||||
|
||||
const rateLimitResult = await rateLimitByKey({
|
||||
apiKey: apiKey.id,
|
||||
tenantId: apiKey.tenantId,
|
||||
tenantSubscription,
|
||||
});
|
||||
|
||||
const apiKeyLog = await createApiKeyLog(request, {
|
||||
apiKeyId: apiKey.id,
|
||||
tenantId: apiKey.tenantId,
|
||||
endpoint: new URL(request.url).pathname,
|
||||
});
|
||||
|
||||
if (rateLimitResult.error) {
|
||||
throw await setApiError(request, params, "Rate limit exceeded: " + rateLimitResult.error, 429, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
|
||||
createUniqueLegacyTenantIpAddress({
|
||||
ip: getTrustedClientIpOrNull(request) ?? "Unknown",
|
||||
fromUrl: new URL(request.url).pathname,
|
||||
tenantId: apiKey.tenantId,
|
||||
apiKeyId: apiKey.id,
|
||||
});
|
||||
|
||||
if (tenant.deactivatedReason) {
|
||||
throw await setApiError(request, params, "Account deactivated: " + tenant.deactivatedReason, 403, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
if (!apiKey.active) {
|
||||
throw await setApiError(request, params, "Inactive API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
if (apiKey.expires && apiKey?.expires < new Date()) {
|
||||
throw await setApiError(request, params, "Expired API Key", 400, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
|
||||
const usage = await getPlanFeatureUsage(apiKey.tenantId, DefaultFeatures.API, tenantSubscription);
|
||||
if (usage && !usage.enabled) {
|
||||
await NotificationService.sendToRoles({
|
||||
channel: "admin-users",
|
||||
tenantId: null,
|
||||
notification: {
|
||||
message: `${tenant.name} (${tenant.slug}) API error. ${t(usage.message)}`,
|
||||
action: {
|
||||
url: absoluteAppPath(loadRequiredWebConfig().routing, tenant.slug, "api/keys"),
|
||||
},
|
||||
},
|
||||
});
|
||||
throw await setApiError(request, params, t(usage.message), 402, { id: apiKeyLog.id, tenantId: apiKey.tenantId });
|
||||
}
|
||||
return {
|
||||
userId: apiKey.createdByUserId,
|
||||
tenant,
|
||||
tenantApiKey: {
|
||||
apiKey: { ...apiKey, tenant },
|
||||
apiKeyLog,
|
||||
usage,
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export type WorkflowApiAccessValidation = {
|
||||
@@ -296,7 +257,7 @@ export async function getWorkflowApiKeyFromRequest(request: Request, params: Par
|
||||
|
||||
export async function setWorkflowApiKeyLogStatus(
|
||||
apiAccessValidation: WorkflowApiAccessValidation | undefined,
|
||||
data: { error?: string; status: number; startTime: number },
|
||||
data: { error?: string; status: number; startTime: number }
|
||||
) {
|
||||
if (!apiAccessValidation?.apiKeyLog) {
|
||||
return;
|
||||
@@ -305,5 +266,15 @@ export async function setWorkflowApiKeyLogStatus(
|
||||
if (!tenantId) {
|
||||
throw new Error(`API key log ${apiAccessValidation.apiKeyLog.id} cannot be updated without tenant scope`);
|
||||
}
|
||||
await setApiKeyLogStatus({ id: apiAccessValidation.apiKeyLog.id, tenantId }, data);
|
||||
await runWithRlsContext({ tenantId, userId: apiAccessValidation.userId }, () =>
|
||||
setApiKeyLogStatus({ id: apiAccessValidation.apiKeyLog!.id, tenantId }, data)
|
||||
);
|
||||
}
|
||||
|
||||
export function runWithWorkflowApiRlsContext<T>(apiAccessValidation: WorkflowApiAccessValidation, callback: () => T): T {
|
||||
const tenantId = apiAccessValidation.tenant?.id;
|
||||
if (!tenantId) {
|
||||
throw new Error("Workflow API tenant context is required");
|
||||
}
|
||||
return runWithRlsContext({ tenantId, userId: apiAccessValidation.userId }, callback);
|
||||
}
|
||||
Reference in new issue
Block a user