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
+8
-7
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { ApiConfig } from "@toolctrl/config";
|
||||
import type { ApiConfig } from "@hivegrid/config";
|
||||
import { serializeApiAuthCookie, serializeExpiredApiAuthCookie } from "./session-cookie.js";
|
||||
|
||||
const baseConfig: ApiConfig = {
|
||||
@@ -19,7 +19,8 @@ const baseConfig: ApiConfig = {
|
||||
jwtSecret: "test-jwt-secret",
|
||||
analytics: {},
|
||||
mailjet: {},
|
||||
stripe: {},
|
||||
lago: { timeoutMs: 10000 },
|
||||
mollie: { timeoutMs: 10000 },
|
||||
apiKeys: {
|
||||
allowLegacyPlaintextFallback: true,
|
||||
},
|
||||
@@ -41,13 +42,13 @@ describe("serializeApiAuthCookie", () => {
|
||||
} satisfies ApiConfig;
|
||||
const cookie = serializeApiAuthCookie("signed.jwt.value", config);
|
||||
|
||||
expect(cookie).toContain("RJ_api_session=signed.jwt.value");
|
||||
expect(cookie).toContain("hivegrid_api_session=signed.jwt.value");
|
||||
expect(cookie).toContain("Domain=example.com");
|
||||
expect(cookie).toContain("SameSite=Lax");
|
||||
expect(cookie).toContain("Secure");
|
||||
expect(cookie).toContain("HttpOnly");
|
||||
expect(cookie).toContain("Path=/");
|
||||
expect(cookie).not.toContain("RJ_session=");
|
||||
expect(cookie).not.toContain("hivegrid_session=");
|
||||
expect(cookie).not.toContain(config.apiAccessToken);
|
||||
expect(cookie).not.toContain(config.jwtSecret);
|
||||
});
|
||||
@@ -55,7 +56,7 @@ describe("serializeApiAuthCookie", () => {
|
||||
test("omits Domain and Secure for localhost HTTP development", () => {
|
||||
const cookie = serializeApiAuthCookie("local-token", baseConfig);
|
||||
|
||||
expect(cookie).toContain("RJ_api_session=local-token");
|
||||
expect(cookie).toContain("hivegrid_api_session=local-token");
|
||||
expect(cookie).toContain("SameSite=Lax");
|
||||
expect(cookie).toContain("HttpOnly");
|
||||
expect(cookie).toContain("Path=/");
|
||||
@@ -68,7 +69,7 @@ describe("serializeApiAuthCookie", () => {
|
||||
test("URL-encodes token values without serializing config secrets", () => {
|
||||
const cookie = serializeApiAuthCookie("token with spaces;and=symbols", baseConfig);
|
||||
|
||||
expect(cookie).toContain("RJ_api_session=token%20with%20spaces%3Band%3Dsymbols");
|
||||
expect(cookie).toContain("hivegrid_api_session=token%20with%20spaces%3Band%3Dsymbols");
|
||||
expect(cookie).not.toContain("token with spaces;and=symbols");
|
||||
expect(cookie).not.toContain(baseConfig.apiAccessToken);
|
||||
expect(cookie).not.toContain(baseConfig.jwtSecret);
|
||||
@@ -88,7 +89,7 @@ describe("serializeApiAuthCookie", () => {
|
||||
} satisfies ApiConfig;
|
||||
const cookie = serializeExpiredApiAuthCookie(config);
|
||||
|
||||
expect(cookie).toContain("RJ_api_session=");
|
||||
expect(cookie).toContain("hivegrid_api_session=");
|
||||
expect(cookie).toContain("Max-Age=0");
|
||||
expect(cookie).toContain("Expires=Thu, 01 Jan 1970 00:00:00 GMT");
|
||||
expect(cookie).toContain("Domain=example.com");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { resolveApiSessionCookiePolicy, type ApiConfig } from "@toolctrl/config";
|
||||
import { resolveApiSessionCookiePolicy, type ApiConfig } from "@hivegrid/config";
|
||||
|
||||
function serializeApiAuthCookieWithValue(value: string, config: ApiConfig, extraAttributes: string[] = []) {
|
||||
const policy = resolveApiSessionCookiePolicy({
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import { createSharedStore } from "@toolctrl/shared-store";
|
||||
import { createSharedStore } from "@hivegrid/shared-store";
|
||||
|
||||
import {
|
||||
LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS,
|
||||
@@ -17,7 +17,8 @@ import {
|
||||
function request(account: string | undefined = "User@Example.com", ip: string | undefined = "203.0.113.10") {
|
||||
return {
|
||||
account,
|
||||
headers: ip ? { "x-forwarded-for": ip } : {},
|
||||
// Trusted proxy-set header — the limiter no longer trusts X-Forwarded-For.
|
||||
headers: ip ? { "cf-connecting-ip": ip } : {},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -76,14 +77,18 @@ describe("login rate limiter (shared-store)", () => {
|
||||
expect(await checkLoginRateLimit(request("fresh@example.com", "203.0.113.2"))).toMatchObject({ allowed: true });
|
||||
});
|
||||
|
||||
test("uses the first x-forwarded-for segment before x-real-ip and remote fallback", () => {
|
||||
test("prefers trusted proxy headers and ignores spoofable X-Forwarded-For", () => {
|
||||
// Cloudflare's CF-Connecting-IP wins over an attacker-forged X-Forwarded-For.
|
||||
expect(
|
||||
deriveLoginRateLimitClientIp({
|
||||
headers: new Headers({ "x-forwarded-for": " 198.51.100.7, 10.0.0.1 ", "x-real-ip": "198.51.100.8" }),
|
||||
headers: new Headers({ "x-forwarded-for": "1.2.3.4, 10.0.0.1", "cf-connecting-ip": "198.51.100.7" }),
|
||||
remoteAddress: "198.51.100.9",
|
||||
}),
|
||||
).toBe("198.51.100.7");
|
||||
// X-Real-IP is the next trusted fallback.
|
||||
expect(deriveLoginRateLimitClientIp({ headers: { "x-real-ip": "198.51.100.8" }, remoteAddress: "198.51.100.9" })).toBe("198.51.100.8");
|
||||
// A lone X-Forwarded-For is NOT trusted -> falls through to remoteAddress.
|
||||
expect(deriveLoginRateLimitClientIp({ headers: { "x-forwarded-for": "203.0.113.9" }, remoteAddress: "198.51.100.9" })).toBe("198.51.100.9");
|
||||
expect(deriveLoginRateLimitClientIp({ remoteAddress: "198.51.100.9" })).toBe("198.51.100.9");
|
||||
expect(deriveLoginRateLimitClientIp({})).toBe("unknown");
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createFixedWindowRateLimiter, type FixedWindowRateLimiter, type SharedStore } from "@toolctrl/shared-store";
|
||||
import { createFixedWindowRateLimiter, type FixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
|
||||
import { getSharedStore } from "../shared-store.js";
|
||||
|
||||
export const LOGIN_RATE_LIMIT_WINDOW_MS = 60_000;
|
||||
@@ -158,16 +158,17 @@ export function __resetLoginRateLimitStoreForTests(): void {
|
||||
storeFactory = () => getSharedStore();
|
||||
}
|
||||
|
||||
export function deriveLoginRateLimitClientIp(request: Pick<LoginRateLimitRequest, "headers" | "remoteAddress">): string {
|
||||
const forwardedFor = readHeader(request.headers, "x-forwarded-for");
|
||||
const forwardedClient = forwardedFor?.split(",")[0]?.trim();
|
||||
if (forwardedClient) {
|
||||
return forwardedClient;
|
||||
}
|
||||
// Trusted, proxy-set headers only. The leftmost X-Forwarded-For value is
|
||||
// client-controlled, so keying the login throttle on it let an attacker reset
|
||||
// their bucket by rotating the header (credential-stuffing bypass).
|
||||
const TRUSTED_LOGIN_IP_HEADERS = ["cf-connecting-ip", "true-client-ip", "x-real-ip"] as const;
|
||||
|
||||
const realIp = readHeader(request.headers, "x-real-ip")?.trim();
|
||||
if (realIp) {
|
||||
return realIp;
|
||||
export function deriveLoginRateLimitClientIp(request: Pick<LoginRateLimitRequest, "headers" | "remoteAddress">): string {
|
||||
for (const headerName of TRUSTED_LOGIN_IP_HEADERS) {
|
||||
const value = readHeader(request.headers, headerName)?.trim();
|
||||
if (value) {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
const remoteAddress = request.remoteAddress?.trim();
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { dirname, resolve } from "node:path";
|
||||
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
const appSourcePath = resolve(dirname(fileURLToPath(import.meta.url)), "../app.ts");
|
||||
const entityRowRoutesSourcePath = resolve(dirname(fileURLToPath(import.meta.url)), "../routes/entity-row-routes.ts");
|
||||
const relationshipRoutesSourcePath = resolve(dirname(fileURLToPath(import.meta.url)), "../routes/relationship-routes.ts");
|
||||
|
||||
function read(path: string) {
|
||||
return readFileSync(path, "utf8");
|
||||
}
|
||||
|
||||
describe("API permission helper wiring", () => {
|
||||
// The legacy v1 row + relationship routes were extracted out of
|
||||
// `app.ts` into dedicated route modules. The assertions here pin the
|
||||
// shared `authorizeApiEntityRowScope` / `authorizeApiRelationshipScope`
|
||||
// helpers to those extraction sites so a regression that re-inlines
|
||||
// permission checks in `app.ts` (or a different file) fails CI.
|
||||
test("entity-row routes call the shared API permission helper", () => {
|
||||
const src = read(entityRowRoutesSourcePath);
|
||||
expect(src).toContain('import { authorizeApiEntityRowScope } from "../auth/permission.js";');
|
||||
expect(src.match(/authorizeApiEntityRowScope\(/g)).toHaveLength(5);
|
||||
});
|
||||
|
||||
test("relationship routes call the shared API permission helper", () => {
|
||||
const src = read(relationshipRoutesSourcePath);
|
||||
expect(src).toContain('import { authorizeApiRelationshipScope } from "../auth/permission.js";');
|
||||
expect(src.match(/authorizeApiRelationshipScope\(/g)).toHaveLength(3);
|
||||
});
|
||||
|
||||
test("app.ts does not define or call stale local entity-row scope helpers", () => {
|
||||
const appSource = read(appSourcePath);
|
||||
|
||||
expect(appSource).not.toMatch(/function\s+authorizeEntityRowScope\b/);
|
||||
expect(appSource).not.toMatch(/const\s+authorizeEntityRowScope\b/);
|
||||
expect(appSource).not.toMatch(/=>\s*authorizeEntityRowScope\(/);
|
||||
expect(appSource).not.toMatch(/\bauthorizeEntityRowScope\(/);
|
||||
expect(appSource).not.toMatch(/\bgetEntityPermission\b/);
|
||||
expect(appSource).not.toMatch(/\bverifyUserHasPermission\b/);
|
||||
});
|
||||
});
|
||||
@@ -1,187 +0,0 @@
|
||||
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
|
||||
import type { LegacyEntity } from "@toolctrl/db/entities.server";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { createServicePrincipal } from "../auth.js";
|
||||
import { authorizeApiEntityRowScope, authorizeApiRelationshipScope } from "./permission.js";
|
||||
import { createStoredApiKeyPrincipal, type ApiScopeResult } from "./scope.js";
|
||||
|
||||
const NOW = new Date("2026-01-15T12:00:00.000Z");
|
||||
|
||||
function buildEntity(overrides: Partial<LegacyEntity> = {}): LegacyEntity {
|
||||
return {
|
||||
id: "entity-1",
|
||||
name: "contacts",
|
||||
description: null,
|
||||
url: null,
|
||||
multiTenant: true,
|
||||
isPublic: false,
|
||||
useAsUser: false,
|
||||
createdById: null,
|
||||
createdAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function buildApiKey(overrides: Partial<LegacyApiKeySimple> = {}): LegacyApiKeySimple {
|
||||
return {
|
||||
id: "api-key-1",
|
||||
alias: "Production key",
|
||||
expires: new Date("2026-02-01T00:00:00.000Z"),
|
||||
tenantId: "tenant-1",
|
||||
active: true,
|
||||
entities: [
|
||||
{
|
||||
entityId: "entity-1",
|
||||
create: true,
|
||||
read: true,
|
||||
update: true,
|
||||
delete: false,
|
||||
},
|
||||
{
|
||||
entityId: "child-entity",
|
||||
create: true,
|
||||
read: true,
|
||||
update: false,
|
||||
delete: false,
|
||||
},
|
||||
],
|
||||
tenant: {
|
||||
id: "tenant-1",
|
||||
name: "Tenant One",
|
||||
slug: "tenant-one",
|
||||
deactivatedReason: null,
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function expectRedactedDeny(result: ApiScopeResult, reason: string) {
|
||||
expect(result).toEqual({
|
||||
allowed: false,
|
||||
principalType: "api-key",
|
||||
reason,
|
||||
code: "FORBIDDEN_API_KEY_SCOPE",
|
||||
});
|
||||
const serialized = JSON.stringify(result);
|
||||
expect(serialized).not.toContain("plaintext-secret");
|
||||
expect(serialized).not.toContain("hash-value");
|
||||
expect(serialized).not.toContain("service-token-value");
|
||||
}
|
||||
|
||||
describe("authorizeApiEntityRowScope", () => {
|
||||
test("allows entity row operations when the stored API key has the entity operation scope", () => {
|
||||
const result = authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
|
||||
tenantId: "tenant-1",
|
||||
entity: buildEntity(),
|
||||
operation: "read",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
allowed: true,
|
||||
principalType: "api-key",
|
||||
});
|
||||
});
|
||||
|
||||
test("denies entity row operations when the stored API key lacks the entity operation scope", () => {
|
||||
const result = authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
|
||||
tenantId: "tenant-1",
|
||||
entity: buildEntity(),
|
||||
operation: "delete",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expectRedactedDeny(result, "operation_permission_missing");
|
||||
});
|
||||
|
||||
test("fails closed for malformed legacy entities without an id", () => {
|
||||
expect(() =>
|
||||
authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
|
||||
tenantId: "tenant-1",
|
||||
entity: buildEntity({ id: "" }),
|
||||
operation: "read",
|
||||
now: NOW,
|
||||
}),
|
||||
).toThrow("Entity is missing an id.");
|
||||
});
|
||||
|
||||
test("denies stored API keys when tenant scope cannot be resolved", () => {
|
||||
const result = authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
|
||||
tenantId: null,
|
||||
entity: buildEntity(),
|
||||
operation: "read",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expectRedactedDeny(result, "tenant_mismatch");
|
||||
});
|
||||
});
|
||||
|
||||
describe("authorizeApiRelationshipScope", () => {
|
||||
test("allows service-token principals for relationship operations without entity scopes", () => {
|
||||
const result = authorizeApiRelationshipScope(createServicePrincipal(), {
|
||||
tenantId: "tenant-1",
|
||||
parentEntityId: "missing-parent",
|
||||
childEntityId: "missing-child",
|
||||
operation: "delete",
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
allowed: true,
|
||||
principalType: "service-token",
|
||||
});
|
||||
});
|
||||
|
||||
test("denies relationship operations when the parent entity lacks the requested operation", () => {
|
||||
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
|
||||
tenantId: "tenant-1",
|
||||
parentEntityId: "missing-parent",
|
||||
childEntityId: "child-entity",
|
||||
operation: "read",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expectRedactedDeny(result, "entity_permission_missing");
|
||||
});
|
||||
|
||||
test("denies relationship operations when the child entity lacks the requested operation", () => {
|
||||
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
|
||||
tenantId: "tenant-1",
|
||||
parentEntityId: "entity-1",
|
||||
childEntityId: "child-entity",
|
||||
operation: "update",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expectRedactedDeny(result, "operation_permission_missing");
|
||||
});
|
||||
|
||||
test("allows relationship operations when parent and child entities both include the requested operation", () => {
|
||||
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
|
||||
tenantId: "tenant-1",
|
||||
parentEntityId: "entity-1",
|
||||
childEntityId: "child-entity",
|
||||
operation: "create",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expect(result).toEqual({
|
||||
allowed: true,
|
||||
principalType: "api-key",
|
||||
});
|
||||
});
|
||||
|
||||
test("denies stored API keys for relationship operations when tenant scope cannot be resolved", () => {
|
||||
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
|
||||
tenantId: null,
|
||||
parentEntityId: "entity-1",
|
||||
childEntityId: "child-entity",
|
||||
operation: "read",
|
||||
now: NOW,
|
||||
});
|
||||
|
||||
expectRedactedDeny(result, "tenant_mismatch");
|
||||
});
|
||||
});
|
||||
@@ -1,54 +0,0 @@
|
||||
import type { LegacyEntity } from "@toolctrl/db/entities.server";
|
||||
|
||||
import { authorizeApiScope, type ApiKeyScopeOperation, type ApiScopedPrincipal, type ApiScopeResult } from "./scope.js";
|
||||
|
||||
export type ApiEntityRowScopeRequest = {
|
||||
tenantId: string | null;
|
||||
entity: LegacyEntity;
|
||||
operation: ApiKeyScopeOperation;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type ApiRelationshipScopeRequest = {
|
||||
tenantId: string | null;
|
||||
parentEntityId: string;
|
||||
childEntityId: string;
|
||||
operation: ApiKeyScopeOperation;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export function authorizeApiEntityRowScope(principal: ApiScopedPrincipal, request: ApiEntityRowScopeRequest): ApiScopeResult {
|
||||
return authorizeApiScope(principal, {
|
||||
tenantId: request.tenantId ?? "",
|
||||
entityId: getLegacyEntityId(request.entity),
|
||||
operation: request.operation,
|
||||
now: request.now,
|
||||
});
|
||||
}
|
||||
|
||||
export function authorizeApiRelationshipScope(principal: ApiScopedPrincipal, request: ApiRelationshipScopeRequest): ApiScopeResult {
|
||||
const parentScope = authorizeApiScope(principal, {
|
||||
tenantId: request.tenantId ?? "",
|
||||
entityId: request.parentEntityId,
|
||||
operation: request.operation,
|
||||
now: request.now,
|
||||
});
|
||||
|
||||
if (!parentScope.allowed) {
|
||||
return parentScope;
|
||||
}
|
||||
|
||||
return authorizeApiScope(principal, {
|
||||
tenantId: request.tenantId ?? "",
|
||||
entityId: request.childEntityId,
|
||||
operation: request.operation,
|
||||
now: request.now,
|
||||
});
|
||||
}
|
||||
|
||||
function getLegacyEntityId(entity: LegacyEntity) {
|
||||
if (entity && typeof entity === "object" && "id" in entity && typeof entity.id === "string" && entity.id) {
|
||||
return entity.id;
|
||||
}
|
||||
throw new Error("Entity is missing an id.");
|
||||
}
|
||||
@@ -1,130 +1,99 @@
|
||||
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
|
||||
|
||||
import { createServicePrincipal } from "../auth.js";
|
||||
import { authorizeApiScope, createStoredApiKeyPrincipal, type ApiScopeResult } from "./scope.js";
|
||||
import type { ServicePrincipal } from "../auth.js";
|
||||
import { createStoredApiKeyPrincipal, resolveApiTenantScope, type ApiScopedPrincipal } from "./scope.js";
|
||||
|
||||
const NOW = new Date("2026-01-15T12:00:00.000Z");
|
||||
// R-P6B-β (AD-2): the entity-builder API-key *entity-scope* matrix was removed
|
||||
// with the generic entity REST API; this test keeps the surviving tenant-scope
|
||||
// resolution (service tokens + stored API keys) fully covered.
|
||||
|
||||
function buildApiKey(overrides: Partial<LegacyApiKeySimple> = {}): LegacyApiKeySimple {
|
||||
return {
|
||||
id: "api-key-1",
|
||||
alias: "Production key",
|
||||
expires: new Date("2026-02-01T00:00:00.000Z"),
|
||||
tenantId: "tenant-1",
|
||||
active: true,
|
||||
entities: [
|
||||
{
|
||||
entityId: "entity-1",
|
||||
create: true,
|
||||
read: true,
|
||||
update: true,
|
||||
delete: false,
|
||||
},
|
||||
],
|
||||
tenant: {
|
||||
id: "tenant-1",
|
||||
name: "Tenant One",
|
||||
slug: "tenant-one",
|
||||
deactivatedReason: null,
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
const serviceTokenPrincipal: ApiScopedPrincipal = { type: "service-token" } as ServicePrincipal;
|
||||
|
||||
function apiKeyPrincipal(overrides: Partial<{ active: boolean; expires: Date | null; tenantId: string; tenantDbId: string; deactivatedReason: string | null }> = {}) {
|
||||
const { active = true, expires = null, tenantId = "tenant_1", tenantDbId = "tenant_1", deactivatedReason = null } = overrides;
|
||||
const apiKey = {
|
||||
id: "api_key_1",
|
||||
tenantId,
|
||||
active,
|
||||
expires,
|
||||
tenant: { id: tenantDbId, deactivatedReason },
|
||||
} as unknown as LegacyApiKeySimple;
|
||||
return createStoredApiKeyPrincipal(apiKey);
|
||||
}
|
||||
|
||||
function authorize(apiKey: LegacyApiKeySimple, overrides: Partial<Parameters<typeof authorizeApiScope>[1]> = {}): ApiScopeResult {
|
||||
return authorizeApiScope(createStoredApiKeyPrincipal(apiKey), {
|
||||
tenantId: "tenant-1",
|
||||
entityId: "entity-1",
|
||||
operation: "read",
|
||||
now: NOW,
|
||||
...overrides,
|
||||
describe("createStoredApiKeyPrincipal", () => {
|
||||
it("wraps the API key in a stored-api-key principal", () => {
|
||||
const apiKey = { id: "api_key_1" } as unknown as LegacyApiKeySimple;
|
||||
expect(createStoredApiKeyPrincipal(apiKey)).toEqual({ type: "api-key", apiKey });
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
function expectRedactedDeny(result: ApiScopeResult, reason: string) {
|
||||
expect(result).toEqual({
|
||||
allowed: false,
|
||||
principalType: "api-key",
|
||||
reason,
|
||||
code: "FORBIDDEN_API_KEY_SCOPE",
|
||||
});
|
||||
const serialized = JSON.stringify(result);
|
||||
expect(serialized).not.toContain("plaintext-secret");
|
||||
expect(serialized).not.toContain("hash-value");
|
||||
expect(serialized).not.toContain("service-token");
|
||||
}
|
||||
|
||||
describe("authorizeApiScope", () => {
|
||||
test("allows service-token principals for every scoped operation", () => {
|
||||
const principal = createServicePrincipal();
|
||||
|
||||
expect(
|
||||
authorizeApiScope(principal, {
|
||||
tenantId: "other-tenant",
|
||||
entityId: "unknown-entity",
|
||||
operation: "delete",
|
||||
now: NOW,
|
||||
}),
|
||||
).toEqual({
|
||||
describe("resolveApiTenantScope", () => {
|
||||
it("allows service tokens for the requested tenant (including null)", () => {
|
||||
expect(resolveApiTenantScope(serviceTokenPrincipal, "tenant_9")).toEqual({
|
||||
allowed: true,
|
||||
principalType: "service-token",
|
||||
tenantId: "tenant_9",
|
||||
});
|
||||
expect(resolveApiTenantScope(serviceTokenPrincipal, null)).toEqual({
|
||||
allowed: true,
|
||||
principalType: "service-token",
|
||||
tenantId: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("allows active stored API keys with matching tenant, entity, and CRUD permission", () => {
|
||||
expect(authorize(buildApiKey(), { operation: "create" })).toEqual({
|
||||
allowed: true,
|
||||
principalType: "api-key",
|
||||
it("denies inactive API keys", () => {
|
||||
expect(resolveApiTenantScope(apiKeyPrincipal({ active: false }), null)).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "api_key_inactive",
|
||||
code: "FORBIDDEN_API_KEY_SCOPE",
|
||||
});
|
||||
});
|
||||
|
||||
test("denies inactive stored API keys", () => {
|
||||
expectRedactedDeny(authorize(buildApiKey({ active: false })), "api_key_inactive");
|
||||
it("denies expired API keys (expiry at/under now)", () => {
|
||||
const now = new Date("2026-06-30T12:00:00.000Z");
|
||||
expect(resolveApiTenantScope(apiKeyPrincipal({ expires: new Date("2026-06-30T11:59:59.000Z") }), null, now)).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "api_key_expired",
|
||||
});
|
||||
});
|
||||
|
||||
test("denies expired stored API keys", () => {
|
||||
expectRedactedDeny(authorize(buildApiKey({ expires: new Date("2026-01-01T00:00:00.000Z") })), "api_key_expired");
|
||||
it("denies API keys whose tenant is deactivated", () => {
|
||||
expect(resolveApiTenantScope(apiKeyPrincipal({ deactivatedReason: "fraud" }), null)).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "tenant_deactivated",
|
||||
});
|
||||
});
|
||||
|
||||
test("denies stored API keys for deactivated tenants", () => {
|
||||
expectRedactedDeny(
|
||||
authorize(
|
||||
buildApiKey({
|
||||
tenant: {
|
||||
id: "tenant-1",
|
||||
name: "Tenant One",
|
||||
slug: "tenant-one",
|
||||
deactivatedReason: "billing_issue",
|
||||
},
|
||||
}),
|
||||
),
|
||||
"tenant_deactivated",
|
||||
);
|
||||
it("denies a tenant/tenant.id row mismatch", () => {
|
||||
expect(resolveApiTenantScope(apiKeyPrincipal({ tenantId: "tenant_1", tenantDbId: "tenant_2" }), null)).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "tenant_mismatch",
|
||||
});
|
||||
});
|
||||
|
||||
test("denies stored API keys whose tenant does not match the request tenant", () => {
|
||||
expectRedactedDeny(authorize(buildApiKey(), { tenantId: "tenant-2" }), "tenant_mismatch");
|
||||
expectRedactedDeny(
|
||||
authorize(
|
||||
buildApiKey({
|
||||
tenant: {
|
||||
id: "tenant-2",
|
||||
name: "Tenant Two",
|
||||
slug: "tenant-two",
|
||||
deactivatedReason: null,
|
||||
},
|
||||
}),
|
||||
),
|
||||
"tenant_mismatch",
|
||||
);
|
||||
it("denies a requested tenant that does not match the key tenant", () => {
|
||||
expect(resolveApiTenantScope(apiKeyPrincipal({ tenantId: "tenant_1" }), "tenant_2")).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "tenant_mismatch",
|
||||
});
|
||||
});
|
||||
|
||||
test("denies stored API keys missing the requested entity permission", () => {
|
||||
expectRedactedDeny(authorize(buildApiKey(), { entityId: "entity-2" }), "entity_permission_missing");
|
||||
it("allows a valid API key with no requested tenant and with a future expiry", () => {
|
||||
const now = new Date("2026-06-30T12:00:00.000Z");
|
||||
expect(resolveApiTenantScope(apiKeyPrincipal({ expires: new Date("2026-07-30T12:00:00.000Z") }), null, now)).toEqual({
|
||||
allowed: true,
|
||||
principalType: "api-key",
|
||||
tenantId: "tenant_1",
|
||||
});
|
||||
});
|
||||
|
||||
test("denies stored API keys missing the requested CRUD operation permission", () => {
|
||||
expectRedactedDeny(authorize(buildApiKey(), { operation: "delete" }), "operation_permission_missing");
|
||||
it("allows a valid API key when the requested tenant matches", () => {
|
||||
expect(resolveApiTenantScope(apiKeyPrincipal({ tenantId: "tenant_1" }), "tenant_1")).toEqual({
|
||||
allowed: true,
|
||||
principalType: "api-key",
|
||||
tenantId: "tenant_1",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
|
||||
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
|
||||
|
||||
import type { ServicePrincipal } from "../auth.js";
|
||||
|
||||
@@ -13,20 +13,11 @@ export type StoredApiKeyPrincipal = {
|
||||
|
||||
export type ApiScopedPrincipal = ServicePrincipal | StoredApiKeyPrincipal;
|
||||
|
||||
export type ApiScopeRequest = {
|
||||
tenantId: string;
|
||||
entityId: string;
|
||||
operation: ApiKeyScopeOperation;
|
||||
now?: Date;
|
||||
};
|
||||
|
||||
export type ApiScopeDenyReason =
|
||||
| "api_key_inactive"
|
||||
| "api_key_expired"
|
||||
| "tenant_deactivated"
|
||||
| "tenant_mismatch"
|
||||
| "entity_permission_missing"
|
||||
| "operation_permission_missing";
|
||||
| "tenant_mismatch";
|
||||
|
||||
export type ApiScopeAllowed = {
|
||||
allowed: true;
|
||||
@@ -44,8 +35,6 @@ export type ApiScopeDenied = {
|
||||
code: "FORBIDDEN_API_KEY_SCOPE";
|
||||
};
|
||||
|
||||
export type ApiScopeResult = ApiScopeAllowed | ApiScopeDenied;
|
||||
|
||||
function deny(principalType: ApiScopedPrincipal["type"], reason: ApiScopeDenyReason): ApiScopeDenied {
|
||||
return {
|
||||
allowed: false,
|
||||
@@ -62,48 +51,6 @@ export function createStoredApiKeyPrincipal(apiKey: LegacyApiKeySimple): StoredA
|
||||
};
|
||||
}
|
||||
|
||||
export function authorizeApiScope(principal: ApiScopedPrincipal, request: ApiScopeRequest): ApiScopeResult {
|
||||
if (principal.type === "service-token") {
|
||||
return {
|
||||
allowed: true,
|
||||
principalType: principal.type,
|
||||
};
|
||||
}
|
||||
|
||||
const { apiKey } = principal;
|
||||
|
||||
if (!apiKey.active) {
|
||||
return deny(principal.type, "api_key_inactive");
|
||||
}
|
||||
|
||||
if (apiKey.expires && apiKey.expires.getTime() <= (request.now ?? new Date()).getTime()) {
|
||||
return deny(principal.type, "api_key_expired");
|
||||
}
|
||||
|
||||
if (apiKey.tenant.deactivatedReason) {
|
||||
return deny(principal.type, "tenant_deactivated");
|
||||
}
|
||||
|
||||
if (apiKey.tenantId !== request.tenantId || apiKey.tenant.id !== request.tenantId) {
|
||||
return deny(principal.type, "tenant_mismatch");
|
||||
}
|
||||
|
||||
const entityPermission = apiKey.entities.find((entity) => entity.entityId === request.entityId);
|
||||
|
||||
if (!entityPermission) {
|
||||
return deny(principal.type, "entity_permission_missing");
|
||||
}
|
||||
|
||||
if (!entityPermission[request.operation]) {
|
||||
return deny(principal.type, "operation_permission_missing");
|
||||
}
|
||||
|
||||
return {
|
||||
allowed: true,
|
||||
principalType: principal.type,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveApiTenantScope(principal: ApiScopedPrincipal, requestedTenantId: string | null, now = new Date()): ApiTenantScopeAllowed | ApiScopeDenied {
|
||||
if (principal.type === "service-token") {
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user