mirror of
https://github.com/fosrl/pangolin.git
synced 2026-09-22 13:59:05 +02:00
Merge remote-tracking branch 'upstream/dev' into feature-response-headers
# Conflicts: # server/db/pg/schema/schema.ts # server/lib/blueprints/proxyResources.ts # server/routers/resource/getResource.ts # src/app/[orgId]/settings/resources/proxy/[niceId]/proxy/page.tsx # src/components/HealthCheckCredenza.tsx
This commit is contained in:
@@ -22,7 +22,7 @@ const addEmailToResourceWhitelistBodySchema = z.strictObject({
|
||||
});
|
||||
|
||||
const addEmailToResourceWhitelistParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
@@ -40,7 +40,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function addEmailToResourceWhitelist(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, resources } from "@server/db";
|
||||
import { roleResources, roles } from "@server/db";
|
||||
import { roleResources, roles, rolePolicies } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -28,7 +28,8 @@ const addRoleToResourceParamsSchema = z
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/resource/{resourceId}/roles/add",
|
||||
description: "Add a single role to a resource.",
|
||||
description:
|
||||
"Add a single role to a resource. When the resource has an inline policy defined (no shared resource policy assigned), the role is added to the inline policy instead of directly to the resource.",
|
||||
tags: [OpenAPITags.PublicResource, OpenAPITags.Role],
|
||||
request: {
|
||||
params: addRoleToResourceParamsSchema,
|
||||
@@ -40,7 +41,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function addRoleToResource(
|
||||
@@ -116,31 +132,64 @@ export async function addRoleToResource(
|
||||
);
|
||||
}
|
||||
|
||||
// Check if role already exists in resource
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(roleResources)
|
||||
.where(
|
||||
and(
|
||||
eq(roleResources.resourceId, resourceId),
|
||||
eq(roleResources.roleId, roleId)
|
||||
)
|
||||
);
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
if (existingEntry.length > 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.CONFLICT,
|
||||
"Role already assigned to resource"
|
||||
)
|
||||
);
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
|
||||
// Check if role already exists in the inline policy
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(rolePolicies)
|
||||
.where(
|
||||
and(
|
||||
eq(rolePolicies.resourcePolicyId, policyId),
|
||||
eq(rolePolicies.roleId, roleId)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingEntry.length > 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.CONFLICT,
|
||||
"Role already assigned to resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db.insert(rolePolicies).values({
|
||||
roleId,
|
||||
resourcePolicyId: policyId
|
||||
});
|
||||
} else {
|
||||
// Check if role already exists in resource
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(roleResources)
|
||||
.where(
|
||||
and(
|
||||
eq(roleResources.resourceId, resourceId),
|
||||
eq(roleResources.roleId, roleId)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingEntry.length > 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.CONFLICT,
|
||||
"Role already assigned to resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db.insert(roleResources).values({
|
||||
roleId,
|
||||
resourceId
|
||||
});
|
||||
}
|
||||
|
||||
await db.insert(roleResources).values({
|
||||
roleId,
|
||||
resourceId
|
||||
});
|
||||
|
||||
return response(res, {
|
||||
data: {},
|
||||
success: true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, resources } from "@server/db";
|
||||
import { userResources } from "@server/db";
|
||||
import { userResources, userPolicies } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -28,7 +28,8 @@ const addUserToResourceParamsSchema = z
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/resource/{resourceId}/users/add",
|
||||
description: "Add a single user to a resource.",
|
||||
description:
|
||||
"Add a single user to a resource. When the resource has an inline policy defined (no shared resource policy assigned), the user is added to the inline policy instead of directly to the resource.",
|
||||
tags: [OpenAPITags.PublicResource, OpenAPITags.User],
|
||||
request: {
|
||||
params: addUserToResourceParamsSchema,
|
||||
@@ -40,7 +41,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function addUserToResource(
|
||||
@@ -88,31 +104,64 @@ export async function addUserToResource(
|
||||
);
|
||||
}
|
||||
|
||||
// Check if user already exists in resource
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(userResources)
|
||||
.where(
|
||||
and(
|
||||
eq(userResources.resourceId, resourceId),
|
||||
eq(userResources.userId, userId)
|
||||
)
|
||||
);
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
if (existingEntry.length > 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.CONFLICT,
|
||||
"User already assigned to resource"
|
||||
)
|
||||
);
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
|
||||
// Check if user already exists in the inline policy
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(userPolicies)
|
||||
.where(
|
||||
and(
|
||||
eq(userPolicies.resourcePolicyId, policyId),
|
||||
eq(userPolicies.userId, userId)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingEntry.length > 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.CONFLICT,
|
||||
"User already assigned to resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db.insert(userPolicies).values({
|
||||
userId,
|
||||
resourcePolicyId: policyId
|
||||
});
|
||||
} else {
|
||||
// Check if user already exists in resource
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(userResources)
|
||||
.where(
|
||||
and(
|
||||
eq(userResources.resourceId, resourceId),
|
||||
eq(userResources.userId, userId)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingEntry.length > 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.CONFLICT,
|
||||
"User already assigned to resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db.insert(userResources).values({
|
||||
userId,
|
||||
resourceId
|
||||
});
|
||||
}
|
||||
|
||||
await db.insert(userResources).values({
|
||||
userId,
|
||||
resourceId
|
||||
});
|
||||
|
||||
return response(res, {
|
||||
data: {},
|
||||
success: true,
|
||||
|
||||
@@ -167,7 +167,12 @@ export async function authWithAccessToken(
|
||||
|
||||
let redirectUrl = `${resource.ssl ? "https" : "http"}://${resource.fullDomain}`;
|
||||
const postAuthPath = normalizePostAuthPath(resource.postAuthPath);
|
||||
if (postAuthPath) {
|
||||
if (tokenItem.path) {
|
||||
// add the path from the access token to the redirect URL, ensuring there is exactly one slash between the domain and the path
|
||||
redirectUrl =
|
||||
redirectUrl.replace(/\/?$/, "/") +
|
||||
tokenItem.path.replace(/^\/?/, "");
|
||||
} else if (postAuthPath) {
|
||||
redirectUrl = redirectUrl + postAuthPath;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
import { verify } from "@node-rs/argon2";
|
||||
import { generateSessionToken } from "@server/auth/sessions/app";
|
||||
import { db } from "@server/db";
|
||||
import { orgs, resourcePassword, resources } from "@server/db";
|
||||
import {
|
||||
orgs,
|
||||
resourcePassword,
|
||||
resourcePolicies,
|
||||
resourcePolicyPassword,
|
||||
resources
|
||||
} from "@server/db";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import response from "@server/lib/response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { alias } from "@server/db";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import createHttpError from "http-errors";
|
||||
import { z } from "zod";
|
||||
@@ -20,7 +27,7 @@ export const authWithPasswordBodySchema = z.strictObject({
|
||||
});
|
||||
|
||||
export const authWithPasswordParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
export type AuthWithPasswordResponse = {
|
||||
@@ -58,20 +65,64 @@ export async function authWithPassword(
|
||||
const { password } = parsedBody.data;
|
||||
|
||||
try {
|
||||
const sharedPolicy = alias(resourcePolicies, "sharedPolicy");
|
||||
const defaultPolicy = alias(resourcePolicies, "defaultPolicy");
|
||||
const sharedPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"sharedPolicyPassword"
|
||||
);
|
||||
const defaultPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"defaultPolicyPassword"
|
||||
);
|
||||
|
||||
const [result] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.leftJoin(orgs, eq(orgs.orgId, resources.orgId))
|
||||
.leftJoin(
|
||||
sharedPolicy,
|
||||
eq(sharedPolicy.resourcePolicyId, resources.resourcePolicyId)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicyPassword,
|
||||
eq(
|
||||
sharedPolicyPassword.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicy,
|
||||
eq(
|
||||
defaultPolicy.resourcePolicyId,
|
||||
resources.defaultResourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyPassword,
|
||||
eq(
|
||||
defaultPolicyPassword.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
resourcePassword,
|
||||
eq(resourcePassword.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(orgs, eq(orgs.orgId, resources.orgId))
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
const resource = result?.resources;
|
||||
const org = result?.orgs;
|
||||
const definedPassword = result?.resourcePassword;
|
||||
|
||||
// Shared policy takes precedence, then default (inline) policy, then resource-level
|
||||
const policyPassword =
|
||||
result?.sharedPolicyPassword ??
|
||||
result?.defaultPolicyPassword ??
|
||||
null;
|
||||
const definedPassword =
|
||||
policyPassword ?? result?.resourcePassword ?? null;
|
||||
const isPolicyPassword = !!policyPassword;
|
||||
|
||||
if (!org) {
|
||||
return next(
|
||||
@@ -89,10 +140,7 @@ export async function authWithPassword(
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.UNAUTHORIZED,
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Resource has no password protection"
|
||||
)
|
||||
"Resource has no password protection"
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -126,7 +174,10 @@ export async function authWithPassword(
|
||||
await createResourceSession({
|
||||
resourceId,
|
||||
token,
|
||||
passwordId: definedPassword.passwordId,
|
||||
passwordId: isPolicyPassword ? null : definedPassword.passwordId,
|
||||
policyPasswordId: isPolicyPassword
|
||||
? definedPassword.passwordId
|
||||
: null,
|
||||
isRequestToken: true,
|
||||
expiresAt: Date.now() + 1000 * 30, // 30 seconds
|
||||
sessionLength: 1000 * 30,
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
import { generateSessionToken } from "@server/auth/sessions/app";
|
||||
import { db } from "@server/db";
|
||||
import { orgs, resourcePincode, resources } from "@server/db";
|
||||
import {
|
||||
orgs,
|
||||
resourcePincode,
|
||||
resourcePolicies,
|
||||
resourcePolicyPincode,
|
||||
resources
|
||||
} from "@server/db";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import response from "@server/lib/response";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { alias } from "@server/db";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import createHttpError from "http-errors";
|
||||
import { z } from "zod";
|
||||
@@ -19,7 +26,7 @@ export const authWithPincodeBodySchema = z.strictObject({
|
||||
});
|
||||
|
||||
export const authWithPincodeParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
export type AuthWithPincodeResponse = {
|
||||
@@ -57,20 +64,61 @@ export async function authWithPincode(
|
||||
const { pincode } = parsedBody.data;
|
||||
|
||||
try {
|
||||
const sharedPolicy = alias(resourcePolicies, "sharedPolicy");
|
||||
const defaultPolicy = alias(resourcePolicies, "defaultPolicy");
|
||||
const sharedPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"sharedPolicyPincode"
|
||||
);
|
||||
const defaultPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"defaultPolicyPincode"
|
||||
);
|
||||
|
||||
const [result] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.leftJoin(orgs, eq(orgs.orgId, resources.orgId))
|
||||
.leftJoin(
|
||||
sharedPolicy,
|
||||
eq(sharedPolicy.resourcePolicyId, resources.resourcePolicyId)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicyPincode,
|
||||
eq(
|
||||
sharedPolicyPincode.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicy,
|
||||
eq(
|
||||
defaultPolicy.resourcePolicyId,
|
||||
resources.defaultResourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyPincode,
|
||||
eq(
|
||||
defaultPolicyPincode.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
resourcePincode,
|
||||
eq(resourcePincode.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(orgs, eq(orgs.orgId, resources.orgId))
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
const resource = result?.resources;
|
||||
const org = result?.orgs;
|
||||
const definedPincode = result?.resourcePincode;
|
||||
|
||||
// Shared policy takes precedence, then default (inline) policy, then resource-level
|
||||
const policyPincode =
|
||||
result?.sharedPolicyPincode ?? result?.defaultPolicyPincode ?? null;
|
||||
const definedPincode = policyPincode ?? result?.resourcePincode ?? null;
|
||||
const isPolicyPincode = !!policyPincode;
|
||||
|
||||
if (!org) {
|
||||
return next(
|
||||
@@ -125,7 +173,8 @@ export async function authWithPincode(
|
||||
await createResourceSession({
|
||||
resourceId,
|
||||
token,
|
||||
pincodeId: definedPincode.pincodeId,
|
||||
pincodeId: isPolicyPincode ? null : definedPincode.pincodeId,
|
||||
policyPincodeId: isPolicyPincode ? definedPincode.pincodeId : null,
|
||||
isRequestToken: true,
|
||||
expiresAt: Date.now() + 1000 * 30, // 30 seconds
|
||||
sessionLength: 1000 * 30,
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { generateSessionToken } from "@server/auth/sessions/app";
|
||||
import { db } from "@server/db";
|
||||
import { orgs, resourceOtp, resources, resourceWhitelist } from "@server/db";
|
||||
import {
|
||||
orgs,
|
||||
resourceOtp,
|
||||
resources,
|
||||
resourceWhitelist,
|
||||
resourcePolicyWhiteList
|
||||
} from "@server/db";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import response from "@server/lib/response";
|
||||
import { eq, and } from "drizzle-orm";
|
||||
@@ -20,7 +26,7 @@ const authWithWhitelistBodySchema = z.strictObject({
|
||||
});
|
||||
|
||||
const authWithWhitelistParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
export type AuthWithWhitelistResponse = {
|
||||
@@ -59,82 +65,21 @@ export async function authWithWhitelist(
|
||||
const { email, otp } = parsedBody.data;
|
||||
|
||||
try {
|
||||
const [result] = await db
|
||||
// Fetch resource and org first
|
||||
const [resourceResult] = await db
|
||||
.select()
|
||||
.from(resourceWhitelist)
|
||||
.where(
|
||||
and(
|
||||
eq(resourceWhitelist.resourceId, resourceId),
|
||||
eq(resourceWhitelist.email, email)
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
resources,
|
||||
eq(resources.resourceId, resourceWhitelist.resourceId)
|
||||
)
|
||||
.from(resources)
|
||||
.leftJoin(orgs, eq(orgs.orgId, resources.orgId))
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
let resource = result?.resources;
|
||||
let org = result?.orgs;
|
||||
let whitelistedEmail = result?.resourceWhitelist;
|
||||
const resource = resourceResult?.resources;
|
||||
const org = resourceResult?.orgs;
|
||||
|
||||
if (!whitelistedEmail) {
|
||||
// if email is not found, check for wildcard email
|
||||
const wildcard = "*@" + email.split("@")[1];
|
||||
|
||||
logger.debug("Checking for wildcard email: " + wildcard);
|
||||
|
||||
const [result] = await db
|
||||
.select()
|
||||
.from(resourceWhitelist)
|
||||
.where(
|
||||
and(
|
||||
eq(resourceWhitelist.resourceId, resourceId),
|
||||
eq(resourceWhitelist.email, wildcard)
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
resources,
|
||||
eq(resources.resourceId, resourceWhitelist.resourceId)
|
||||
)
|
||||
.leftJoin(orgs, eq(orgs.orgId, resources.orgId))
|
||||
.limit(1);
|
||||
|
||||
resource = result?.resources;
|
||||
org = result?.orgs;
|
||||
whitelistedEmail = result?.resourceWhitelist;
|
||||
|
||||
// if wildcard is still not found, return unauthorized
|
||||
if (!whitelistedEmail) {
|
||||
if (config.getRawConfig().app.log_failed_attempts) {
|
||||
logger.info(
|
||||
`Email is not whitelisted. Email: ${email}. IP: ${req.ip}.`
|
||||
);
|
||||
}
|
||||
|
||||
if (org && resource) {
|
||||
logAccessAudit({
|
||||
orgId: org.orgId,
|
||||
resourceId: resource.resourceId,
|
||||
action: false,
|
||||
type: "whitelistedEmail",
|
||||
metadata: { email },
|
||||
userAgent: req.headers["user-agent"],
|
||||
requestIp: req.ip
|
||||
});
|
||||
}
|
||||
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.UNAUTHORIZED,
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Email is not whitelisted"
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, "Resource does not exist")
|
||||
);
|
||||
}
|
||||
|
||||
if (!org) {
|
||||
@@ -143,9 +88,153 @@ export async function authWithWhitelist(
|
||||
);
|
||||
}
|
||||
|
||||
if (!resource) {
|
||||
const wildcard = "*@" + email.split("@")[1];
|
||||
|
||||
// Check shared policy whitelist first, then default (inline) policy whitelist
|
||||
let policyWhitelistEntry: {
|
||||
whitelistId: number;
|
||||
email: string;
|
||||
} | null = null;
|
||||
if (resource.resourcePolicyId) {
|
||||
const [exact] = await db
|
||||
.select()
|
||||
.from(resourcePolicyWhiteList)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
resourcePolicyWhiteList.resourcePolicyId,
|
||||
resource.resourcePolicyId
|
||||
),
|
||||
eq(resourcePolicyWhiteList.email, email)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (exact) {
|
||||
policyWhitelistEntry = exact;
|
||||
} else {
|
||||
logger.debug(
|
||||
"Checking for wildcard email in shared policy: " + wildcard
|
||||
);
|
||||
const [wildcardMatch] = await db
|
||||
.select()
|
||||
.from(resourcePolicyWhiteList)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
resourcePolicyWhiteList.resourcePolicyId,
|
||||
resource.resourcePolicyId
|
||||
),
|
||||
eq(resourcePolicyWhiteList.email, wildcard)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
if (wildcardMatch) policyWhitelistEntry = wildcardMatch;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to default (inline) policy whitelist if shared policy didn't match
|
||||
if (!policyWhitelistEntry && resource.defaultResourcePolicyId) {
|
||||
const [exact] = await db
|
||||
.select()
|
||||
.from(resourcePolicyWhiteList)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
resourcePolicyWhiteList.resourcePolicyId,
|
||||
resource.defaultResourcePolicyId
|
||||
),
|
||||
eq(resourcePolicyWhiteList.email, email)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (exact) {
|
||||
policyWhitelistEntry = exact;
|
||||
} else {
|
||||
logger.debug(
|
||||
"Checking for wildcard email in default policy: " + wildcard
|
||||
);
|
||||
const [wildcardMatch] = await db
|
||||
.select()
|
||||
.from(resourcePolicyWhiteList)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
resourcePolicyWhiteList.resourcePolicyId,
|
||||
resource.defaultResourcePolicyId
|
||||
),
|
||||
eq(resourcePolicyWhiteList.email, wildcard)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
if (wildcardMatch) policyWhitelistEntry = wildcardMatch;
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to resource whitelist if not found in policy
|
||||
let resourceWhitelistEntry: {
|
||||
whitelistId: number;
|
||||
email: string;
|
||||
} | null = null;
|
||||
if (!policyWhitelistEntry) {
|
||||
const [exact] = await db
|
||||
.select()
|
||||
.from(resourceWhitelist)
|
||||
.where(
|
||||
and(
|
||||
eq(resourceWhitelist.resourceId, resourceId),
|
||||
eq(resourceWhitelist.email, email)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (exact) {
|
||||
resourceWhitelistEntry = exact;
|
||||
} else {
|
||||
logger.debug("Checking for wildcard email: " + wildcard);
|
||||
const [wildcardMatch] = await db
|
||||
.select()
|
||||
.from(resourceWhitelist)
|
||||
.where(
|
||||
and(
|
||||
eq(resourceWhitelist.resourceId, resourceId),
|
||||
eq(resourceWhitelist.email, wildcard)
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
if (wildcardMatch) resourceWhitelistEntry = wildcardMatch;
|
||||
}
|
||||
}
|
||||
|
||||
const isPolicyWhitelist = !!policyWhitelistEntry;
|
||||
const whitelistedEmail = policyWhitelistEntry ?? resourceWhitelistEntry;
|
||||
|
||||
if (!whitelistedEmail) {
|
||||
if (config.getRawConfig().app.log_failed_attempts) {
|
||||
logger.info(
|
||||
`Email is not whitelisted. Email: ${email}. IP: ${req.ip}.`
|
||||
);
|
||||
}
|
||||
|
||||
logAccessAudit({
|
||||
orgId: org.orgId,
|
||||
resourceId: resource.resourceId,
|
||||
action: false,
|
||||
type: "whitelistedEmail",
|
||||
metadata: { email },
|
||||
userAgent: req.headers["user-agent"],
|
||||
requestIp: req.ip
|
||||
});
|
||||
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, "Resource does not exist")
|
||||
createHttpError(
|
||||
HttpCode.UNAUTHORIZED,
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Email is not whitelisted"
|
||||
)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -211,7 +300,12 @@ export async function authWithWhitelist(
|
||||
await createResourceSession({
|
||||
resourceId,
|
||||
token,
|
||||
whitelistId: whitelistedEmail.whitelistId,
|
||||
whitelistId: isPolicyWhitelist
|
||||
? null
|
||||
: whitelistedEmail.whitelistId,
|
||||
policyWhitelistId: isPolicyWhitelist
|
||||
? whitelistedEmail.whitelistId
|
||||
: null,
|
||||
isRequestToken: true,
|
||||
expiresAt: Date.now() + 1000 * 30, // 30 seconds
|
||||
sessionLength: 1000 * 30,
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, domainNamespaces, loginPage } from "@server/db";
|
||||
import { build } from "@server/build";
|
||||
import {
|
||||
domains,
|
||||
orgDomains,
|
||||
db,
|
||||
loginPage,
|
||||
orgs,
|
||||
Resource,
|
||||
resources,
|
||||
resourcePolicies,
|
||||
roleResources,
|
||||
rolePolicies,
|
||||
roles,
|
||||
userResources
|
||||
userPolicies,
|
||||
userResources,
|
||||
domainNamespaces
|
||||
} from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
@@ -20,27 +24,77 @@ import logger from "@server/logger";
|
||||
import { subdomainSchema, wildcardSubdomainSchema } from "@server/lib/schemas";
|
||||
import config from "@server/lib/config";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { build } from "@server/build";
|
||||
import { createCertificate } from "#dynamic/routers/certificates/createCertificate";
|
||||
import { getUniqueResourceName } from "@server/db/names";
|
||||
import { validateAndConstructDomain, checkWildcardDomainConflict } from "@server/lib/domainUtils";
|
||||
import {
|
||||
validateAndConstructDomain,
|
||||
checkWildcardDomainConflict
|
||||
} from "@server/lib/domainUtils";
|
||||
import { isSubscribed } from "#dynamic/lib/isSubscribed";
|
||||
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
|
||||
import { tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { TierFeature, tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import {
|
||||
getUniqueResourceName,
|
||||
getUniqueResourcePolicyName
|
||||
} from "@server/db/names";
|
||||
import { usageService } from "@server/lib/billing/usageService";
|
||||
import { LimitId } from "@server/lib/billing";
|
||||
|
||||
const createResourceParamsSchema = z.strictObject({
|
||||
orgId: z.string()
|
||||
});
|
||||
|
||||
function resolveModeFromLegacyFields(data: {
|
||||
mode?: "http" | "ssh" | "rdp" | "vnc" | "tcp" | "udp";
|
||||
http?: boolean;
|
||||
protocol?: "tcp" | "udp";
|
||||
}): {
|
||||
mode?: "http" | "ssh" | "rdp" | "vnc" | "tcp" | "udp";
|
||||
error?: string;
|
||||
} {
|
||||
if (data.mode) {
|
||||
return { mode: data.mode };
|
||||
}
|
||||
|
||||
if (typeof data.http === "boolean" && data.protocol) {
|
||||
if (data.http && data.protocol === "tcp") {
|
||||
return { mode: "http" };
|
||||
}
|
||||
if (!data.http && data.protocol === "tcp") {
|
||||
return { mode: "tcp" };
|
||||
}
|
||||
if (!data.http && data.protocol === "udp") {
|
||||
return { mode: "udp" };
|
||||
}
|
||||
return {
|
||||
error: "Invalid deprecated http/protocol combination"
|
||||
};
|
||||
}
|
||||
|
||||
return { mode: undefined };
|
||||
}
|
||||
|
||||
const createHttpResourceSchema = z
|
||||
.strictObject({
|
||||
name: z.string().min(1).max(255),
|
||||
subdomain: z.string().nullable().optional(),
|
||||
http: z.boolean(),
|
||||
protocol: z.enum(["tcp", "udp"]),
|
||||
http: z.boolean().optional().openapi({
|
||||
deprecated: true,
|
||||
description:
|
||||
"Deprecated. Use `mode` instead. Legacy compatibility only."
|
||||
}),
|
||||
protocol: z.enum(["tcp", "udp"]).optional().openapi({
|
||||
deprecated: true,
|
||||
description:
|
||||
"Deprecated. Use `mode` instead. Legacy compatibility only."
|
||||
}),
|
||||
domainId: z.string(),
|
||||
stickySession: z.boolean().optional(),
|
||||
postAuthPath: z.string().nullable().optional()
|
||||
postAuthPath: z.string().nullable().optional(),
|
||||
mode: z.enum(["http", "ssh", "rdp", "vnc", "tcp", "udp"]).optional(),
|
||||
// SSH Settings
|
||||
pamMode: z.enum(["passthrough", "push"]).optional(),
|
||||
authDaemonPort: z.int().positive().optional(),
|
||||
authDaemonMode: z.enum(["site", "remote", "native"]).optional()
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
@@ -60,13 +114,27 @@ const createHttpResourceSchema = z
|
||||
const createRawResourceSchema = z
|
||||
.strictObject({
|
||||
name: z.string().min(1).max(255),
|
||||
http: z.boolean(),
|
||||
protocol: z.enum(["tcp", "udp"]),
|
||||
http: z.boolean().optional().openapi({
|
||||
deprecated: true,
|
||||
description:
|
||||
"Deprecated. Use `mode` instead. Legacy compatibility only."
|
||||
}),
|
||||
protocol: z.enum(["tcp", "udp"]).optional().openapi({
|
||||
deprecated: true,
|
||||
description:
|
||||
"Deprecated. Use `mode` instead. Legacy compatibility only."
|
||||
}),
|
||||
mode: z.enum(["tcp", "udp"]).optional(),
|
||||
proxyPort: z.int().min(1).max(65535)
|
||||
// enableProxy: z.boolean().default(true) // always true now
|
||||
})
|
||||
.refine(
|
||||
(data) => {
|
||||
const resolved = resolveModeFromLegacyFields(data);
|
||||
if (resolved.error || !resolved.mode) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!config.getRawConfig().flags?.allow_raw_resources) {
|
||||
if (data.proxyPort !== undefined) {
|
||||
return false;
|
||||
@@ -96,7 +164,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function createResource(
|
||||
@@ -143,17 +226,50 @@ export async function createResource(
|
||||
);
|
||||
}
|
||||
|
||||
if (typeof req.body.http !== "boolean") {
|
||||
const resolvedMode = resolveModeFromLegacyFields(req.body);
|
||||
if (resolvedMode.error) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, "http field is required")
|
||||
createHttpError(HttpCode.BAD_REQUEST, resolvedMode.error)
|
||||
);
|
||||
}
|
||||
|
||||
const { http } = req.body;
|
||||
if (resolvedMode.mode) {
|
||||
req.body.mode = resolvedMode.mode;
|
||||
}
|
||||
|
||||
if (http) {
|
||||
return await createHttpResource({ req, res, next }, { orgId });
|
||||
} else {
|
||||
if (build == "saas") {
|
||||
const usage = await usageService.getUsage(
|
||||
orgId,
|
||||
LimitId.PUBLIC_RESOURCES
|
||||
);
|
||||
if (!usage) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"No usage data found for this organization"
|
||||
)
|
||||
);
|
||||
}
|
||||
const rejectResource = await usageService.checkLimitSet(
|
||||
orgId,
|
||||
|
||||
LimitId.PUBLIC_RESOURCES,
|
||||
{
|
||||
...usage,
|
||||
instantaneousValue: (usage.instantaneousValue || 0) + 1
|
||||
} // We need to add one to know if we are violating the limit
|
||||
);
|
||||
if (rejectResource) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"Public resource limit exceeded. Please upgrade your plan."
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof req.body.proxyPort === "number") {
|
||||
if (
|
||||
!config.getRawConfig().flags?.allow_raw_resources &&
|
||||
build == "oss"
|
||||
@@ -167,6 +283,17 @@ export async function createResource(
|
||||
}
|
||||
return await createRawResource({ req, res, next }, { orgId });
|
||||
}
|
||||
|
||||
if (req.body.mode) {
|
||||
return await createHttpResource({ req, res, next }, { orgId });
|
||||
} else {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"mode is required when deprecated fields are not provided"
|
||||
)
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
@@ -198,7 +325,15 @@ async function createHttpResource(
|
||||
);
|
||||
}
|
||||
|
||||
const { name, domainId, postAuthPath } = parsedBody.data;
|
||||
const {
|
||||
name,
|
||||
domainId,
|
||||
postAuthPath,
|
||||
mode,
|
||||
authDaemonPort,
|
||||
authDaemonMode,
|
||||
pamMode
|
||||
} = parsedBody.data;
|
||||
const subdomain = parsedBody.data.subdomain;
|
||||
const stickySession = parsedBody.data.stickySession;
|
||||
|
||||
@@ -241,6 +376,21 @@ async function createHttpResource(
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
["ssh", "rdp", "vnc"].includes(mode!) &&
|
||||
!isLicensedOrSubscribed(
|
||||
orgId!,
|
||||
tierMatrix[TierFeature.AdvancedPublicResources]
|
||||
)
|
||||
) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Your current subscription does not support browser gateway resources. Please upgrade to access this feature."
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Validate domain and construct full domain
|
||||
const domainResult = await validateAndConstructDomain(
|
||||
domainId,
|
||||
@@ -311,28 +461,10 @@ async function createHttpResource(
|
||||
let resource: Resource | undefined;
|
||||
|
||||
const niceId = await getUniqueResourceName(orgId);
|
||||
const policyNiceId = await getUniqueResourcePolicyName(orgId);
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
const newResource = await trx
|
||||
.insert(resources)
|
||||
.values({
|
||||
niceId,
|
||||
fullDomain,
|
||||
domainId,
|
||||
orgId,
|
||||
name,
|
||||
subdomain: finalSubdomain,
|
||||
http: true,
|
||||
protocol: "tcp",
|
||||
ssl: true,
|
||||
stickySession: stickySession,
|
||||
postAuthPath: postAuthPath,
|
||||
wildcard,
|
||||
health: "unknown"
|
||||
})
|
||||
.returning();
|
||||
|
||||
const adminRole = await db
|
||||
const adminRole = await trx
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.isAdmin, true), eq(roles.orgId, orgId)))
|
||||
@@ -344,6 +476,53 @@ async function createHttpResource(
|
||||
);
|
||||
}
|
||||
|
||||
const [defaultPolicy] = await trx
|
||||
.insert(resourcePolicies)
|
||||
.values({
|
||||
niceId: policyNiceId,
|
||||
orgId,
|
||||
name: `default policy for ${niceId}`,
|
||||
sso: true,
|
||||
scope: "resource"
|
||||
})
|
||||
.returning();
|
||||
|
||||
// make this policy visible by the admin role
|
||||
await trx.insert(rolePolicies).values({
|
||||
roleId: adminRole[0].roleId,
|
||||
resourcePolicyId: defaultPolicy.resourcePolicyId
|
||||
});
|
||||
|
||||
// make this policy visible by the current user
|
||||
if (req.user && !req.userOrgRoleIds?.includes(adminRole[0].roleId)) {
|
||||
await trx.insert(userPolicies).values({
|
||||
userId: req.user?.userId!,
|
||||
resourcePolicyId: defaultPolicy.resourcePolicyId
|
||||
});
|
||||
}
|
||||
|
||||
const newResource = await trx
|
||||
.insert(resources)
|
||||
.values({
|
||||
niceId,
|
||||
fullDomain,
|
||||
domainId,
|
||||
orgId,
|
||||
name,
|
||||
subdomain: finalSubdomain,
|
||||
mode: mode,
|
||||
pamMode: pamMode,
|
||||
authDaemonMode: authDaemonMode,
|
||||
authDaemonPort: authDaemonPort,
|
||||
ssl: true,
|
||||
stickySession: stickySession,
|
||||
postAuthPath: postAuthPath,
|
||||
wildcard,
|
||||
health: "unknown",
|
||||
defaultResourcePolicyId: defaultPolicy.resourcePolicyId
|
||||
})
|
||||
.returning();
|
||||
|
||||
await trx.insert(roleResources).values({
|
||||
roleId: adminRole[0].roleId,
|
||||
resourceId: newResource[0].resourceId
|
||||
@@ -358,6 +537,8 @@ async function createHttpResource(
|
||||
}
|
||||
|
||||
resource = newResource[0];
|
||||
|
||||
await usageService.add(orgId, LimitId.PUBLIC_RESOURCES, 1, trx);
|
||||
});
|
||||
|
||||
if (!resource) {
|
||||
@@ -369,7 +550,7 @@ async function createHttpResource(
|
||||
);
|
||||
}
|
||||
|
||||
if (build != "oss") {
|
||||
if (build !== "oss") {
|
||||
await createCertificate(domainId, fullDomain, db);
|
||||
}
|
||||
|
||||
@@ -405,27 +586,25 @@ async function createRawResource(
|
||||
);
|
||||
}
|
||||
|
||||
const { name, http, protocol, proxyPort } = parsedBody.data;
|
||||
const { name, proxyPort } = parsedBody.data;
|
||||
const resolvedMode = resolveModeFromLegacyFields(parsedBody.data);
|
||||
if (resolvedMode.error || !resolvedMode.mode) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
resolvedMode.error ||
|
||||
"mode is required when deprecated fields are not provided"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
let resource: Resource | undefined;
|
||||
|
||||
const niceId = await getUniqueResourceName(orgId);
|
||||
const policyNiceId = await getUniqueResourcePolicyName(orgId);
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
const newResource = await trx
|
||||
.insert(resources)
|
||||
.values({
|
||||
niceId,
|
||||
orgId,
|
||||
name,
|
||||
http,
|
||||
protocol,
|
||||
proxyPort
|
||||
// enableProxy
|
||||
})
|
||||
.returning();
|
||||
|
||||
const adminRole = await db
|
||||
const adminRole = await trx
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.isAdmin, true), eq(roles.orgId, orgId)))
|
||||
@@ -437,6 +616,43 @@ async function createRawResource(
|
||||
);
|
||||
}
|
||||
|
||||
const [defaultPolicy] = await trx
|
||||
.insert(resourcePolicies)
|
||||
.values({
|
||||
niceId: policyNiceId,
|
||||
orgId,
|
||||
name: `default policy for ${niceId}`,
|
||||
sso: true,
|
||||
scope: "resource"
|
||||
})
|
||||
.returning();
|
||||
|
||||
// make this policy visible by the admin role
|
||||
await trx.insert(rolePolicies).values({
|
||||
roleId: adminRole[0].roleId,
|
||||
resourcePolicyId: defaultPolicy.resourcePolicyId
|
||||
});
|
||||
|
||||
// make this policy visible by the current user
|
||||
if (req.user && !req.userOrgRoleIds?.includes(adminRole[0].roleId)) {
|
||||
await trx.insert(userPolicies).values({
|
||||
userId: req.user?.userId!,
|
||||
resourcePolicyId: defaultPolicy.resourcePolicyId
|
||||
});
|
||||
}
|
||||
|
||||
const newResource = await trx
|
||||
.insert(resources)
|
||||
.values({
|
||||
niceId,
|
||||
orgId,
|
||||
name,
|
||||
mode: resolvedMode.mode,
|
||||
proxyPort,
|
||||
defaultResourcePolicyId: defaultPolicy.resourcePolicyId
|
||||
})
|
||||
.returning();
|
||||
|
||||
await trx.insert(roleResources).values({
|
||||
roleId: adminRole[0].roleId,
|
||||
resourceId: newResource[0].resourceId
|
||||
@@ -451,6 +667,8 @@ async function createRawResource(
|
||||
}
|
||||
|
||||
resource = newResource[0];
|
||||
|
||||
await usageService.add(orgId, LimitId.PUBLIC_RESOURCES, 1, trx);
|
||||
});
|
||||
|
||||
if (!resource) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { resourceRules, resources } from "@server/db";
|
||||
import { resourceRules, resourcePolicyRules, resources } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
@@ -25,7 +25,7 @@ const createResourceRuleSchema = z.strictObject({
|
||||
});
|
||||
|
||||
const createResourceRuleParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
@@ -43,7 +43,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function createResourceRule(
|
||||
@@ -94,7 +109,7 @@ export async function createResourceRule(
|
||||
);
|
||||
}
|
||||
|
||||
if (!resource.http) {
|
||||
if (!["http", "ssh", "rdp", "vnc"].includes(resource.mode)) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
@@ -138,6 +153,34 @@ export async function createResourceRule(
|
||||
}
|
||||
}
|
||||
|
||||
// Create the new resource rule
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
const [newRule] = await db
|
||||
.insert(resourcePolicyRules)
|
||||
.values({
|
||||
resourcePolicyId: policyId,
|
||||
action,
|
||||
match,
|
||||
value,
|
||||
priority,
|
||||
enabled
|
||||
})
|
||||
.returning();
|
||||
|
||||
return response(res, {
|
||||
data: newRule,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Resource rule created successfully",
|
||||
status: HttpCode.CREATED
|
||||
});
|
||||
}
|
||||
|
||||
// Create the new resource rule
|
||||
const [newRule] = await db
|
||||
.insert(resourceRules)
|
||||
|
||||
@@ -1,21 +1,21 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, targetHealthCheck } from "@server/db";
|
||||
import { newts, resources, sites, targets } from "@server/db";
|
||||
import { eq, inArray } from "drizzle-orm";
|
||||
import { db } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import logger from "@server/logger";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { addPeer } from "../gerbil/peers";
|
||||
import { removeTargets } from "../newt/targets";
|
||||
import { getAllowedIps } from "../target/helpers";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import { NextFunction, Request, Response } from "express";
|
||||
import createHttpError from "http-errors";
|
||||
import { z } from "zod";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import {
|
||||
performDeleteResource,
|
||||
runResourceDeleteSideEffects
|
||||
} from "@server/lib/deleteResource";
|
||||
import { LimitId } from "@server/lib/billing";
|
||||
import { usageService } from "@server/lib/billing/usageService";
|
||||
|
||||
// Define Zod schema for request parameters validation
|
||||
const deleteResourceSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
@@ -26,7 +26,22 @@ registry.registerPath({
|
||||
request: {
|
||||
params: deleteResourceSchema
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function deleteResource(
|
||||
@@ -47,27 +62,21 @@ export async function deleteResource(
|
||||
|
||||
const { resourceId } = parsedParams.data;
|
||||
|
||||
const targetsToBeRemoved = await db
|
||||
.select()
|
||||
.from(targets)
|
||||
.where(eq(targets.resourceId, resourceId));
|
||||
let deleteResult = null;
|
||||
|
||||
const healthChecksToBeRemoved = await db
|
||||
.select()
|
||||
.from(targetHealthCheck)
|
||||
.where(
|
||||
inArray(
|
||||
targetHealthCheck.targetId,
|
||||
targetsToBeRemoved.map((t) => t.targetId)
|
||||
)
|
||||
);
|
||||
await db.transaction(async (trx) => {
|
||||
deleteResult = await performDeleteResource(resourceId, trx);
|
||||
if (deleteResult?.deletedResource?.orgId) {
|
||||
await usageService.add(
|
||||
deleteResult?.deletedResource?.orgId,
|
||||
LimitId.PUBLIC_RESOURCES,
|
||||
-1,
|
||||
trx
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
const [deletedResource] = await db
|
||||
.delete(resources)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.returning();
|
||||
|
||||
if (!deletedResource) {
|
||||
if (!deleteResult) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
@@ -76,42 +85,7 @@ export async function deleteResource(
|
||||
);
|
||||
}
|
||||
|
||||
for (const target of targetsToBeRemoved) {
|
||||
const [site] = await db
|
||||
.select()
|
||||
.from(sites)
|
||||
.where(eq(sites.siteId, target.siteId))
|
||||
.limit(1);
|
||||
|
||||
if (!site) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Site with ID ${target.siteId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (site.pubKey) {
|
||||
if (site.type == "newt") {
|
||||
// get the newt on the site by querying the newt table for siteId
|
||||
const [newt] = await db
|
||||
.select()
|
||||
.from(newts)
|
||||
.where(eq(newts.siteId, site.siteId))
|
||||
.limit(1);
|
||||
|
||||
await removeTargets(
|
||||
newt.newtId,
|
||||
// [target],
|
||||
[], // deleting the target from newt causes issues because we cant unbind the port. this needs to be fixed in newt before we can do this
|
||||
healthChecksToBeRemoved,
|
||||
deletedResource.protocol,
|
||||
newt.version
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
await runResourceDeleteSideEffects(deleteResult);
|
||||
|
||||
return response(res, {
|
||||
data: null,
|
||||
@@ -122,6 +96,9 @@ export async function deleteResource(
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
if (createHttpError.isHttpError(error)) {
|
||||
return next(error);
|
||||
}
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { resourceRules, resources } from "@server/db";
|
||||
import { resourceRules, resourcePolicyRules, resources } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
@@ -11,8 +11,8 @@ import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const deleteResourceRuleSchema = z.strictObject({
|
||||
ruleId: z.string().transform(Number).pipe(z.int().positive()),
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
ruleId: z.coerce.number().int().positive(),
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
@@ -23,7 +23,22 @@ registry.registerPath({
|
||||
request: {
|
||||
params: deleteResourceRuleSchema
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function deleteResourceRule(
|
||||
@@ -44,6 +59,48 @@ export async function deleteResourceRule(
|
||||
|
||||
const { ruleId } = parsedParams.data;
|
||||
|
||||
// Look up resource to determine which table to use
|
||||
const { resourceId } = parsedParams.data;
|
||||
const [resource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
|
||||
);
|
||||
}
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
if (isInlinePolicy) {
|
||||
const [deletedRule] = await db
|
||||
.delete(resourcePolicyRules)
|
||||
.where(eq(resourcePolicyRules.ruleId, ruleId))
|
||||
.returning();
|
||||
|
||||
if (!deletedRule) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Resource rule with ID ${ruleId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: null,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Resource rule deleted successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
}
|
||||
|
||||
// Delete the rule and return the deleted record
|
||||
const [deletedRule] = await db
|
||||
.delete(resourceRules)
|
||||
|
||||
@@ -17,7 +17,7 @@ import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
|
||||
import { logAccessAudit } from "#dynamic/lib/logAccessAudit";
|
||||
|
||||
const getExchangeTokenParams = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
export type GetExchangeTokenResponse = {
|
||||
@@ -80,8 +80,7 @@ export async function getExchangeToken(
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"Failed organization access policy check: " +
|
||||
(hasAccess.error || "Unknown error")
|
||||
"" + (hasAccess.error || "Unknown error")
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { db, resources } from "@server/db";
|
||||
import { db, resourcePolicies, resources } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import stoi from "@server/lib/stoi";
|
||||
import logger from "@server/logger";
|
||||
@@ -9,6 +9,7 @@ import { NextFunction, Request, Response } from "express";
|
||||
import createHttpError from "http-errors";
|
||||
import { z } from "zod";
|
||||
import { fromError } from "zod-validation-error";
|
||||
import { applyInlinePolicyFields } from "./inlinePolicyFields";
|
||||
|
||||
const getResourceSchema = z.strictObject({
|
||||
resourceId: z
|
||||
@@ -41,6 +42,15 @@ async function query(resourceId?: number, niceId?: string, orgId?: string) {
|
||||
}
|
||||
}
|
||||
|
||||
async function queryInlinePolicy(resourcePolicyId: number) {
|
||||
const [res] = await db
|
||||
.select()
|
||||
.from(resourcePolicies)
|
||||
.where(eq(resourcePolicies.resourcePolicyId, resourcePolicyId))
|
||||
.limit(1);
|
||||
return res;
|
||||
}
|
||||
|
||||
export type GetResourceResponse = Omit<
|
||||
NonNullable<Awaited<ReturnType<typeof query>>>,
|
||||
"requestHeaders" | "responseHeaders"
|
||||
@@ -61,7 +71,22 @@ registry.registerPath({
|
||||
niceId: z.string()
|
||||
})
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
@@ -74,7 +99,22 @@ registry.registerPath({
|
||||
resourceId: z.number()
|
||||
})
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function getResource(
|
||||
@@ -103,15 +143,28 @@ export async function getResource(
|
||||
);
|
||||
}
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
let returnData = resource;
|
||||
if (isInlinePolicy) {
|
||||
// get the policy
|
||||
const policy = await queryInlinePolicy(
|
||||
resource.defaultResourcePolicyId!
|
||||
);
|
||||
returnData = applyInlinePolicyFields(returnData, policy);
|
||||
}
|
||||
|
||||
return response<GetResourceResponse>(res, {
|
||||
data: {
|
||||
...resource,
|
||||
requestHeaders: resource.requestHeaders
|
||||
? JSON.parse(resource.requestHeaders)
|
||||
: resource.requestHeaders,
|
||||
responseHeaders: resource.responseHeaders
|
||||
? JSON.parse(resource.responseHeaders)
|
||||
: resource.responseHeaders
|
||||
...returnData,
|
||||
requestHeaders: returnData.requestHeaders
|
||||
? JSON.parse(returnData.requestHeaders)
|
||||
: returnData.requestHeaders,
|
||||
responseHeaders: returnData.responseHeaders
|
||||
? JSON.parse(returnData.responseHeaders)
|
||||
: returnData.responseHeaders
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
|
||||
@@ -2,13 +2,17 @@ import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
db,
|
||||
resourceHeaderAuth,
|
||||
resourceHeaderAuthExtendedCompatibility,
|
||||
resourcePassword,
|
||||
resourcePolicies,
|
||||
resourcePolicyHeaderAuth,
|
||||
resourcePolicyPassword,
|
||||
resourcePolicyPincode,
|
||||
resourcePincode,
|
||||
resourcePassword,
|
||||
resourceHeaderAuth,
|
||||
resources
|
||||
} from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { alias } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -60,64 +64,114 @@ export async function getResourceAuthInfo(
|
||||
|
||||
const isGuidInteger = /^\d+$/.test(resourceGuid);
|
||||
|
||||
const sharedPolicy = alias(resourcePolicies, "sharedPolicy");
|
||||
const defaultPolicy = alias(resourcePolicies, "defaultPolicy");
|
||||
const sharedPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"sharedPolicyPincode"
|
||||
);
|
||||
const defaultPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"defaultPolicyPincode"
|
||||
);
|
||||
const sharedPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"sharedPolicyPassword"
|
||||
);
|
||||
const defaultPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"defaultPolicyPassword"
|
||||
);
|
||||
const sharedPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"sharedPolicyHeaderAuth"
|
||||
);
|
||||
const defaultPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"defaultPolicyHeaderAuth"
|
||||
);
|
||||
|
||||
const buildQuery = (whereClause: ReturnType<typeof eq>) =>
|
||||
db
|
||||
.select()
|
||||
.from(resources)
|
||||
.leftJoin(
|
||||
resourcePincode,
|
||||
eq(resourcePincode.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
resourcePassword,
|
||||
eq(resourcePassword.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
resourceHeaderAuth,
|
||||
eq(resourceHeaderAuth.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicy,
|
||||
eq(
|
||||
sharedPolicy.resourcePolicyId,
|
||||
resources.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicyPincode,
|
||||
eq(
|
||||
sharedPolicyPincode.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicyPassword,
|
||||
eq(
|
||||
sharedPolicyPassword.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicyHeaderAuth,
|
||||
eq(
|
||||
sharedPolicyHeaderAuth.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicy,
|
||||
eq(
|
||||
defaultPolicy.resourcePolicyId,
|
||||
resources.defaultResourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyPincode,
|
||||
eq(
|
||||
defaultPolicyPincode.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyPassword,
|
||||
eq(
|
||||
defaultPolicyPassword.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyHeaderAuth,
|
||||
eq(
|
||||
defaultPolicyHeaderAuth.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.where(whereClause)
|
||||
.limit(1);
|
||||
|
||||
const [result] =
|
||||
isGuidInteger && build === "saas"
|
||||
? await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.leftJoin(
|
||||
resourcePincode,
|
||||
eq(resourcePincode.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
resourcePassword,
|
||||
eq(resourcePassword.resourceId, resources.resourceId)
|
||||
)
|
||||
|
||||
.leftJoin(
|
||||
resourceHeaderAuth,
|
||||
eq(
|
||||
resourceHeaderAuth.resourceId,
|
||||
resources.resourceId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
resourceHeaderAuthExtendedCompatibility,
|
||||
eq(
|
||||
resourceHeaderAuthExtendedCompatibility.resourceId,
|
||||
resources.resourceId
|
||||
)
|
||||
)
|
||||
.where(eq(resources.resourceId, Number(resourceGuid)))
|
||||
.limit(1)
|
||||
: await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.leftJoin(
|
||||
resourcePincode,
|
||||
eq(resourcePincode.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
resourcePassword,
|
||||
eq(resourcePassword.resourceId, resources.resourceId)
|
||||
)
|
||||
|
||||
.leftJoin(
|
||||
resourceHeaderAuth,
|
||||
eq(
|
||||
resourceHeaderAuth.resourceId,
|
||||
resources.resourceId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
resourceHeaderAuthExtendedCompatibility,
|
||||
eq(
|
||||
resourceHeaderAuthExtendedCompatibility.resourceId,
|
||||
resources.resourceId
|
||||
)
|
||||
)
|
||||
.where(eq(resources.resourceGuid, resourceGuid))
|
||||
.limit(1);
|
||||
? await buildQuery(
|
||||
eq(resources.resourceId, Number(resourceGuid))
|
||||
)
|
||||
: await buildQuery(eq(resources.resourceGuid, resourceGuid));
|
||||
|
||||
const resource = result?.resources;
|
||||
if (!resource) {
|
||||
@@ -126,11 +180,29 @@ export async function getResourceAuthInfo(
|
||||
);
|
||||
}
|
||||
|
||||
const pincode = result?.resourcePincode;
|
||||
const password = result?.resourcePassword;
|
||||
const headerAuth = result?.resourceHeaderAuth;
|
||||
const headerAuthExtendedCompatibility =
|
||||
result?.resourceHeaderAuthExtendedCompatibility;
|
||||
// If a shared (custom) policy is assigned to the resource, use ONLY
|
||||
// its values — do not fall back to the default policy. The default
|
||||
// policy is only consulted when no shared policy is assigned at all.
|
||||
const hasSharedPolicy = result.sharedPolicy !== null;
|
||||
|
||||
const effectivePolicyPincode = hasSharedPolicy
|
||||
? result.sharedPolicyPincode
|
||||
: (result.defaultPolicyPincode ?? null);
|
||||
const effectivePolicyPassword = hasSharedPolicy
|
||||
? result.sharedPolicyPassword
|
||||
: (result.defaultPolicyPassword ?? null);
|
||||
const effectivePolicyHeaderAuth = hasSharedPolicy
|
||||
? result.sharedPolicyHeaderAuth
|
||||
: (result.defaultPolicyHeaderAuth ?? null);
|
||||
|
||||
const effectivePolicy = hasSharedPolicy
|
||||
? result.sharedPolicy
|
||||
: result.defaultPolicy;
|
||||
|
||||
const pincode = effectivePolicyPincode ?? result.resourcePincode;
|
||||
const password = effectivePolicyPassword ?? result.resourcePassword;
|
||||
const headerAuth =
|
||||
effectivePolicyHeaderAuth ?? result.resourceHeaderAuth;
|
||||
|
||||
const url = resource.fullDomain
|
||||
? `${resource.ssl ? "https" : "http"}://${resource.fullDomain}`
|
||||
@@ -146,14 +218,14 @@ export async function getResourceAuthInfo(
|
||||
pincode: pincode !== null,
|
||||
headerAuth: headerAuth !== null,
|
||||
headerAuthExtendedCompatibility:
|
||||
headerAuthExtendedCompatibility !== null,
|
||||
sso: resource.sso,
|
||||
effectivePolicyHeaderAuth?.extendedCompatibility ?? false,
|
||||
sso: effectivePolicy?.sso ?? false,
|
||||
blockAccess: resource.blockAccess,
|
||||
url: url ?? "",
|
||||
wildcard: resource.wildcard ?? false,
|
||||
fullDomain: resource.fullDomain,
|
||||
whitelist: resource.emailWhitelistEnabled,
|
||||
skipToIdpId: resource.skipToIdpId,
|
||||
whitelist: effectivePolicy?.emailWhitelistEnabled ?? false,
|
||||
skipToIdpId: effectivePolicy?.idpId ?? resource.skipToIdpId,
|
||||
orgId: resource.orgId,
|
||||
postAuthPath: resource.postAuthPath ?? null
|
||||
},
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { db, resources } from "@server/db";
|
||||
import {
|
||||
queryResourcePolicy,
|
||||
type GetResourcePolicyResponse
|
||||
} from "@server/routers/policy/getResourcePolicy";
|
||||
import response from "@server/lib/response";
|
||||
import logger from "@server/logger";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import { eq } from "drizzle-orm";
|
||||
import type { NextFunction, Request, Response } from "express";
|
||||
import createHttpError from "http-errors";
|
||||
import z from "zod";
|
||||
import { fromError } from "zod-validation-error";
|
||||
|
||||
const getResourcePoliciesParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
});
|
||||
|
||||
export type GetResourcePoliciesResponse = {
|
||||
defaultPolicy: GetResourcePolicyResponse;
|
||||
sharedPolicy: GetResourcePolicyResponse | null;
|
||||
};
|
||||
|
||||
registry.registerPath({
|
||||
method: "get",
|
||||
path: "/resource/{resourceId}/policies",
|
||||
description: "Get the inline and shared policies associated with a resource.",
|
||||
tags: [OpenAPITags.PublicResource, OpenAPITags.Policy],
|
||||
request: {
|
||||
params: getResourcePoliciesParamsSchema
|
||||
},
|
||||
responses: {}
|
||||
});
|
||||
|
||||
export async function getResourcePolicies(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const parsedParams = getResourcePoliciesParamsSchema.safeParse(
|
||||
req.params
|
||||
);
|
||||
if (!parsedParams.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
fromError(parsedParams.error).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const { resourceId } = parsedParams.data;
|
||||
|
||||
const [resource] = await db
|
||||
.select({
|
||||
defaultResourcePolicyId: resources.defaultResourcePolicyId,
|
||||
resourcePolicyId: resources.resourcePolicyId
|
||||
})
|
||||
.from(resources)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
|
||||
);
|
||||
}
|
||||
|
||||
if (!resource.defaultResourcePolicyId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"Resource has no default policy"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const [defaultPolicy, sharedPolicy] = await Promise.all([
|
||||
queryResourcePolicy({
|
||||
resourcePolicyId: resource.defaultResourcePolicyId
|
||||
}),
|
||||
resource.resourcePolicyId
|
||||
? queryResourcePolicy({
|
||||
resourcePolicyId: resource.resourcePolicyId
|
||||
})
|
||||
: null
|
||||
]);
|
||||
|
||||
return response<GetResourcePoliciesResponse>(res, {
|
||||
data: {
|
||||
defaultPolicy:
|
||||
// the policy will always be non nullable
|
||||
defaultPolicy as unknown as GetResourcePolicyResponse,
|
||||
sharedPolicy
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Resource policies retrieved successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { resourceWhitelist, users } from "@server/db"; // Assuming these are the correct tables
|
||||
import {
|
||||
resourceWhitelist,
|
||||
resourcePolicyWhiteList,
|
||||
resources
|
||||
} from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
@@ -11,7 +15,7 @@ import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const getResourceWhitelistSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
async function queryWhitelist(resourceId: number) {
|
||||
@@ -23,6 +27,15 @@ async function queryWhitelist(resourceId: number) {
|
||||
.where(eq(resourceWhitelist.resourceId, resourceId));
|
||||
}
|
||||
|
||||
async function queryPolicyWhitelist(policyId: number) {
|
||||
return await db
|
||||
.select({
|
||||
email: resourcePolicyWhiteList.email
|
||||
})
|
||||
.from(resourcePolicyWhiteList)
|
||||
.where(eq(resourcePolicyWhiteList.resourcePolicyId, policyId));
|
||||
}
|
||||
|
||||
export type GetResourceWhitelistResponse = {
|
||||
whitelist: NonNullable<Awaited<ReturnType<typeof queryWhitelist>>>;
|
||||
};
|
||||
@@ -35,7 +48,22 @@ registry.registerPath({
|
||||
request: {
|
||||
params: getResourceWhitelistSchema
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function getResourceWhitelist(
|
||||
@@ -56,7 +84,25 @@ export async function getResourceWhitelist(
|
||||
|
||||
const { resourceId } = parsedParams.data;
|
||||
|
||||
const whitelist = await queryWhitelist(resourceId);
|
||||
const [resource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
|
||||
);
|
||||
}
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
const whitelist = isInlinePolicy
|
||||
? await queryPolicyWhitelist(resource.defaultResourcePolicyId!)
|
||||
: await queryWhitelist(resourceId);
|
||||
|
||||
return response<GetResourceWhitelistResponse>(res, {
|
||||
data: {
|
||||
|
||||
@@ -1,24 +1,36 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { db, DB_TYPE } from "@server/db";
|
||||
import { and, eq, or, inArray, sql } from "drizzle-orm";
|
||||
import { db, DB_TYPE, type Label } from "@server/db";
|
||||
import { and, asc, eq, or, inArray, sql } from "drizzle-orm";
|
||||
import {
|
||||
resources,
|
||||
userResources,
|
||||
roleResources,
|
||||
userPolicies,
|
||||
rolePolicies,
|
||||
resourcePolicies,
|
||||
userOrgRoles,
|
||||
userOrgs,
|
||||
resourcePassword,
|
||||
resourcePincode,
|
||||
resourceWhitelist,
|
||||
resourcePolicyPassword,
|
||||
resourcePolicyPincode,
|
||||
resourcePolicyWhiteList,
|
||||
siteResources,
|
||||
userSiteResources,
|
||||
roleSiteResources,
|
||||
siteNetworks,
|
||||
sites
|
||||
sites,
|
||||
labels,
|
||||
resourceLabels,
|
||||
siteResourceLabels
|
||||
} from "@server/db";
|
||||
import createHttpError from "http-errors";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import { response } from "@server/lib/response";
|
||||
import { getFirstString } from "@server/lib/requestParams";
|
||||
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
|
||||
import { tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
|
||||
export async function getUserResources(
|
||||
req: Request,
|
||||
@@ -26,7 +38,11 @@ export async function getUserResources(
|
||||
next: NextFunction
|
||||
): Promise<any> {
|
||||
try {
|
||||
const { orgId } = req.params;
|
||||
const effectiveResourcePolicyId = sql<
|
||||
number | null
|
||||
>`coalesce(${resources.resourcePolicyId}, ${resources.defaultResourcePolicyId})`;
|
||||
|
||||
const orgId = getFirstString(req.params.orgId);
|
||||
const userId = req.user?.userId;
|
||||
|
||||
if (!userId) {
|
||||
@@ -35,6 +51,12 @@ export async function getUserResources(
|
||||
);
|
||||
}
|
||||
|
||||
if (!orgId) {
|
||||
return next(
|
||||
createHttpError(HttpCode.BAD_REQUEST, "Invalid organization ID")
|
||||
);
|
||||
}
|
||||
|
||||
// Check user is in organization and get their role IDs
|
||||
const [userOrg] = await db
|
||||
.select()
|
||||
@@ -63,14 +85,63 @@ export async function getUserResources(
|
||||
const directResourcesQuery = db
|
||||
.select({ resourceId: userResources.resourceId })
|
||||
.from(userResources)
|
||||
.where(eq(userResources.userId, userId));
|
||||
.innerJoin(
|
||||
resources,
|
||||
eq(userResources.resourceId, resources.resourceId)
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
eq(userResources.userId, userId),
|
||||
eq(resources.orgId, orgId)
|
||||
)
|
||||
);
|
||||
|
||||
const roleResourcesQuery =
|
||||
userRoleIds.length > 0
|
||||
? db
|
||||
.select({ resourceId: roleResources.resourceId })
|
||||
.from(roleResources)
|
||||
.where(inArray(roleResources.roleId, userRoleIds))
|
||||
.innerJoin(
|
||||
resources,
|
||||
eq(roleResources.resourceId, resources.resourceId)
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
inArray(roleResources.roleId, userRoleIds),
|
||||
eq(resources.orgId, orgId)
|
||||
)
|
||||
)
|
||||
: Promise.resolve([]);
|
||||
|
||||
const directPolicyResourcesQuery = db
|
||||
.select({ resourceId: resources.resourceId })
|
||||
.from(resources)
|
||||
.innerJoin(
|
||||
userPolicies,
|
||||
eq(effectiveResourcePolicyId, userPolicies.resourcePolicyId)
|
||||
)
|
||||
.where(
|
||||
and(eq(userPolicies.userId, userId), eq(resources.orgId, orgId))
|
||||
);
|
||||
|
||||
const rolePolicyResourcesQuery =
|
||||
userRoleIds.length > 0
|
||||
? db
|
||||
.select({ resourceId: resources.resourceId })
|
||||
.from(resources)
|
||||
.innerJoin(
|
||||
rolePolicies,
|
||||
eq(
|
||||
effectiveResourcePolicyId,
|
||||
rolePolicies.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
inArray(rolePolicies.roleId, userRoleIds),
|
||||
eq(resources.orgId, orgId)
|
||||
)
|
||||
)
|
||||
: Promise.resolve([]);
|
||||
|
||||
const directSiteResourcesQuery = db
|
||||
@@ -91,11 +162,15 @@ export async function getUserResources(
|
||||
const [
|
||||
directResources,
|
||||
roleResourceResults,
|
||||
directPolicyResourceResults,
|
||||
rolePolicyResourceResults,
|
||||
directSiteResourceResults,
|
||||
roleSiteResourceResults
|
||||
] = await Promise.all([
|
||||
directResourcesQuery,
|
||||
roleResourcesQuery,
|
||||
directPolicyResourcesQuery,
|
||||
rolePolicyResourcesQuery,
|
||||
directSiteResourcesQuery,
|
||||
roleSiteResourcesQuery
|
||||
]);
|
||||
@@ -103,42 +178,62 @@ export async function getUserResources(
|
||||
// Combine all accessible resource IDs
|
||||
const accessibleResourceIds = [
|
||||
...directResources.map((r) => r.resourceId),
|
||||
...roleResourceResults.map((r) => r.resourceId)
|
||||
...roleResourceResults.map((r) => r.resourceId),
|
||||
...directPolicyResourceResults.map((r) => r.resourceId),
|
||||
...rolePolicyResourceResults.map((r) => r.resourceId)
|
||||
];
|
||||
|
||||
// remove duplicates
|
||||
const uniqueResourceIds = Array.from(new Set(accessibleResourceIds));
|
||||
|
||||
// Combine all accessible site resource IDs
|
||||
const accessibleSiteResourceIds = [
|
||||
...directSiteResourceResults.map((r) => r.siteResourceId),
|
||||
...roleSiteResourceResults.map((r) => r.siteResourceId)
|
||||
];
|
||||
const uniqueSiteResourceIds = Array.from(
|
||||
new Set(accessibleSiteResourceIds)
|
||||
);
|
||||
|
||||
// Get resource details for accessible resources
|
||||
let resourcesData: Array<{
|
||||
resourceId: number;
|
||||
effectiveResourcePolicyId: number | null;
|
||||
name: string;
|
||||
fullDomain: string | null;
|
||||
ssl: boolean;
|
||||
enabled: boolean;
|
||||
sso: boolean;
|
||||
protocol: string;
|
||||
emailWhitelistEnabled: boolean;
|
||||
sso: boolean | null;
|
||||
mode: string;
|
||||
emailWhitelistEnabled: boolean | null;
|
||||
policyEmailWhitelistEnabled: boolean | null;
|
||||
}> = [];
|
||||
if (accessibleResourceIds.length > 0) {
|
||||
if (uniqueResourceIds.length > 0) {
|
||||
resourcesData = await db
|
||||
.select({
|
||||
resourceId: resources.resourceId,
|
||||
effectiveResourcePolicyId,
|
||||
name: resources.name,
|
||||
fullDomain: resources.fullDomain,
|
||||
ssl: resources.ssl,
|
||||
enabled: resources.enabled,
|
||||
sso: resources.sso,
|
||||
protocol: resources.protocol,
|
||||
emailWhitelistEnabled: resources.emailWhitelistEnabled
|
||||
mode: resources.mode,
|
||||
emailWhitelistEnabled: resources.emailWhitelistEnabled,
|
||||
policyEmailWhitelistEnabled:
|
||||
resourcePolicies.emailWhitelistEnabled
|
||||
})
|
||||
.from(resources)
|
||||
.leftJoin(
|
||||
resourcePolicies,
|
||||
eq(
|
||||
effectiveResourcePolicyId,
|
||||
resourcePolicies.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.where(
|
||||
and(
|
||||
inArray(resources.resourceId, accessibleResourceIds),
|
||||
inArray(resources.resourceId, uniqueResourceIds),
|
||||
eq(resources.orgId, orgId),
|
||||
eq(resources.enabled, true)
|
||||
)
|
||||
@@ -167,7 +262,7 @@ export async function getUserResources(
|
||||
siteAddresses: (string | null)[];
|
||||
siteOnlines: boolean[];
|
||||
}> = [];
|
||||
if (accessibleSiteResourceIds.length > 0) {
|
||||
if (uniqueSiteResourceIds.length > 0) {
|
||||
const aggCol = <T>(column: any) => {
|
||||
if (DB_TYPE === "sqlite") {
|
||||
return sql<T>`json_group_array(${column})`;
|
||||
@@ -207,7 +302,7 @@ export async function getUserResources(
|
||||
and(
|
||||
inArray(
|
||||
siteResources.siteResourceId,
|
||||
accessibleSiteResourceIds
|
||||
uniqueSiteResourceIds
|
||||
),
|
||||
eq(siteResources.orgId, orgId),
|
||||
eq(siteResources.enabled, true)
|
||||
@@ -263,47 +358,157 @@ export async function getUserResources(
|
||||
});
|
||||
}
|
||||
|
||||
const resourceIdList = resourcesData.map((r) => r.resourceId);
|
||||
const siteResourceIdList = siteResourcesData.map(
|
||||
(r) => r.siteResourceId
|
||||
);
|
||||
|
||||
const isLabelFeatureEnabled = await isLicensedOrSubscribed(
|
||||
orgId,
|
||||
tierMatrix.labels
|
||||
);
|
||||
|
||||
let labelsForResources: Array<{
|
||||
labelId: number;
|
||||
name: string;
|
||||
color: string;
|
||||
resourceId: number;
|
||||
}> = [];
|
||||
let labelsForSiteResources: Array<{
|
||||
labelId: number;
|
||||
name: string;
|
||||
color: string;
|
||||
siteResourceId: number;
|
||||
}> = [];
|
||||
|
||||
if (isLabelFeatureEnabled) {
|
||||
[labelsForResources, labelsForSiteResources] = await Promise.all([
|
||||
resourceIdList.length === 0
|
||||
? Promise.resolve([])
|
||||
: db
|
||||
.select({
|
||||
labelId: labels.labelId,
|
||||
name: labels.name,
|
||||
color: labels.color,
|
||||
resourceId: resourceLabels.resourceId
|
||||
})
|
||||
.from(labels)
|
||||
.innerJoin(
|
||||
resourceLabels,
|
||||
eq(resourceLabels.labelId, labels.labelId)
|
||||
)
|
||||
.where(
|
||||
inArray(resourceLabels.resourceId, resourceIdList)
|
||||
)
|
||||
.orderBy(asc(resourceLabels.resourceLabelId)),
|
||||
siteResourceIdList.length === 0
|
||||
? Promise.resolve([])
|
||||
: db
|
||||
.select({
|
||||
labelId: labels.labelId,
|
||||
name: labels.name,
|
||||
color: labels.color,
|
||||
siteResourceId: siteResourceLabels.siteResourceId
|
||||
})
|
||||
.from(labels)
|
||||
.innerJoin(
|
||||
siteResourceLabels,
|
||||
eq(siteResourceLabels.labelId, labels.labelId)
|
||||
)
|
||||
.where(
|
||||
inArray(
|
||||
siteResourceLabels.siteResourceId,
|
||||
siteResourceIdList
|
||||
)
|
||||
)
|
||||
.orderBy(asc(siteResourceLabels.siteResourceLabelId))
|
||||
]);
|
||||
}
|
||||
|
||||
// Check for password, pincode, and whitelist protection for each resource
|
||||
const resourcesWithAuth = await Promise.all(
|
||||
resourcesData.map(async (resource) => {
|
||||
const [passwordCheck, pincodeCheck, whitelistCheck] =
|
||||
await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(resourcePassword)
|
||||
.where(
|
||||
eq(
|
||||
resourcePassword.resourceId,
|
||||
resource.resourceId
|
||||
)
|
||||
)
|
||||
.limit(1),
|
||||
db
|
||||
.select()
|
||||
.from(resourcePincode)
|
||||
.where(
|
||||
eq(
|
||||
resourcePincode.resourceId,
|
||||
resource.resourceId
|
||||
)
|
||||
)
|
||||
.limit(1),
|
||||
db
|
||||
.select()
|
||||
.from(resourceWhitelist)
|
||||
.where(
|
||||
eq(
|
||||
resourceWhitelist.resourceId,
|
||||
resource.resourceId
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
]);
|
||||
const policyId = resource.effectiveResourcePolicyId;
|
||||
|
||||
const hasPassword = passwordCheck.length > 0;
|
||||
const hasPincode = pincodeCheck.length > 0;
|
||||
const [
|
||||
passwordCheck,
|
||||
pincodeCheck,
|
||||
whitelistCheck,
|
||||
policyPasswordCheck,
|
||||
policyPincodeCheck,
|
||||
policyWhitelistCheck
|
||||
] = await Promise.all([
|
||||
db
|
||||
.select()
|
||||
.from(resourcePassword)
|
||||
.where(
|
||||
eq(resourcePassword.resourceId, resource.resourceId)
|
||||
)
|
||||
.limit(1),
|
||||
db
|
||||
.select()
|
||||
.from(resourcePincode)
|
||||
.where(
|
||||
eq(resourcePincode.resourceId, resource.resourceId)
|
||||
)
|
||||
.limit(1),
|
||||
db
|
||||
.select()
|
||||
.from(resourceWhitelist)
|
||||
.where(
|
||||
eq(
|
||||
resourceWhitelist.resourceId,
|
||||
resource.resourceId
|
||||
)
|
||||
)
|
||||
.limit(1),
|
||||
policyId
|
||||
? db
|
||||
.select()
|
||||
.from(resourcePolicyPassword)
|
||||
.where(
|
||||
eq(
|
||||
resourcePolicyPassword.resourcePolicyId,
|
||||
policyId
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
: Promise.resolve([]),
|
||||
policyId
|
||||
? db
|
||||
.select()
|
||||
.from(resourcePolicyPincode)
|
||||
.where(
|
||||
eq(
|
||||
resourcePolicyPincode.resourcePolicyId,
|
||||
policyId
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
: Promise.resolve([]),
|
||||
policyId
|
||||
? db
|
||||
.select()
|
||||
.from(resourcePolicyWhiteList)
|
||||
.where(
|
||||
eq(
|
||||
resourcePolicyWhiteList.resourcePolicyId,
|
||||
policyId
|
||||
)
|
||||
)
|
||||
.limit(1)
|
||||
: Promise.resolve([])
|
||||
]);
|
||||
|
||||
const hasPassword =
|
||||
passwordCheck.length > 0 || policyPasswordCheck.length > 0;
|
||||
const hasPincode =
|
||||
pincodeCheck.length > 0 || policyPincodeCheck.length > 0;
|
||||
const hasWhitelist =
|
||||
whitelistCheck.length > 0 || resource.emailWhitelistEnabled;
|
||||
whitelistCheck.length > 0 ||
|
||||
policyWhitelistCheck.length > 0 ||
|
||||
resource.emailWhitelistEnabled ||
|
||||
!!resource.policyEmailWhitelistEnabled;
|
||||
|
||||
return {
|
||||
resourceId: resource.resourceId,
|
||||
@@ -316,11 +521,14 @@ export async function getUserResources(
|
||||
hasPincode ||
|
||||
hasWhitelist
|
||||
),
|
||||
protocol: resource.protocol,
|
||||
mode: resource.mode,
|
||||
sso: resource.sso,
|
||||
password: hasPassword,
|
||||
pincode: hasPincode,
|
||||
whitelist: hasWhitelist
|
||||
whitelist: hasWhitelist,
|
||||
labels: labelsForResources.filter(
|
||||
(l) => l.resourceId === resource.resourceId
|
||||
)
|
||||
};
|
||||
})
|
||||
);
|
||||
@@ -330,9 +538,9 @@ export async function getUserResources(
|
||||
return {
|
||||
siteResourceId: siteResource.siteResourceId,
|
||||
name: siteResource.name,
|
||||
niceId: siteResource.niceId,
|
||||
destination: siteResource.destination,
|
||||
mode: siteResource.mode,
|
||||
protocol: siteResource.scheme,
|
||||
ssl: siteResource.ssl,
|
||||
fullDomain: siteResource.fullDomain,
|
||||
enabled: siteResource.enabled,
|
||||
@@ -346,7 +554,10 @@ export async function getUserResources(
|
||||
siteNiceIds: siteResource.siteNiceIds,
|
||||
siteAddresses: siteResource.siteAddresses,
|
||||
siteOnlines: siteResource.siteOnlines,
|
||||
type: "site" as const
|
||||
type: "site" as const,
|
||||
labels: labelsForSiteResources.filter(
|
||||
(l) => l.siteResourceId === siteResource.siteResourceId
|
||||
)
|
||||
};
|
||||
});
|
||||
|
||||
@@ -380,14 +591,15 @@ export type GetUserResourcesResponse = {
|
||||
domain: string;
|
||||
enabled: boolean;
|
||||
protected: boolean;
|
||||
protocol: string;
|
||||
mode: string;
|
||||
labels?: Array<Pick<Label, "color" | "labelId" | "name">>;
|
||||
}>;
|
||||
siteResources: Array<{
|
||||
siteResourceId: number;
|
||||
name: string;
|
||||
niceId: string;
|
||||
destination: string;
|
||||
mode: string;
|
||||
protocol: string | null;
|
||||
tcpPortRangeString: string | null;
|
||||
udpPortRangeString: string | null;
|
||||
disableIcmp: boolean | null;
|
||||
@@ -402,6 +614,7 @@ export type GetUserResourcesResponse = {
|
||||
siteAddresses: (string | null)[];
|
||||
siteOnlines: boolean[];
|
||||
type: "site";
|
||||
labels?: Array<Pick<Label, "color" | "labelId" | "name">>;
|
||||
}>;
|
||||
};
|
||||
};
|
||||
|
||||
@@ -33,3 +33,4 @@ export * from "./removeUserFromResource";
|
||||
export * from "./listAllResourceNames";
|
||||
export * from "./removeEmailFromResourceWhitelist";
|
||||
export * from "./getStatusHistory";
|
||||
export * from "./getResourcePolicies";
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
import { assertEquals } from "../../../test/assert";
|
||||
import { applyInlinePolicyFields } from "./inlinePolicyFields";
|
||||
|
||||
function runTests() {
|
||||
const resource = {
|
||||
resourceId: 1,
|
||||
name: "dashboard",
|
||||
sso: null,
|
||||
emailWhitelistEnabled: null,
|
||||
applyRules: null,
|
||||
skipToIdpId: null
|
||||
} as any;
|
||||
|
||||
const enabledPolicy = {
|
||||
sso: true,
|
||||
emailWhitelistEnabled: true,
|
||||
applyRules: true,
|
||||
idpId: 42
|
||||
};
|
||||
|
||||
const enabledResult = applyInlinePolicyFields(resource, enabledPolicy);
|
||||
assertEquals(enabledResult.sso, true, "sso should mirror policy true");
|
||||
assertEquals(
|
||||
enabledResult.emailWhitelistEnabled,
|
||||
true,
|
||||
"email whitelist should mirror policy true"
|
||||
);
|
||||
assertEquals(
|
||||
enabledResult.applyRules,
|
||||
true,
|
||||
"applyRules should mirror policy true"
|
||||
);
|
||||
assertEquals(
|
||||
enabledResult.skipToIdpId,
|
||||
42,
|
||||
"skipToIdpId should use policy idpId"
|
||||
);
|
||||
|
||||
const disabledPolicy = {
|
||||
sso: false,
|
||||
emailWhitelistEnabled: false,
|
||||
applyRules: false,
|
||||
idpId: null
|
||||
};
|
||||
|
||||
const disabledResult = applyInlinePolicyFields(resource, disabledPolicy);
|
||||
assertEquals(disabledResult.sso, false, "sso false must not become null");
|
||||
assertEquals(
|
||||
disabledResult.emailWhitelistEnabled,
|
||||
false,
|
||||
"email whitelist false must not become null"
|
||||
);
|
||||
assertEquals(
|
||||
disabledResult.applyRules,
|
||||
false,
|
||||
"applyRules false must not become null"
|
||||
);
|
||||
assertEquals(
|
||||
disabledResult.skipToIdpId,
|
||||
null,
|
||||
"missing idp should stay null"
|
||||
);
|
||||
|
||||
const missingPolicyResult = applyInlinePolicyFields(resource, null);
|
||||
assertEquals(
|
||||
missingPolicyResult.sso,
|
||||
null,
|
||||
"missing policy should return nullable resource fields"
|
||||
);
|
||||
|
||||
console.log("PASS: inline policy fields mirror policy values");
|
||||
}
|
||||
|
||||
runTests();
|
||||
@@ -0,0 +1,19 @@
|
||||
import type { Resource, ResourcePolicy } from "@server/db";
|
||||
|
||||
type InlinePolicyFields = Pick<
|
||||
ResourcePolicy,
|
||||
"sso" | "emailWhitelistEnabled" | "applyRules" | "idpId"
|
||||
>;
|
||||
|
||||
export function applyInlinePolicyFields<T extends Resource>(
|
||||
resource: T,
|
||||
policy: InlinePolicyFields | null | undefined
|
||||
): T {
|
||||
return {
|
||||
...resource,
|
||||
sso: policy?.sso ?? null,
|
||||
emailWhitelistEnabled: policy?.emailWhitelistEnabled ?? null,
|
||||
applyRules: policy?.applyRules ?? null,
|
||||
skipToIdpId: policy?.idpId ?? null
|
||||
};
|
||||
}
|
||||
@@ -39,7 +39,22 @@ registry.registerPath({
|
||||
orgId: z.string()
|
||||
})
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function listAllResourceNames(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { roleResources, roles } from "@server/db";
|
||||
import { roleResources, roles, rolePolicies, resources } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
@@ -11,7 +11,7 @@ import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const listResourceRolesSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
async function query(resourceId: number) {
|
||||
@@ -27,6 +27,19 @@ async function query(resourceId: number) {
|
||||
.where(eq(roleResources.resourceId, resourceId));
|
||||
}
|
||||
|
||||
async function queryInlinePolicy(policyId: number) {
|
||||
return await db
|
||||
.select({
|
||||
roleId: roles.roleId,
|
||||
name: roles.name,
|
||||
description: roles.description,
|
||||
isAdmin: roles.isAdmin
|
||||
})
|
||||
.from(rolePolicies)
|
||||
.innerJoin(roles, eq(rolePolicies.roleId, roles.roleId))
|
||||
.where(eq(rolePolicies.resourcePolicyId, policyId));
|
||||
}
|
||||
|
||||
export type ListResourceRolesResponse = {
|
||||
roles: NonNullable<Awaited<ReturnType<typeof query>>>;
|
||||
};
|
||||
@@ -39,7 +52,22 @@ registry.registerPath({
|
||||
request: {
|
||||
params: listResourceRolesSchema
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function listResourceRoles(
|
||||
@@ -60,7 +88,25 @@ export async function listResourceRoles(
|
||||
|
||||
const { resourceId } = parsedParams.data;
|
||||
|
||||
const resourceRolesList = await query(resourceId);
|
||||
const [resource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
|
||||
);
|
||||
}
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
const resourceRolesList = isInlinePolicy
|
||||
? await queryInlinePolicy(resource.defaultResourcePolicyId!)
|
||||
: await query(resourceId);
|
||||
|
||||
return response<ListResourceRolesResponse>(res, {
|
||||
data: {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { db } from "@server/db";
|
||||
import { resourceRules, resources } from "@server/db";
|
||||
import { resourceRules, resourcePolicyRules, resources } from "@server/db";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import response from "@server/lib/response";
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
@@ -11,10 +11,10 @@ import logger from "@server/logger";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const listResourceRulesParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
const listResourceRulesSchema = z.object({
|
||||
const listResourceRulesSchema = z.strictObject({
|
||||
limit: z
|
||||
.string()
|
||||
.optional()
|
||||
@@ -47,6 +47,21 @@ function queryResourceRules(resourceId: number) {
|
||||
return baseQuery;
|
||||
}
|
||||
|
||||
function queryPolicyRules(policyId: number) {
|
||||
return db
|
||||
.select({
|
||||
ruleId: resourcePolicyRules.ruleId,
|
||||
resourceId: sql<number | null>`null`,
|
||||
action: resourcePolicyRules.action,
|
||||
match: resourcePolicyRules.match,
|
||||
value: resourcePolicyRules.value,
|
||||
priority: resourcePolicyRules.priority,
|
||||
enabled: resourcePolicyRules.enabled
|
||||
})
|
||||
.from(resourcePolicyRules)
|
||||
.where(eq(resourcePolicyRules.resourcePolicyId, policyId));
|
||||
}
|
||||
|
||||
export type ListResourceRulesResponse = {
|
||||
rules: Awaited<ReturnType<typeof queryResourceRules>>;
|
||||
pagination: { total: number; limit: number; offset: number };
|
||||
@@ -61,7 +76,22 @@ registry.registerPath({
|
||||
params: listResourceRulesParamsSchema,
|
||||
query: listResourceRulesSchema
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function listResourceRules(
|
||||
@@ -110,16 +140,34 @@ export async function listResourceRules(
|
||||
);
|
||||
}
|
||||
|
||||
const baseQuery = queryResourceRules(resourceId);
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
const countQuery = db
|
||||
.select({ count: sql<number>`cast(count(*) as integer)` })
|
||||
.from(resourceRules)
|
||||
.where(eq(resourceRules.resourceId, resourceId));
|
||||
let rulesList: Awaited<ReturnType<typeof queryResourceRules>>;
|
||||
let totalCount: number;
|
||||
|
||||
let rulesList = await baseQuery.limit(limit).offset(offset);
|
||||
const totalCountResult = await countQuery;
|
||||
const totalCount = totalCountResult[0].count;
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
const policyRules = await queryPolicyRules(policyId)
|
||||
.limit(limit)
|
||||
.offset(offset);
|
||||
const countResult = await db
|
||||
.select({ count: sql<number>`cast(count(*) as integer)` })
|
||||
.from(resourcePolicyRules)
|
||||
.where(eq(resourcePolicyRules.resourcePolicyId, policyId));
|
||||
rulesList = policyRules as typeof rulesList;
|
||||
totalCount = countResult[0].count;
|
||||
} else {
|
||||
const baseQuery = queryResourceRules(resourceId);
|
||||
const countQuery = db
|
||||
.select({ count: sql<number>`cast(count(*) as integer)` })
|
||||
.from(resourceRules)
|
||||
.where(eq(resourceRules.resourceId, resourceId));
|
||||
rulesList = await baseQuery.limit(limit).offset(offset);
|
||||
const totalCountResult = await countQuery;
|
||||
totalCount = totalCountResult[0].count;
|
||||
}
|
||||
|
||||
// sort rules list by the priority in ascending order
|
||||
rulesList = rulesList.sort((a, b) => a.priority - b.priority);
|
||||
|
||||
@@ -11,7 +11,7 @@ import { fromError } from "zod-validation-error";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const listResourceUsersSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
async function queryUsers(resourceId: number) {
|
||||
@@ -42,7 +42,22 @@ registry.registerPath({
|
||||
request: {
|
||||
params: listResourceUsersSchema
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function listResourceUsers(
|
||||
|
||||
@@ -1,11 +1,15 @@
|
||||
import {
|
||||
alias,
|
||||
db,
|
||||
labels,
|
||||
resourceHeaderAuth,
|
||||
resourceHeaderAuthExtendedCompatibility,
|
||||
resourceLabels,
|
||||
resourcePassword,
|
||||
resourcePincode,
|
||||
resourcePolicies,
|
||||
resourcePolicyHeaderAuth,
|
||||
resourcePolicyPassword,
|
||||
resourcePolicyPincode,
|
||||
resources,
|
||||
roleResources,
|
||||
sites,
|
||||
@@ -44,7 +48,7 @@ const listResourcesParamsSchema = z.strictObject({
|
||||
orgId: z.string()
|
||||
});
|
||||
|
||||
const listResourcesSchema = z.object({
|
||||
const listResourcesSchema = z.strictObject({
|
||||
pageSize: z.coerce
|
||||
.number<string>() // for prettier formatting
|
||||
.int()
|
||||
@@ -119,6 +123,16 @@ const listResourcesSchema = z.object({
|
||||
description:
|
||||
"Filter resources based on health status of their targets. `healthy` means all targets are healthy. `degraded` means at least one target is unhealthy, but not all are unhealthy. `offline` means all targets are unhealthy. `unknown` means all targets have unknown health status."
|
||||
}),
|
||||
protocol: z
|
||||
.enum(["http", "https", "tcp", "udp", "ssh", "rdp", "vnc"])
|
||||
.optional()
|
||||
.catch(undefined)
|
||||
.openapi({
|
||||
type: "string",
|
||||
enum: ["http", "https", "tcp", "udp", "ssh", "rdp", "vnc"],
|
||||
description:
|
||||
"Filter resources by protocol. `http` and `https` match HTTP resources without and with SSL respectively."
|
||||
}),
|
||||
siteId: z.coerce.number<string>().int().positive().optional().openapi({
|
||||
type: "integer",
|
||||
description:
|
||||
@@ -156,8 +170,6 @@ export type ResourceWithTargets = {
|
||||
sso: boolean;
|
||||
pincodeId: number | null;
|
||||
whitelist: boolean;
|
||||
http: boolean;
|
||||
protocol: string;
|
||||
proxyPort: number | null;
|
||||
enabled: boolean;
|
||||
domainId: string | null;
|
||||
@@ -165,6 +177,7 @@ export type ResourceWithTargets = {
|
||||
headerAuthId: number | null;
|
||||
wildcard: boolean;
|
||||
health: string | null;
|
||||
mode: string | null;
|
||||
targets: Array<{
|
||||
targetId: number;
|
||||
ip: string;
|
||||
@@ -183,46 +196,173 @@ export type ResourceWithTargets = {
|
||||
};
|
||||
|
||||
function queryResourcesBase() {
|
||||
const sharedPolicy = alias(resourcePolicies, "sharedPolicy");
|
||||
const defaultPolicy = alias(resourcePolicies, "defaultPolicy");
|
||||
const sharedPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"sharedPolicyPincode"
|
||||
);
|
||||
const defaultPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"defaultPolicyPincode"
|
||||
);
|
||||
const sharedPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"sharedPolicyPassword"
|
||||
);
|
||||
const defaultPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"defaultPolicyPassword"
|
||||
);
|
||||
const sharedPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"sharedPolicyHeaderAuth"
|
||||
);
|
||||
const defaultPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"defaultPolicyHeaderAuth"
|
||||
);
|
||||
|
||||
const effectivePasswordId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyPassword.passwordId}
|
||||
ELSE ${defaultPolicyPassword.passwordId}
|
||||
END,
|
||||
${resourcePassword.passwordId}
|
||||
)
|
||||
`;
|
||||
const effectivePincodeId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyPincode.pincodeId}
|
||||
ELSE ${defaultPolicyPincode.pincodeId}
|
||||
END,
|
||||
${resourcePincode.pincodeId}
|
||||
)
|
||||
`;
|
||||
const effectiveHeaderAuthId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyHeaderAuth.headerAuthId}
|
||||
ELSE ${defaultPolicyHeaderAuth.headerAuthId}
|
||||
END,
|
||||
${resourceHeaderAuth.headerAuthId}
|
||||
)
|
||||
`;
|
||||
const effectiveSso = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicy.sso}
|
||||
ELSE ${defaultPolicy.sso}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
const effectiveWhitelist = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicy.emailWhitelistEnabled}
|
||||
ELSE ${defaultPolicy.emailWhitelistEnabled}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
const effectiveHeaderAuthExtendedCompatibility = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyHeaderAuth.extendedCompatibility}
|
||||
ELSE ${defaultPolicyHeaderAuth.extendedCompatibility}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
|
||||
return db
|
||||
.select({
|
||||
resourceId: resources.resourceId,
|
||||
name: resources.name,
|
||||
ssl: resources.ssl,
|
||||
fullDomain: resources.fullDomain,
|
||||
passwordId: resourcePassword.passwordId,
|
||||
sso: resources.sso,
|
||||
pincodeId: resourcePincode.pincodeId,
|
||||
whitelist: resources.emailWhitelistEnabled,
|
||||
http: resources.http,
|
||||
protocol: resources.protocol,
|
||||
passwordId: effectivePasswordId,
|
||||
sso: effectiveSso,
|
||||
pincodeId: effectivePincodeId,
|
||||
whitelist: effectiveWhitelist,
|
||||
proxyPort: resources.proxyPort,
|
||||
enabled: resources.enabled,
|
||||
domainId: resources.domainId,
|
||||
niceId: resources.niceId,
|
||||
wildcard: resources.wildcard,
|
||||
headerAuthId: resourceHeaderAuth.headerAuthId,
|
||||
headerAuthExtendedCompatibilityId:
|
||||
resourceHeaderAuthExtendedCompatibility.headerAuthExtendedCompatibilityId,
|
||||
health: resources.health
|
||||
mode: resources.mode,
|
||||
health: resources.health,
|
||||
headerAuthId: effectiveHeaderAuthId,
|
||||
headerAuthExtendedCompatibility:
|
||||
effectiveHeaderAuthExtendedCompatibility
|
||||
})
|
||||
.from(resources)
|
||||
.leftJoin(
|
||||
resourcePassword,
|
||||
eq(resourcePassword.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
resourcePincode,
|
||||
eq(resourcePincode.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
resourcePassword,
|
||||
eq(resourcePassword.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
resourceHeaderAuth,
|
||||
eq(resourceHeaderAuth.resourceId, resources.resourceId)
|
||||
)
|
||||
.leftJoin(
|
||||
resourceHeaderAuthExtendedCompatibility,
|
||||
sharedPolicy,
|
||||
eq(sharedPolicy.resourcePolicyId, resources.resourcePolicyId)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicyPincode,
|
||||
eq(
|
||||
resourceHeaderAuthExtendedCompatibility.resourceId,
|
||||
resources.resourceId
|
||||
sharedPolicyPincode.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicyPassword,
|
||||
eq(
|
||||
sharedPolicyPassword.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
sharedPolicyHeaderAuth,
|
||||
eq(
|
||||
sharedPolicyHeaderAuth.resourcePolicyId,
|
||||
sharedPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicy,
|
||||
eq(
|
||||
defaultPolicy.resourcePolicyId,
|
||||
resources.defaultResourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyPincode,
|
||||
eq(
|
||||
defaultPolicyPincode.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyPassword,
|
||||
eq(
|
||||
defaultPolicyPassword.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(
|
||||
defaultPolicyHeaderAuth,
|
||||
eq(
|
||||
defaultPolicyHeaderAuth.resourcePolicyId,
|
||||
defaultPolicy.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.leftJoin(targets, eq(targets.resourceId, resources.resourceId))
|
||||
@@ -232,10 +372,23 @@ function queryResourcesBase() {
|
||||
)
|
||||
.groupBy(
|
||||
resources.resourceId,
|
||||
resourcePassword.passwordId,
|
||||
resourcePincode.pincodeId,
|
||||
resourcePassword.passwordId,
|
||||
resourceHeaderAuth.headerAuthId,
|
||||
resourceHeaderAuthExtendedCompatibility.headerAuthExtendedCompatibilityId
|
||||
sharedPolicy.resourcePolicyId,
|
||||
sharedPolicy.sso,
|
||||
sharedPolicy.emailWhitelistEnabled,
|
||||
sharedPolicyPincode.pincodeId,
|
||||
sharedPolicyPassword.passwordId,
|
||||
sharedPolicyHeaderAuth.headerAuthId,
|
||||
sharedPolicyHeaderAuth.extendedCompatibility,
|
||||
defaultPolicy.resourcePolicyId,
|
||||
defaultPolicy.sso,
|
||||
defaultPolicy.emailWhitelistEnabled,
|
||||
defaultPolicyPincode.pincodeId,
|
||||
defaultPolicyPassword.passwordId,
|
||||
defaultPolicyHeaderAuth.headerAuthId,
|
||||
defaultPolicyHeaderAuth.extendedCompatibility
|
||||
);
|
||||
}
|
||||
|
||||
@@ -254,7 +407,22 @@ registry.registerPath({
|
||||
}),
|
||||
query: listResourcesSchema
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function listResources(
|
||||
@@ -279,6 +447,7 @@ export async function listResources(
|
||||
enabled,
|
||||
query,
|
||||
healthStatus,
|
||||
protocol,
|
||||
sort_by,
|
||||
order,
|
||||
siteId,
|
||||
@@ -362,28 +531,110 @@ export async function listResources(
|
||||
}
|
||||
|
||||
if (typeof authState !== "undefined") {
|
||||
const sharedPolicy = alias(resourcePolicies, "sharedPolicy");
|
||||
const defaultPolicy = alias(resourcePolicies, "defaultPolicy");
|
||||
const sharedPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"sharedPolicyPincode"
|
||||
);
|
||||
const defaultPolicyPincode = alias(
|
||||
resourcePolicyPincode,
|
||||
"defaultPolicyPincode"
|
||||
);
|
||||
const sharedPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"sharedPolicyPassword"
|
||||
);
|
||||
const defaultPolicyPassword = alias(
|
||||
resourcePolicyPassword,
|
||||
"defaultPolicyPassword"
|
||||
);
|
||||
const sharedPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"sharedPolicyHeaderAuth"
|
||||
);
|
||||
const defaultPolicyHeaderAuth = alias(
|
||||
resourcePolicyHeaderAuth,
|
||||
"defaultPolicyHeaderAuth"
|
||||
);
|
||||
|
||||
const effectiveSso = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicy.sso}
|
||||
ELSE ${defaultPolicy.sso}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
const effectiveWhitelist = sql<boolean>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicy.emailWhitelistEnabled}
|
||||
ELSE ${defaultPolicy.emailWhitelistEnabled}
|
||||
END,
|
||||
false
|
||||
)
|
||||
`;
|
||||
const effectiveHeaderAuthId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyHeaderAuth.headerAuthId}
|
||||
ELSE ${defaultPolicyHeaderAuth.headerAuthId}
|
||||
END,
|
||||
${resourceHeaderAuth.headerAuthId}
|
||||
)
|
||||
`;
|
||||
const effectivePincodeId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyPincode.pincodeId}
|
||||
ELSE ${defaultPolicyPincode.pincodeId}
|
||||
END,
|
||||
${resourcePincode.pincodeId}
|
||||
)
|
||||
`;
|
||||
const effectivePasswordId = sql<number | null>`
|
||||
COALESCE(
|
||||
CASE
|
||||
WHEN ${sharedPolicy.resourcePolicyId} IS NOT NULL THEN ${sharedPolicyPassword.passwordId}
|
||||
ELSE ${defaultPolicyPassword.passwordId}
|
||||
END,
|
||||
${resourcePassword.passwordId}
|
||||
)
|
||||
`;
|
||||
const browserGatewayModes = ["http", "ssh", "rdp", "vnc"];
|
||||
|
||||
switch (authState) {
|
||||
case "none":
|
||||
conditions.push(eq(resources.http, false));
|
||||
conditions.push(
|
||||
or(eq(resources.mode, "tcp"), eq(resources.mode, "udp"))
|
||||
);
|
||||
break;
|
||||
case "protected":
|
||||
conditions.push(
|
||||
or(
|
||||
eq(resources.sso, true),
|
||||
eq(resources.emailWhitelistEnabled, true),
|
||||
not(isNull(resourceHeaderAuth.headerAuthId)),
|
||||
not(isNull(resourcePincode.pincodeId)),
|
||||
not(isNull(resourcePassword.passwordId))
|
||||
and(
|
||||
inArray(resources.mode, browserGatewayModes),
|
||||
or(
|
||||
effectiveSso,
|
||||
effectiveWhitelist,
|
||||
not(isNull(effectiveHeaderAuthId)),
|
||||
not(isNull(effectivePincodeId)),
|
||||
not(isNull(effectivePasswordId))
|
||||
)
|
||||
)
|
||||
);
|
||||
break;
|
||||
case "not_protected":
|
||||
conditions.push(
|
||||
not(eq(resources.sso, true)),
|
||||
not(eq(resources.emailWhitelistEnabled, true)),
|
||||
isNull(resourceHeaderAuth.headerAuthId),
|
||||
isNull(resourcePincode.pincodeId),
|
||||
isNull(resourcePassword.passwordId)
|
||||
and(
|
||||
inArray(resources.mode, browserGatewayModes),
|
||||
not(effectiveSso),
|
||||
not(effectiveWhitelist),
|
||||
isNull(effectiveHeaderAuthId),
|
||||
isNull(effectivePincodeId),
|
||||
isNull(effectivePasswordId)
|
||||
)
|
||||
);
|
||||
break;
|
||||
}
|
||||
@@ -392,13 +643,37 @@ export async function listResources(
|
||||
if (typeof healthStatus !== "undefined") {
|
||||
conditions.push(eq(resources.health, healthStatus));
|
||||
}
|
||||
|
||||
if (typeof protocol !== "undefined") {
|
||||
switch (protocol) {
|
||||
case "http":
|
||||
conditions.push(
|
||||
and(
|
||||
eq(resources.mode, "http"),
|
||||
eq(resources.ssl, false)
|
||||
)
|
||||
);
|
||||
break;
|
||||
case "https":
|
||||
conditions.push(
|
||||
and(eq(resources.mode, "http"), eq(resources.ssl, true))
|
||||
);
|
||||
break;
|
||||
default:
|
||||
conditions.push(eq(resources.mode, protocol));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (siteId != null) {
|
||||
const resourcesWithSite = db
|
||||
.select({ resourceId: targets.resourceId })
|
||||
.from(targets)
|
||||
.innerJoin(sites, eq(targets.siteId, sites.siteId))
|
||||
.where(and(eq(sites.orgId, orgId), eq(sites.siteId, siteId)));
|
||||
conditions.push(inArray(resources.resourceId, resourcesWithSite));
|
||||
conditions.push(
|
||||
or(inArray(resources.resourceId, resourcesWithSite))
|
||||
);
|
||||
}
|
||||
|
||||
if (isLabelFeatureEnabled && labelFilter && labelFilter.length > 0) {
|
||||
@@ -533,13 +808,12 @@ export async function listResources(
|
||||
ssl: row.ssl,
|
||||
fullDomain: row.fullDomain,
|
||||
passwordId: row.passwordId,
|
||||
sso: row.sso,
|
||||
sso: row.sso ?? false,
|
||||
pincodeId: row.pincodeId,
|
||||
whitelist: row.whitelist,
|
||||
http: row.http,
|
||||
protocol: row.protocol,
|
||||
whitelist: row.whitelist ?? false,
|
||||
proxyPort: row.proxyPort,
|
||||
wildcard: row.wildcard,
|
||||
mode: row.mode,
|
||||
enabled: row.enabled,
|
||||
domainId: row.domainId,
|
||||
headerAuthId: row.headerAuthId,
|
||||
|
||||
@@ -5,9 +5,13 @@ import {
|
||||
userSiteResources,
|
||||
roleSiteResources,
|
||||
userOrgRoles,
|
||||
userOrgs
|
||||
userOrgs,
|
||||
labels,
|
||||
siteResourceLabels
|
||||
} from "@server/db";
|
||||
import { and, eq, inArray, asc, isNotNull, ne } from "drizzle-orm";
|
||||
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
|
||||
import { tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { and, eq, inArray, asc, isNotNull, ne, or } from "drizzle-orm";
|
||||
import createHttpError from "http-errors";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import response from "@server/lib/response";
|
||||
@@ -15,25 +19,44 @@ import logger from "@server/logger";
|
||||
import { z } from "zod";
|
||||
import { fromZodError } from "zod-validation-error";
|
||||
import type { PaginatedResponse } from "@server/types/Pagination";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
import { localCache } from "#dynamic/lib/cache";
|
||||
import { regionalCache as cache } from "#dynamic/lib/cache";
|
||||
|
||||
const USER_RESOURCE_ALIASES_CACHE_TTL_SEC = 60;
|
||||
|
||||
const labelFilterQuerySchema = z
|
||||
.preprocess((val) => {
|
||||
if (val === undefined || val === null || val === "") {
|
||||
return undefined;
|
||||
}
|
||||
if (Array.isArray(val)) {
|
||||
return val;
|
||||
}
|
||||
if (typeof val === "string") {
|
||||
return val.split(",");
|
||||
}
|
||||
return undefined;
|
||||
}, z.array(z.string()))
|
||||
.optional()
|
||||
.catch([]);
|
||||
|
||||
function userResourceAliasesCacheKey(
|
||||
orgId: string,
|
||||
userId: string,
|
||||
page: number,
|
||||
pageSize: number
|
||||
pageSize: number,
|
||||
includeLabels: boolean,
|
||||
labelFilter: string[]
|
||||
) {
|
||||
return `userResourceAliases:${orgId}:${userId}:${page}:${pageSize}`;
|
||||
const labelsKey =
|
||||
labelFilter.length > 0 ? labelFilter.slice().sort().join(",") : "all";
|
||||
return `userResourceAliases:${orgId}:${userId}:${page}:${pageSize}:${includeLabels ? "labels" : "plain"}:${labelsKey}`;
|
||||
}
|
||||
|
||||
const listUserResourceAliasesParamsSchema = z.strictObject({
|
||||
orgId: z.string()
|
||||
});
|
||||
|
||||
const listUserResourceAliasesQuerySchema = z.object({
|
||||
const listUserResourceAliasesQuerySchema = z.strictObject({
|
||||
pageSize: z.coerce
|
||||
.number<string>()
|
||||
.int()
|
||||
@@ -57,28 +80,35 @@ const listUserResourceAliasesQuerySchema = z.object({
|
||||
type: "integer",
|
||||
default: 1,
|
||||
description: "Page number to retrieve"
|
||||
})
|
||||
}),
|
||||
includeLabels: z
|
||||
.enum(["true", "false"])
|
||||
.optional()
|
||||
.default("false")
|
||||
.transform((val) => val === "true")
|
||||
.openapi({
|
||||
type: "boolean",
|
||||
default: false,
|
||||
description:
|
||||
"When true, include label names for each alias in the items field"
|
||||
}),
|
||||
labels: labelFilterQuerySchema.openapi({
|
||||
type: "array",
|
||||
description:
|
||||
"Filter by resource labels. A resource matches when it has any of the given labels (OR)."
|
||||
})
|
||||
});
|
||||
|
||||
export type UserResourceAliasItem = {
|
||||
alias: string;
|
||||
labels: string[];
|
||||
};
|
||||
|
||||
export type ListUserResourceAliasesResponse = PaginatedResponse<{
|
||||
aliases: string[];
|
||||
items?: UserResourceAliasItem[];
|
||||
}>;
|
||||
|
||||
// registry.registerPath({
|
||||
// method: "get",
|
||||
// path: "/org/{orgId}/user-resource-aliases",
|
||||
// description:
|
||||
// "List private (host-mode) site resource aliases the authenticated user can access in the organization, paginated.",
|
||||
// tags: [OpenAPITags.PrivateResource],
|
||||
// request: {
|
||||
// params: z.object({
|
||||
// orgId: z.string()
|
||||
// }),
|
||||
// query: listUserResourceAliasesQuerySchema
|
||||
// },
|
||||
// responses: {}
|
||||
// });
|
||||
|
||||
export async function listUserResourceAliases(
|
||||
req: Request,
|
||||
res: Response,
|
||||
@@ -96,7 +126,12 @@ export async function listUserResourceAliases(
|
||||
)
|
||||
);
|
||||
}
|
||||
const { page, pageSize } = parsedQuery.data;
|
||||
const {
|
||||
page,
|
||||
pageSize,
|
||||
includeLabels,
|
||||
labels: labelFilter
|
||||
} = parsedQuery.data;
|
||||
|
||||
const parsedParams = listUserResourceAliasesParamsSchema.safeParse(
|
||||
req.params
|
||||
@@ -135,10 +170,12 @@ export async function listUserResourceAliases(
|
||||
orgId,
|
||||
userId,
|
||||
page,
|
||||
pageSize
|
||||
pageSize,
|
||||
includeLabels,
|
||||
labelFilter ?? []
|
||||
);
|
||||
const cachedData: ListUserResourceAliasesResponse | undefined =
|
||||
localCache.get(cacheKey);
|
||||
await cache.get(cacheKey);
|
||||
|
||||
if (cachedData) {
|
||||
return response<ListUserResourceAliasesResponse>(res, {
|
||||
@@ -190,13 +227,18 @@ export async function listUserResourceAliases(
|
||||
if (accessibleSiteResourceIds.length === 0) {
|
||||
const data: ListUserResourceAliasesResponse = {
|
||||
aliases: [],
|
||||
...(includeLabels ? { items: [] } : {}),
|
||||
pagination: {
|
||||
total: 0,
|
||||
pageSize,
|
||||
page
|
||||
}
|
||||
};
|
||||
localCache.set(cacheKey, data, USER_RESOURCE_ALIASES_CACHE_TTL_SEC);
|
||||
await cache.set(
|
||||
cacheKey,
|
||||
data,
|
||||
USER_RESOURCE_ALIASES_CACHE_TTL_SEC
|
||||
);
|
||||
return response<ListUserResourceAliasesResponse>(res, {
|
||||
data,
|
||||
success: true,
|
||||
@@ -206,18 +248,44 @@ export async function listUserResourceAliases(
|
||||
});
|
||||
}
|
||||
|
||||
const whereClause = and(
|
||||
const isLabelFeatureEnabled = await isLicensedOrSubscribed(
|
||||
orgId,
|
||||
tierMatrix.labels
|
||||
);
|
||||
|
||||
const whereConditions = [
|
||||
eq(siteResources.orgId, orgId),
|
||||
eq(siteResources.enabled, true),
|
||||
eq(siteResources.mode, "host"),
|
||||
or(eq(siteResources.mode, "host"), eq(siteResources.mode, "ssh")),
|
||||
isNotNull(siteResources.alias),
|
||||
ne(siteResources.alias, ""),
|
||||
inArray(siteResources.siteResourceId, accessibleSiteResourceIds)
|
||||
);
|
||||
];
|
||||
|
||||
if (isLabelFeatureEnabled && labelFilter && labelFilter.length > 0) {
|
||||
whereConditions.push(
|
||||
inArray(
|
||||
siteResources.siteResourceId,
|
||||
db
|
||||
.select({ id: siteResourceLabels.siteResourceId })
|
||||
.from(siteResourceLabels)
|
||||
.innerJoin(
|
||||
labels,
|
||||
eq(labels.labelId, siteResourceLabels.labelId)
|
||||
)
|
||||
.where(inArray(labels.name, labelFilter))
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const whereClause = and(...whereConditions);
|
||||
|
||||
const baseSelect = () =>
|
||||
db
|
||||
.select({ alias: siteResources.alias })
|
||||
.select({
|
||||
alias: siteResources.alias,
|
||||
siteResourceId: siteResources.siteResourceId
|
||||
})
|
||||
.from(siteResources)
|
||||
.where(whereClause);
|
||||
|
||||
@@ -233,15 +301,53 @@ export async function listUserResourceAliases(
|
||||
|
||||
const aliases = rows.map((r) => r.alias as string);
|
||||
|
||||
let items: UserResourceAliasItem[] | undefined;
|
||||
if (includeLabels) {
|
||||
const siteResourceIdList = rows.map((r) => r.siteResourceId);
|
||||
|
||||
let labelsForSiteResources: Array<{
|
||||
name: string;
|
||||
siteResourceId: number;
|
||||
}> = [];
|
||||
|
||||
if (isLabelFeatureEnabled && siteResourceIdList.length > 0) {
|
||||
labelsForSiteResources = await db
|
||||
.select({
|
||||
name: labels.name,
|
||||
siteResourceId: siteResourceLabels.siteResourceId
|
||||
})
|
||||
.from(labels)
|
||||
.innerJoin(
|
||||
siteResourceLabels,
|
||||
eq(siteResourceLabels.labelId, labels.labelId)
|
||||
)
|
||||
.where(
|
||||
inArray(
|
||||
siteResourceLabels.siteResourceId,
|
||||
siteResourceIdList
|
||||
)
|
||||
)
|
||||
.orderBy(asc(siteResourceLabels.siteResourceLabelId));
|
||||
}
|
||||
|
||||
items = rows.map((row) => ({
|
||||
alias: row.alias as string,
|
||||
labels: labelsForSiteResources
|
||||
.filter((l) => l.siteResourceId === row.siteResourceId)
|
||||
.map((l) => l.name)
|
||||
}));
|
||||
}
|
||||
|
||||
const data: ListUserResourceAliasesResponse = {
|
||||
aliases,
|
||||
...(items !== undefined ? { items } : {}),
|
||||
pagination: {
|
||||
total: totalCount,
|
||||
pageSize,
|
||||
page
|
||||
}
|
||||
};
|
||||
localCache.set(cacheKey, data, USER_RESOURCE_ALIASES_CACHE_TTL_SEC);
|
||||
await cache.set(cacheKey, data, USER_RESOURCE_ALIASES_CACHE_TTL_SEC);
|
||||
|
||||
return response<ListUserResourceAliasesResponse>(res, {
|
||||
data,
|
||||
|
||||
@@ -22,7 +22,7 @@ const removeEmailFromResourceWhitelistBodySchema = z.strictObject({
|
||||
});
|
||||
|
||||
const removeEmailFromResourceWhitelistParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
@@ -40,7 +40,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function removeEmailFromResourceWhitelist(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, resources } from "@server/db";
|
||||
import { roleResources, roles } from "@server/db";
|
||||
import { roleResources, roles, rolePolicies } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -40,7 +40,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function removeRoleFromResource(
|
||||
@@ -115,35 +130,71 @@ export async function removeRoleFromResource(
|
||||
);
|
||||
}
|
||||
|
||||
// Check if role exists in resource
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(roleResources)
|
||||
.where(
|
||||
and(
|
||||
eq(roleResources.resourceId, resourceId),
|
||||
eq(roleResources.roleId, roleId)
|
||||
)
|
||||
);
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
if (existingEntry.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"Role not found in resource"
|
||||
)
|
||||
);
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(rolePolicies)
|
||||
.where(
|
||||
and(
|
||||
eq(rolePolicies.resourcePolicyId, policyId),
|
||||
eq(rolePolicies.roleId, roleId)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingEntry.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"Role not found in resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(rolePolicies)
|
||||
.where(
|
||||
and(
|
||||
eq(rolePolicies.resourcePolicyId, policyId),
|
||||
eq(rolePolicies.roleId, roleId)
|
||||
)
|
||||
);
|
||||
} else {
|
||||
// Check if role exists in resource
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(roleResources)
|
||||
.where(
|
||||
and(
|
||||
eq(roleResources.resourceId, resourceId),
|
||||
eq(roleResources.roleId, roleId)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingEntry.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"Role not found in resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(roleResources)
|
||||
.where(
|
||||
and(
|
||||
eq(roleResources.resourceId, resourceId),
|
||||
eq(roleResources.roleId, roleId)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(roleResources)
|
||||
.where(
|
||||
and(
|
||||
eq(roleResources.resourceId, resourceId),
|
||||
eq(roleResources.roleId, roleId)
|
||||
)
|
||||
);
|
||||
|
||||
return response(res, {
|
||||
data: {},
|
||||
success: true,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, resources } from "@server/db";
|
||||
import { userResources } from "@server/db";
|
||||
import { userResources, userPolicies } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -40,7 +40,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function removeUserFromResource(
|
||||
@@ -88,35 +103,71 @@ export async function removeUserFromResource(
|
||||
);
|
||||
}
|
||||
|
||||
// Check if user exists in resource
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(userResources)
|
||||
.where(
|
||||
and(
|
||||
eq(userResources.resourceId, resourceId),
|
||||
eq(userResources.userId, userId)
|
||||
)
|
||||
);
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
if (existingEntry.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"User not found in resource"
|
||||
)
|
||||
);
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(userPolicies)
|
||||
.where(
|
||||
and(
|
||||
eq(userPolicies.resourcePolicyId, policyId),
|
||||
eq(userPolicies.userId, userId)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingEntry.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"User not found in resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(userPolicies)
|
||||
.where(
|
||||
and(
|
||||
eq(userPolicies.resourcePolicyId, policyId),
|
||||
eq(userPolicies.userId, userId)
|
||||
)
|
||||
);
|
||||
} else {
|
||||
// Check if user exists in resource
|
||||
const existingEntry = await db
|
||||
.select()
|
||||
.from(userResources)
|
||||
.where(
|
||||
and(
|
||||
eq(userResources.resourceId, resourceId),
|
||||
eq(userResources.userId, userId)
|
||||
)
|
||||
);
|
||||
|
||||
if (existingEntry.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"User not found in resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(userResources)
|
||||
.where(
|
||||
and(
|
||||
eq(userResources.resourceId, resourceId),
|
||||
eq(userResources.userId, userId)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
await db
|
||||
.delete(userResources)
|
||||
.where(
|
||||
and(
|
||||
eq(userResources.resourceId, resourceId),
|
||||
eq(userResources.userId, userId)
|
||||
)
|
||||
);
|
||||
|
||||
return response(res, {
|
||||
data: {},
|
||||
success: true,
|
||||
|
||||
@@ -3,7 +3,9 @@ import { z } from "zod";
|
||||
import {
|
||||
db,
|
||||
resourceHeaderAuth,
|
||||
resourceHeaderAuthExtendedCompatibility
|
||||
resourceHeaderAuthExtendedCompatibility,
|
||||
resourcePolicyHeaderAuth,
|
||||
resources
|
||||
} from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
@@ -15,7 +17,7 @@ import { hashPassword } from "@server/auth/password";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const setResourceAuthMethodsParamsSchema = z.object({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
const setResourceAuthMethodsBodySchema = z.strictObject({
|
||||
@@ -40,7 +42,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function setResourceHeaderAuth(
|
||||
@@ -74,36 +91,72 @@ export async function setResourceHeaderAuth(
|
||||
const { resourceId } = parsedParams.data;
|
||||
const { user, password, extendedCompatibility } = parsedBody.data;
|
||||
|
||||
const [resource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
|
||||
);
|
||||
}
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
const headerAuthHash =
|
||||
user && password && extendedCompatibility !== null
|
||||
? await hashPassword(
|
||||
Buffer.from(`${user}:${password}`).toString("base64")
|
||||
)
|
||||
: null;
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
await trx
|
||||
.delete(resourceHeaderAuth)
|
||||
.where(eq(resourceHeaderAuth.resourceId, resourceId));
|
||||
await trx
|
||||
.delete(resourceHeaderAuthExtendedCompatibility)
|
||||
.where(
|
||||
eq(
|
||||
resourceHeaderAuthExtendedCompatibility.resourceId,
|
||||
resourceId
|
||||
)
|
||||
);
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
await trx
|
||||
.delete(resourcePolicyHeaderAuth)
|
||||
.where(
|
||||
eq(resourcePolicyHeaderAuth.resourcePolicyId, policyId)
|
||||
);
|
||||
|
||||
if (user && password && extendedCompatibility !== null) {
|
||||
const headerAuthHash = await hashPassword(
|
||||
Buffer.from(`${user}:${password}`).toString("base64")
|
||||
);
|
||||
if (headerAuthHash !== null && extendedCompatibility !== null) {
|
||||
await trx.insert(resourcePolicyHeaderAuth).values({
|
||||
resourcePolicyId: policyId,
|
||||
headerAuthHash,
|
||||
extendedCompatibility: extendedCompatibility!
|
||||
});
|
||||
}
|
||||
} else {
|
||||
await trx
|
||||
.delete(resourceHeaderAuth)
|
||||
.where(eq(resourceHeaderAuth.resourceId, resourceId));
|
||||
await trx
|
||||
.delete(resourceHeaderAuthExtendedCompatibility)
|
||||
.where(
|
||||
eq(
|
||||
resourceHeaderAuthExtendedCompatibility.resourceId,
|
||||
resourceId
|
||||
)
|
||||
);
|
||||
|
||||
await Promise.all([
|
||||
trx
|
||||
.insert(resourceHeaderAuth)
|
||||
.values({ resourceId, headerAuthHash }),
|
||||
trx
|
||||
.insert(resourceHeaderAuthExtendedCompatibility)
|
||||
.values({
|
||||
resourceId,
|
||||
extendedCompatibilityIsActivated:
|
||||
extendedCompatibility
|
||||
})
|
||||
]);
|
||||
if (headerAuthHash !== null && extendedCompatibility !== null) {
|
||||
await Promise.all([
|
||||
trx
|
||||
.insert(resourceHeaderAuth)
|
||||
.values({ resourceId, headerAuthHash }),
|
||||
trx
|
||||
.insert(resourceHeaderAuthExtendedCompatibility)
|
||||
.values({
|
||||
resourceId,
|
||||
extendedCompatibilityIsActivated:
|
||||
extendedCompatibility
|
||||
})
|
||||
]);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { resourcePassword } from "@server/db";
|
||||
import {
|
||||
resourcePassword,
|
||||
resourcePolicyPassword,
|
||||
resources
|
||||
} from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -13,7 +17,7 @@ import { hashPassword } from "@server/auth/password";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const setResourceAuthMethodsParamsSchema = z.object({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
const setResourceAuthMethodsBodySchema = z.strictObject({
|
||||
@@ -36,7 +40,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function setResourcePassword(
|
||||
@@ -70,17 +89,49 @@ export async function setResourcePassword(
|
||||
const { resourceId } = parsedParams.data;
|
||||
const { password } = parsedBody.data;
|
||||
|
||||
const [resource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
|
||||
);
|
||||
}
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
await trx
|
||||
.delete(resourcePassword)
|
||||
.where(eq(resourcePassword.resourceId, resourceId));
|
||||
|
||||
if (password) {
|
||||
const passwordHash = await hashPassword(password);
|
||||
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
await trx
|
||||
.insert(resourcePassword)
|
||||
.values({ resourceId, passwordHash });
|
||||
.delete(resourcePolicyPassword)
|
||||
.where(
|
||||
eq(resourcePolicyPassword.resourcePolicyId, policyId)
|
||||
);
|
||||
|
||||
if (password) {
|
||||
const passwordHash = await hashPassword(password);
|
||||
await trx
|
||||
.insert(resourcePolicyPassword)
|
||||
.values({ resourcePolicyId: policyId, passwordHash });
|
||||
}
|
||||
} else {
|
||||
await trx
|
||||
.delete(resourcePassword)
|
||||
.where(eq(resourcePassword.resourceId, resourceId));
|
||||
|
||||
if (password) {
|
||||
const passwordHash = await hashPassword(password);
|
||||
|
||||
await trx
|
||||
.insert(resourcePassword)
|
||||
.values({ resourceId, passwordHash });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { resourcePincode } from "@server/db";
|
||||
import { resourcePincode, resourcePolicyPincode, resources } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -14,7 +14,7 @@ import { hashPassword } from "@server/auth/password";
|
||||
import { OpenAPITags, registry } from "@server/openApi";
|
||||
|
||||
const setResourceAuthMethodsParamsSchema = z.object({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
const setResourceAuthMethodsBodySchema = z.strictObject({
|
||||
@@ -40,7 +40,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function setResourcePincode(
|
||||
@@ -74,17 +89,51 @@ export async function setResourcePincode(
|
||||
const { resourceId } = parsedParams.data;
|
||||
const { pincode } = parsedBody.data;
|
||||
|
||||
const [resource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
|
||||
);
|
||||
}
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
await trx
|
||||
.delete(resourcePincode)
|
||||
.where(eq(resourcePincode.resourceId, resourceId));
|
||||
|
||||
if (pincode) {
|
||||
const pincodeHash = await hashPassword(pincode);
|
||||
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
await trx
|
||||
.insert(resourcePincode)
|
||||
.values({ resourceId, pincodeHash, digitLength: 6 });
|
||||
.delete(resourcePolicyPincode)
|
||||
.where(
|
||||
eq(resourcePolicyPincode.resourcePolicyId, policyId)
|
||||
);
|
||||
|
||||
if (pincode) {
|
||||
const pincodeHash = await hashPassword(pincode);
|
||||
await trx.insert(resourcePolicyPincode).values({
|
||||
resourcePolicyId: policyId,
|
||||
pincodeHash,
|
||||
digitLength: 6
|
||||
});
|
||||
}
|
||||
} else {
|
||||
await trx
|
||||
.delete(resourcePincode)
|
||||
.where(eq(resourcePincode.resourceId, resourceId));
|
||||
|
||||
if (pincode) {
|
||||
const pincodeHash = await hashPassword(pincode);
|
||||
|
||||
await trx
|
||||
.insert(resourcePincode)
|
||||
.values({ resourceId, pincodeHash, digitLength: 6 });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, resources } from "@server/db";
|
||||
import { apiKeys, roleResources, roles } from "@server/db";
|
||||
import { apiKeys, roleResources, roles, rolePolicies } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -15,14 +15,14 @@ const setResourceRolesBodySchema = z.strictObject({
|
||||
});
|
||||
|
||||
const setResourceRolesParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/resource/{resourceId}/roles",
|
||||
description:
|
||||
"Set roles for a resource. This will replace all existing roles.",
|
||||
"Set roles for a resource. This will replace all existing roles. When the resource has an inline policy defined (no shared resource policy assigned), roles are set on the inline policy instead of directly on the resource.",
|
||||
tags: [OpenAPITags.PublicResource, OpenAPITags.Role],
|
||||
request: {
|
||||
params: setResourceRolesParamsSchema,
|
||||
@@ -34,7 +34,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function setResourceRoles(
|
||||
@@ -114,28 +129,61 @@ export async function setResourceRoles(
|
||||
);
|
||||
const adminRoleIds = adminRoles.map((role) => role.roleId);
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
if (adminRoleIds.length > 0) {
|
||||
await trx.delete(roleResources).where(
|
||||
and(
|
||||
eq(roleResources.resourceId, resourceId),
|
||||
ne(roleResources.roleId, adminRoleIds[0]) // delete all but the admin role
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
|
||||
// For inline policy, preserve admin roles by only deleting non-admin entries
|
||||
if (adminRoleIds.length > 0) {
|
||||
await trx
|
||||
.delete(rolePolicies)
|
||||
.where(
|
||||
and(
|
||||
eq(rolePolicies.resourcePolicyId, policyId),
|
||||
ne(rolePolicies.roleId, adminRoleIds[0])
|
||||
)
|
||||
);
|
||||
} else {
|
||||
await trx
|
||||
.delete(rolePolicies)
|
||||
.where(eq(rolePolicies.resourcePolicyId, policyId));
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
roleIds.map((roleId) =>
|
||||
trx
|
||||
.insert(rolePolicies)
|
||||
.values({ roleId, resourcePolicyId: policyId })
|
||||
.returning()
|
||||
)
|
||||
);
|
||||
} else {
|
||||
await trx
|
||||
.delete(roleResources)
|
||||
.where(eq(roleResources.resourceId, resourceId));
|
||||
}
|
||||
if (adminRoleIds.length > 0) {
|
||||
await trx.delete(roleResources).where(
|
||||
and(
|
||||
eq(roleResources.resourceId, resourceId),
|
||||
ne(roleResources.roleId, adminRoleIds[0]) // delete all but the admin role
|
||||
)
|
||||
);
|
||||
} else {
|
||||
await trx
|
||||
.delete(roleResources)
|
||||
.where(eq(roleResources.resourceId, resourceId));
|
||||
}
|
||||
|
||||
const newRoleResources = await Promise.all(
|
||||
roleIds.map((roleId) =>
|
||||
trx
|
||||
.insert(roleResources)
|
||||
.values({ roleId, resourceId })
|
||||
.returning()
|
||||
)
|
||||
);
|
||||
await Promise.all(
|
||||
roleIds.map((roleId) =>
|
||||
trx
|
||||
.insert(roleResources)
|
||||
.values({ roleId, resourceId })
|
||||
.returning()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: {},
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { userResources } from "@server/db";
|
||||
import { userResources, userPolicies, resources } from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -15,14 +15,14 @@ const setUserResourcesBodySchema = z.strictObject({
|
||||
});
|
||||
|
||||
const setUserResourcesParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/resource/{resourceId}/users",
|
||||
description:
|
||||
"Set users for a resource. This will replace all existing users.",
|
||||
"Set users for a resource. This will replace all existing users. When the resource has an inline policy defined (no shared resource policy assigned), users are set on the inline policy instead of directly on the resource.",
|
||||
tags: [OpenAPITags.PublicResource, OpenAPITags.User],
|
||||
request: {
|
||||
params: setUserResourcesParamsSchema,
|
||||
@@ -34,7 +34,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function setResourceUsers(
|
||||
@@ -67,19 +82,51 @@ export async function setResourceUsers(
|
||||
|
||||
const { resourceId } = parsedParams.data;
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
await trx
|
||||
.delete(userResources)
|
||||
.where(eq(userResources.resourceId, resourceId));
|
||||
const [resource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(eq(resources.resourceId, resourceId))
|
||||
.limit(1);
|
||||
|
||||
const newUserResources = await Promise.all(
|
||||
userIds.map((userId) =>
|
||||
trx
|
||||
.insert(userResources)
|
||||
.values({ userId, resourceId })
|
||||
.returning()
|
||||
)
|
||||
if (!resource) {
|
||||
return next(
|
||||
createHttpError(HttpCode.NOT_FOUND, "Resource not found")
|
||||
);
|
||||
}
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
await trx
|
||||
.delete(userPolicies)
|
||||
.where(eq(userPolicies.resourcePolicyId, policyId));
|
||||
|
||||
await Promise.all(
|
||||
userIds.map((userId) =>
|
||||
trx
|
||||
.insert(userPolicies)
|
||||
.values({ userId, resourcePolicyId: policyId })
|
||||
.returning()
|
||||
)
|
||||
);
|
||||
} else {
|
||||
await trx
|
||||
.delete(userResources)
|
||||
.where(eq(userResources.resourceId, resourceId));
|
||||
|
||||
await Promise.all(
|
||||
userIds.map((userId) =>
|
||||
trx
|
||||
.insert(userResources)
|
||||
.values({ userId, resourceId })
|
||||
.returning()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: {},
|
||||
|
||||
@@ -1,7 +1,12 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { resources, resourceWhitelist } from "@server/db";
|
||||
import {
|
||||
resources,
|
||||
resourceWhitelist,
|
||||
resourcePolicies,
|
||||
resourcePolicyWhiteList
|
||||
} from "@server/db";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -24,7 +29,7 @@ const setResourceWhitelistBodySchema = z.strictObject({
|
||||
});
|
||||
|
||||
const setResourceWhitelistParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
registry.registerPath({
|
||||
@@ -43,7 +48,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function setResourceWhitelist(
|
||||
@@ -89,57 +109,135 @@ export async function setResourceWhitelist(
|
||||
);
|
||||
}
|
||||
|
||||
if (!resource.emailWhitelistEnabled) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Email whitelist is not enabled for this resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
const whitelist = await db
|
||||
.select()
|
||||
.from(resourceWhitelist)
|
||||
.where(eq(resourceWhitelist.resourceId, resourceId));
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
// diff the emails
|
||||
const existingEmails = whitelist.map((w) => w.email);
|
||||
const [policy] = await db
|
||||
.select()
|
||||
.from(resourcePolicies)
|
||||
.where(eq(resourcePolicies.resourcePolicyId, policyId));
|
||||
|
||||
const emailsToAdd = emails.filter(
|
||||
(e) => !existingEmails.includes(e)
|
||||
);
|
||||
const emailsToRemove = existingEmails.filter(
|
||||
(e) => !emails.includes(e)
|
||||
);
|
||||
if (!policy) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"Resource policy not found"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
for (const email of emailsToAdd) {
|
||||
await trx.insert(resourceWhitelist).values({
|
||||
email,
|
||||
resourceId
|
||||
if (!policy.emailWhitelistEnabled) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Email whitelist is not enabled for this resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const existingPolicyWhitelist = await db
|
||||
.select()
|
||||
.from(resourcePolicyWhiteList)
|
||||
.where(eq(resourcePolicyWhiteList.resourcePolicyId, policyId));
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
const existingEmails = existingPolicyWhitelist.map(
|
||||
(w) => w.email
|
||||
);
|
||||
|
||||
const emailsToAdd = emails.filter(
|
||||
(e) => !existingEmails.includes(e)
|
||||
);
|
||||
const emailsToRemove = existingEmails.filter(
|
||||
(e) => !emails.includes(e)
|
||||
);
|
||||
|
||||
for (const email of emailsToAdd) {
|
||||
await trx.insert(resourcePolicyWhiteList).values({
|
||||
email,
|
||||
resourcePolicyId: policyId
|
||||
});
|
||||
}
|
||||
|
||||
for (const email of emailsToRemove) {
|
||||
await trx
|
||||
.delete(resourcePolicyWhiteList)
|
||||
.where(
|
||||
and(
|
||||
eq(
|
||||
resourcePolicyWhiteList.resourcePolicyId,
|
||||
policyId
|
||||
),
|
||||
eq(resourcePolicyWhiteList.email, email)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: {},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Whitelist set for resource successfully",
|
||||
status: HttpCode.CREATED
|
||||
});
|
||||
}
|
||||
|
||||
for (const email of emailsToRemove) {
|
||||
await trx
|
||||
.delete(resourceWhitelist)
|
||||
.where(
|
||||
and(
|
||||
eq(resourceWhitelist.resourceId, resourceId),
|
||||
eq(resourceWhitelist.email, email)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: {},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Whitelist set for resource successfully",
|
||||
status: HttpCode.CREATED
|
||||
});
|
||||
});
|
||||
} else {
|
||||
if (!resource.emailWhitelistEnabled) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Email whitelist is not enabled for this resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const whitelist = await db
|
||||
.select()
|
||||
.from(resourceWhitelist)
|
||||
.where(eq(resourceWhitelist.resourceId, resourceId));
|
||||
|
||||
await db.transaction(async (trx) => {
|
||||
// diff the emails
|
||||
const existingEmails = whitelist.map((w) => w.email);
|
||||
|
||||
const emailsToAdd = emails.filter(
|
||||
(e) => !existingEmails.includes(e)
|
||||
);
|
||||
const emailsToRemove = existingEmails.filter(
|
||||
(e) => !emails.includes(e)
|
||||
);
|
||||
|
||||
for (const email of emailsToAdd) {
|
||||
await trx.insert(resourceWhitelist).values({
|
||||
email,
|
||||
resourceId
|
||||
});
|
||||
}
|
||||
|
||||
for (const email of emailsToRemove) {
|
||||
await trx
|
||||
.delete(resourceWhitelist)
|
||||
.where(
|
||||
and(
|
||||
eq(resourceWhitelist.resourceId, resourceId),
|
||||
eq(resourceWhitelist.email, email)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: {},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Whitelist set for resource successfully",
|
||||
status: HttpCode.CREATED
|
||||
});
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import type { Resource, ResourcePolicy } from "@server/db";
|
||||
import type { PaginatedResponse } from "@server/types/Pagination";
|
||||
|
||||
export type GetMaintenanceInfoResponse = {
|
||||
resourceId: number;
|
||||
name: string;
|
||||
@@ -8,3 +11,19 @@ export type GetMaintenanceInfoResponse = {
|
||||
maintenanceMessage: string | null;
|
||||
maintenanceEstimatedTime: string | null;
|
||||
};
|
||||
|
||||
export type AttachedResource = Pick<
|
||||
Resource,
|
||||
"resourceId" | "niceId" | "name" | "fullDomain"
|
||||
>;
|
||||
|
||||
export type ResourcePolicyWithResources = Pick<
|
||||
ResourcePolicy,
|
||||
"resourcePolicyId" | "niceId" | "name" | "orgId"
|
||||
> & {
|
||||
resources: Array<AttachedResource>;
|
||||
};
|
||||
|
||||
export type ListResourcePoliciesResponse = PaginatedResponse<{
|
||||
policies: Array<ResourcePolicyWithResources>;
|
||||
}>;
|
||||
|
||||
@@ -1,12 +1,27 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db, domainNamespaces, loginPage } from "@server/db";
|
||||
import {
|
||||
db,
|
||||
domainNamespaces,
|
||||
loginPage,
|
||||
resourceHeaderAuth,
|
||||
resourceHeaderAuthExtendedCompatibility,
|
||||
resourcePassword,
|
||||
resourcePincode,
|
||||
resourceRules,
|
||||
resourceWhitelist,
|
||||
roleResources,
|
||||
roles,
|
||||
Transaction,
|
||||
userResources
|
||||
} from "@server/db";
|
||||
import {
|
||||
domains,
|
||||
Org,
|
||||
orgDomains,
|
||||
orgs,
|
||||
Resource,
|
||||
resourcePolicies,
|
||||
resources
|
||||
} from "@server/db";
|
||||
import { eq, and, ne } from "drizzle-orm";
|
||||
@@ -32,9 +47,10 @@ import { build } from "@server/build";
|
||||
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
|
||||
import { tierMatrix } from "@server/lib/billing/tierMatrix";
|
||||
import { isSubscribed } from "#dynamic/lib/isSubscribed";
|
||||
import { applyInlinePolicyFields } from "./inlinePolicyFields";
|
||||
|
||||
const updateResourceParamsSchema = z.strictObject({
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
const updateHttpResourceBodySchema = z
|
||||
@@ -51,16 +67,38 @@ const updateHttpResourceBodySchema = z
|
||||
.optional(),
|
||||
subdomain: z.string().nullable().optional(),
|
||||
ssl: z.boolean().optional(),
|
||||
sso: z.boolean().optional(),
|
||||
sso: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"When no shared resource policy is assigned (resourcePolicyId is null), updates the resource's inline policy. When a shared policy is assigned, this value overrides the shared policy for this resource."
|
||||
),
|
||||
blockAccess: z.boolean().optional(),
|
||||
emailWhitelistEnabled: z.boolean().optional(),
|
||||
applyRules: z.boolean().optional(),
|
||||
emailWhitelistEnabled: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"When no shared resource policy is assigned (resourcePolicyId is null), updates the resource's inline policy. When a shared policy is assigned, this value overrides the shared policy for this resource."
|
||||
),
|
||||
applyRules: z
|
||||
.boolean()
|
||||
.optional()
|
||||
.describe(
|
||||
"When no shared resource policy is assigned (resourcePolicyId is null), updates the resource's inline policy. When a shared policy is assigned, this value overrides the shared policy for this resource."
|
||||
),
|
||||
domainId: z.string().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
stickySession: z.boolean().optional(),
|
||||
tlsServerName: z.string().nullable().optional(),
|
||||
setHostHeader: z.string().nullable().optional(),
|
||||
skipToIdpId: z.int().positive().nullable().optional(),
|
||||
skipToIdpId: z
|
||||
.int()
|
||||
.positive()
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"When no shared resource policy is assigned (resourcePolicyId is null), updates the resource's inline policy. When a shared policy is assigned, this value overrides the shared policy for this resource."
|
||||
),
|
||||
headers: z
|
||||
.array(z.strictObject({ name: z.string(), value: z.string() }))
|
||||
.nullable()
|
||||
@@ -79,7 +117,18 @@ const updateHttpResourceBodySchema = z
|
||||
maintenanceTitle: z.string().max(255).nullable().optional(),
|
||||
maintenanceMessage: z.string().max(2000).nullable().optional(),
|
||||
maintenanceEstimatedTime: z.string().max(100).nullable().optional(),
|
||||
postAuthPath: z.string().nullable().optional()
|
||||
postAuthPath: z.string().nullable().optional(),
|
||||
// SSH settings
|
||||
pamMode: z.enum(["passthrough", "push"]).optional(),
|
||||
authDaemonMode: z.enum(["site", "remote", "native"]).optional(),
|
||||
authDaemonPort: z.int().min(1).max(65535).nullable().optional(),
|
||||
resourcePolicyId: z
|
||||
.number()
|
||||
.nullable()
|
||||
.optional()
|
||||
.describe(
|
||||
"ID of the resource policy to apply to this resource. Set to null to remove the resource policy and fall back to the inline policy settings."
|
||||
)
|
||||
})
|
||||
.refine((data) => Object.keys(data).length > 0, {
|
||||
error: "At least one field must be provided for update"
|
||||
@@ -177,7 +226,8 @@ const updateRawResourceBodySchema = z
|
||||
stickySession: z.boolean().optional(),
|
||||
enabled: z.boolean().optional(),
|
||||
proxyProtocol: z.boolean().optional(),
|
||||
proxyProtocolVersion: z.int().min(1).optional()
|
||||
proxyProtocolVersion: z.int().min(1).optional(),
|
||||
resourcePolicyId: z.number().nullable().optional()
|
||||
})
|
||||
.refine((data) => Object.keys(data).length > 0, {
|
||||
error: "At least one field must be provided for update"
|
||||
@@ -199,7 +249,8 @@ const updateRawResourceBodySchema = z
|
||||
registry.registerPath({
|
||||
method: "post",
|
||||
path: "/resource/{resourceId}",
|
||||
description: "Update a resource.",
|
||||
description:
|
||||
"Update a resource. Policy fields (sso, mfa, pincode, password, whitelist) update the inline policy when no shared resource policy is assigned; when a shared policy is assigned those fields override the shared policy for this resource only.",
|
||||
tags: [OpenAPITags.PublicResource],
|
||||
request: {
|
||||
params: updateResourceParamsSchema,
|
||||
@@ -213,7 +264,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function updateResource(
|
||||
@@ -252,7 +318,7 @@ export async function updateResource(
|
||||
);
|
||||
}
|
||||
|
||||
if (resource.http) {
|
||||
if (["http", "ssh", "rdp", "vnc"].includes(resource.mode)) {
|
||||
// HANDLE UPDATING HTTP RESOURCES
|
||||
return await updateHttpResource(
|
||||
{
|
||||
@@ -287,6 +353,61 @@ export async function updateResource(
|
||||
}
|
||||
}
|
||||
|
||||
async function clearResourceSpecificSettings(
|
||||
resourceId: number,
|
||||
orgId: string,
|
||||
trx: Transaction | typeof db
|
||||
) {
|
||||
const adminRole = await db
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.isAdmin, true), eq(roles.orgId, orgId)))
|
||||
.limit(1);
|
||||
|
||||
if (adminRole.length === 0) {
|
||||
throw new Error(`Admin role not found for org ${orgId}`);
|
||||
}
|
||||
// remove the resource specific pincode, password, header auth, rules, nad whitelist entries so that the resource will fall back to the policy settings
|
||||
await Promise.all([
|
||||
trx
|
||||
.delete(resourcePassword)
|
||||
.where(eq(resourcePassword.resourceId, resourceId)),
|
||||
trx
|
||||
.delete(resourcePincode)
|
||||
.where(eq(resourcePincode.resourceId, resourceId)),
|
||||
trx
|
||||
.delete(resourceHeaderAuth)
|
||||
.where(eq(resourceHeaderAuth.resourceId, resourceId)),
|
||||
trx
|
||||
.delete(resourceHeaderAuthExtendedCompatibility)
|
||||
.where(
|
||||
eq(
|
||||
resourceHeaderAuthExtendedCompatibility.resourceId,
|
||||
resourceId
|
||||
)
|
||||
),
|
||||
trx
|
||||
.delete(resourceWhitelist)
|
||||
.where(eq(resourceWhitelist.resourceId, resourceId)),
|
||||
trx
|
||||
.delete(resourceRules)
|
||||
.where(eq(resourceRules.resourceId, resourceId)),
|
||||
// delete the roles and the users as well
|
||||
trx
|
||||
.delete(userResources)
|
||||
.where(eq(userResources.resourceId, resourceId)),
|
||||
// except the admin role
|
||||
trx
|
||||
.delete(roleResources)
|
||||
.where(
|
||||
and(
|
||||
eq(roleResources.resourceId, resourceId),
|
||||
ne(roleResources.roleId, adminRole[0].roleId)
|
||||
)
|
||||
)
|
||||
]);
|
||||
}
|
||||
|
||||
async function updateHttpResource(
|
||||
route: {
|
||||
req: Request;
|
||||
@@ -313,6 +434,51 @@ async function updateHttpResource(
|
||||
|
||||
const updateData = parsedBody.data;
|
||||
|
||||
const isLicensed = await isLicensedOrSubscribed(
|
||||
resource.orgId,
|
||||
tierMatrix.wildcardSubdomain
|
||||
);
|
||||
|
||||
if (updateData.resourcePolicyId != null) {
|
||||
if (!isLicensed) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"Resource policies are not supported on your current plan. Please upgrade to access this feature."
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const [existingPolicy] = await db
|
||||
.select()
|
||||
.from(resourcePolicies)
|
||||
.where(
|
||||
eq(
|
||||
resourcePolicies.resourcePolicyId,
|
||||
updateData.resourcePolicyId
|
||||
)
|
||||
)
|
||||
.limit(1);
|
||||
|
||||
if (!existingPolicy) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Resource policy with ID ${updateData.resourcePolicyId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// catch when the resource policy changes or gets cleared
|
||||
if (resource.resourcePolicyId != updateData.resourcePolicyId) {
|
||||
await clearResourceSpecificSettings(
|
||||
resource.resourceId,
|
||||
resource.orgId,
|
||||
db
|
||||
);
|
||||
}
|
||||
|
||||
if (updateData.niceId) {
|
||||
const [existingResource] = await db
|
||||
.select()
|
||||
@@ -338,10 +504,6 @@ async function updateHttpResource(
|
||||
|
||||
// Wildcard subdomains are a paid feature
|
||||
if (updateData.subdomain && updateData.subdomain.includes("*")) {
|
||||
const isLicensed = await isLicensedOrSubscribed(
|
||||
resource.orgId,
|
||||
tierMatrix.wildcardSubdomain
|
||||
);
|
||||
if (!isLicensed) {
|
||||
return next(
|
||||
createHttpError(
|
||||
@@ -501,10 +663,6 @@ async function updateHttpResource(
|
||||
responseHeaders = null;
|
||||
}
|
||||
|
||||
const isLicensed = await isLicensedOrSubscribed(
|
||||
resource.orgId,
|
||||
tierMatrix.maintencePage
|
||||
);
|
||||
if (!isLicensed) {
|
||||
updateData.maintenanceModeEnabled = undefined;
|
||||
updateData.maintenanceModeType = undefined;
|
||||
@@ -513,6 +671,72 @@ async function updateHttpResource(
|
||||
updateData.maintenanceEstimatedTime = undefined;
|
||||
}
|
||||
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
const {
|
||||
sso,
|
||||
emailWhitelistEnabled,
|
||||
applyRules,
|
||||
skipToIdpId,
|
||||
...resourceOnlyDataRest
|
||||
} = updateData;
|
||||
|
||||
const resourceOnlyData = {
|
||||
...resourceOnlyDataRest,
|
||||
sso: null, // reset these because they are controlled by the inline policy
|
||||
emailWhitelistEnabled: null,
|
||||
applyRules: null,
|
||||
skipToIdpId: null
|
||||
};
|
||||
|
||||
const policyUpdate: Record<string, unknown> = {};
|
||||
if (sso !== undefined) policyUpdate.sso = sso;
|
||||
if (emailWhitelistEnabled !== undefined)
|
||||
policyUpdate.emailWhitelistEnabled = emailWhitelistEnabled;
|
||||
if (applyRules !== undefined) policyUpdate.applyRules = applyRules;
|
||||
if (skipToIdpId !== undefined) policyUpdate.idpId = skipToIdpId;
|
||||
|
||||
if (Object.keys(policyUpdate).length > 0) {
|
||||
await db
|
||||
.update(resourcePolicies)
|
||||
.set(policyUpdate)
|
||||
.where(eq(resourcePolicies.resourcePolicyId, policyId));
|
||||
}
|
||||
|
||||
const [inlinePolicy] = await db
|
||||
.select()
|
||||
.from(resourcePolicies)
|
||||
.where(eq(resourcePolicies.resourcePolicyId, policyId))
|
||||
.limit(1);
|
||||
|
||||
const updatedResource = await db
|
||||
.update(resources)
|
||||
.set({ ...resourceOnlyData, headers })
|
||||
.where(eq(resources.resourceId, resource.resourceId))
|
||||
.returning();
|
||||
|
||||
if (updatedResource.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Resource with ID ${resource.resourceId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: applyInlinePolicyFields(updatedResource[0], inlinePolicy),
|
||||
success: true,
|
||||
error: false,
|
||||
message: "HTTP resource updated successfully",
|
||||
status: HttpCode.OK
|
||||
});
|
||||
}
|
||||
|
||||
const updatedResource = await db
|
||||
.update(resources)
|
||||
.set({ ...updateData, requestHeaders, responseHeaders })
|
||||
@@ -562,38 +786,62 @@ async function updateRawResource(
|
||||
}
|
||||
|
||||
const updateData = parsedBody.data;
|
||||
let updatedResource: Resource | null = null;
|
||||
|
||||
if (updateData.niceId) {
|
||||
const [existingResource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(
|
||||
and(
|
||||
eq(resources.niceId, updateData.niceId),
|
||||
eq(resources.orgId, resource.orgId)
|
||||
)
|
||||
);
|
||||
|
||||
if (
|
||||
existingResource &&
|
||||
existingResource.resourceId !== resource.resourceId
|
||||
) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.CONFLICT,
|
||||
`A resource with niceId "${updateData.niceId}" already exists`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const updatedResource = await db
|
||||
.update(resources)
|
||||
.set(updateData)
|
||||
const [existingResource] = await db
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(eq(resources.resourceId, resource.resourceId))
|
||||
.returning();
|
||||
.limit(1);
|
||||
|
||||
if (updatedResource.length === 0) {
|
||||
await db.transaction(async (trx) => {
|
||||
if (updateData.niceId) {
|
||||
const [existingResourceConflict] = await trx
|
||||
.select()
|
||||
.from(resources)
|
||||
.where(
|
||||
and(
|
||||
eq(resources.niceId, updateData.niceId),
|
||||
eq(resources.orgId, resource.orgId)
|
||||
)
|
||||
);
|
||||
|
||||
if (
|
||||
existingResourceConflict &&
|
||||
existingResourceConflict.resourceId !== resource.resourceId
|
||||
) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.CONFLICT,
|
||||
`A resource with niceId "${updateData.niceId}" already exists`
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
await clearResourceSpecificSettings(
|
||||
resource.resourceId,
|
||||
resource.orgId,
|
||||
trx
|
||||
); // none of these are supported on raw resources
|
||||
|
||||
// we should make sure sso, emailWhitelistEnabled, and applyRules are null because this is a raw resource
|
||||
const realUpdateData = {
|
||||
...updateData,
|
||||
sso: null,
|
||||
emailWhitelistEnabled: null,
|
||||
applyRules: null,
|
||||
skipToIdpId: null
|
||||
};
|
||||
|
||||
[updatedResource] = await trx
|
||||
.update(resources)
|
||||
.set(realUpdateData)
|
||||
.where(eq(resources.resourceId, resource.resourceId))
|
||||
.returning();
|
||||
});
|
||||
|
||||
if (!updatedResource) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
@@ -603,7 +851,7 @@ async function updateRawResource(
|
||||
}
|
||||
|
||||
return response(res, {
|
||||
data: updatedResource[0],
|
||||
data: updatedResource,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Non-http Resource updated successfully",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { resourceRules, resources } from "@server/db";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { resourcePolicyRules, resourceRules, resources } from "@server/db";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import response from "@server/lib/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
@@ -18,15 +18,24 @@ import { isValidRegionId } from "@server/db/regions";
|
||||
|
||||
// Define Zod schema for request parameters validation
|
||||
const updateResourceRuleParamsSchema = z.strictObject({
|
||||
ruleId: z.string().transform(Number).pipe(z.int().positive()),
|
||||
resourceId: z.string().transform(Number).pipe(z.int().positive())
|
||||
ruleId: z.coerce.number().int().positive(),
|
||||
resourceId: z.coerce.number().int().positive()
|
||||
});
|
||||
|
||||
const resourceRuleMatchSchema = z.enum([
|
||||
"CIDR",
|
||||
"IP",
|
||||
"PATH",
|
||||
"COUNTRY",
|
||||
"ASN",
|
||||
"REGION"
|
||||
]);
|
||||
|
||||
// Define Zod schema for request body validation
|
||||
const updateResourceRuleSchema = z
|
||||
.strictObject({
|
||||
action: z.enum(["ACCEPT", "DROP", "PASS"]).optional(),
|
||||
match: z.enum(["CIDR", "IP", "PATH", "COUNTRY", "ASN", "REGION"]).optional(),
|
||||
match: resourceRuleMatchSchema.optional(),
|
||||
value: z.string().min(1).optional(),
|
||||
priority: z.int(),
|
||||
enabled: z.boolean().optional()
|
||||
@@ -50,7 +59,22 @@ registry.registerPath({
|
||||
}
|
||||
}
|
||||
},
|
||||
responses: {}
|
||||
responses: {
|
||||
200: {
|
||||
description: "Successful response",
|
||||
content: {
|
||||
"application/json": {
|
||||
schema: z.object({
|
||||
data: z.record(z.string(), z.any()).nullable(),
|
||||
success: z.boolean(),
|
||||
error: z.boolean(),
|
||||
message: z.string(),
|
||||
status: z.number()
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
export async function updateResourceRule(
|
||||
@@ -102,41 +126,106 @@ export async function updateResourceRule(
|
||||
);
|
||||
}
|
||||
|
||||
if (!resource.http) {
|
||||
if (!["http", "ssh", "rdp", "vnc"].includes(resource.mode)) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.BAD_REQUEST,
|
||||
"Cannot create rule for non-http resource"
|
||||
"Cannot update rule for non-http resource"
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
// Verify that the rule exists and belongs to the specified resource
|
||||
const [existingRule] = await db
|
||||
.select()
|
||||
.from(resourceRules)
|
||||
.where(eq(resourceRules.ruleId, ruleId))
|
||||
.limit(1);
|
||||
const isInlinePolicy =
|
||||
resource.resourcePolicyId === null &&
|
||||
resource.defaultResourcePolicyId !== null;
|
||||
|
||||
if (!existingRule) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Resource rule with ID ${ruleId} not found`
|
||||
)
|
||||
let existingMatch:
|
||||
| "CIDR"
|
||||
| "IP"
|
||||
| "PATH"
|
||||
| "COUNTRY"
|
||||
| "ASN"
|
||||
| "REGION";
|
||||
|
||||
if (isInlinePolicy) {
|
||||
const policyId = resource.defaultResourcePolicyId!;
|
||||
const [existingRule] = await db
|
||||
.select()
|
||||
.from(resourcePolicyRules)
|
||||
.where(eq(resourcePolicyRules.ruleId, ruleId))
|
||||
.limit(1);
|
||||
|
||||
if (!existingRule) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Resource rule with ID ${ruleId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (existingRule.resourcePolicyId !== policyId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
`Resource rule ${ruleId} does not belong to resource ${resourceId}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedExistingMatch = resourceRuleMatchSchema.safeParse(
|
||||
existingRule.match
|
||||
);
|
||||
if (!parsedExistingMatch.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"Resource rule has invalid match type"
|
||||
)
|
||||
);
|
||||
}
|
||||
existingMatch = parsedExistingMatch.data;
|
||||
} else {
|
||||
// Verify that the rule exists and belongs to the specified resource
|
||||
const [existingRule] = await db
|
||||
.select()
|
||||
.from(resourceRules)
|
||||
.where(eq(resourceRules.ruleId, ruleId))
|
||||
.limit(1);
|
||||
|
||||
if (!existingRule) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
`Resource rule with ID ${ruleId} not found`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (existingRule.resourceId !== resourceId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
`Resource rule ${ruleId} does not belong to resource ${resourceId}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const parsedExistingMatch = resourceRuleMatchSchema.safeParse(
|
||||
existingRule.match
|
||||
);
|
||||
if (!parsedExistingMatch.success) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"Resource rule has invalid match type"
|
||||
)
|
||||
);
|
||||
}
|
||||
existingMatch = parsedExistingMatch.data;
|
||||
}
|
||||
|
||||
if (existingRule.resourceId !== resourceId) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
`Resource rule ${ruleId} does not belong to resource ${resourceId}`
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
const match = updateData.match || existingRule.match;
|
||||
const match = updateData.match || existingMatch;
|
||||
const { value } = updateData;
|
||||
|
||||
if (value !== undefined) {
|
||||
@@ -180,11 +269,30 @@ export async function updateResourceRule(
|
||||
}
|
||||
|
||||
// Update the rule
|
||||
const [updatedRule] = await db
|
||||
.update(resourceRules)
|
||||
.set(updateData)
|
||||
.where(eq(resourceRules.ruleId, ruleId))
|
||||
.returning();
|
||||
const [updatedRule] = isInlinePolicy
|
||||
? await db
|
||||
.update(resourcePolicyRules)
|
||||
.set(updateData)
|
||||
.where(
|
||||
and(
|
||||
eq(resourcePolicyRules.ruleId, ruleId),
|
||||
eq(
|
||||
resourcePolicyRules.resourcePolicyId,
|
||||
resource.defaultResourcePolicyId!
|
||||
)
|
||||
)
|
||||
)
|
||||
.returning()
|
||||
: await db
|
||||
.update(resourceRules)
|
||||
.set(updateData)
|
||||
.where(
|
||||
and(
|
||||
eq(resourceRules.ruleId, ruleId),
|
||||
eq(resourceRules.resourceId, resourceId)
|
||||
)
|
||||
)
|
||||
.returning();
|
||||
|
||||
return response(res, {
|
||||
data: updatedRule,
|
||||
|
||||
Reference in New Issue
Block a user