2025-02-11 23:59:13 -05:00
|
|
|
import { generateSessionToken } from "@server/auth/sessions/app";
|
|
|
|
import {
|
|
|
|
createResourceSession,
|
|
|
|
serializeResourceSessionCookie,
|
|
|
|
validateResourceSessionToken
|
|
|
|
} from "@server/auth/sessions/resource";
|
|
|
|
import { verifyResourceAccessToken } from "@server/auth/verifyResourceAccessToken";
|
2024-11-16 22:41:43 -05:00
|
|
|
import db from "@server/db";
|
|
|
|
import {
|
2025-02-11 23:59:13 -05:00
|
|
|
Resource,
|
2025-01-11 19:47:07 -05:00
|
|
|
ResourceAccessToken,
|
2025-01-26 14:42:02 -05:00
|
|
|
ResourcePassword,
|
2024-11-16 22:41:43 -05:00
|
|
|
resourcePassword,
|
2025-01-26 14:42:02 -05:00
|
|
|
ResourcePincode,
|
2024-11-16 22:41:43 -05:00
|
|
|
resourcePincode,
|
2025-02-11 23:59:13 -05:00
|
|
|
ResourceRule,
|
|
|
|
resourceRules,
|
2024-11-16 22:41:43 -05:00
|
|
|
resources,
|
2025-02-11 23:59:13 -05:00
|
|
|
roleResources,
|
2025-01-26 14:42:02 -05:00
|
|
|
sessions,
|
|
|
|
userOrgs,
|
2025-02-11 23:59:13 -05:00
|
|
|
userResources,
|
|
|
|
users
|
2024-11-16 22:41:43 -05:00
|
|
|
} from "@server/db/schema";
|
2025-01-01 21:41:31 -05:00
|
|
|
import config from "@server/lib/config";
|
2025-02-11 23:59:13 -05:00
|
|
|
import { isIpInCidr } from "@server/lib/ip";
|
|
|
|
import { response } from "@server/lib/response";
|
2024-11-23 17:56:21 -05:00
|
|
|
import logger from "@server/logger";
|
2025-02-11 23:59:13 -05:00
|
|
|
import HttpCode from "@server/types/HttpCode";
|
|
|
|
import { and, eq } from "drizzle-orm";
|
|
|
|
import { NextFunction, Request, Response } from "express";
|
|
|
|
import createHttpError from "http-errors";
|
2025-01-26 14:42:02 -05:00
|
|
|
import NodeCache from "node-cache";
|
2025-02-11 23:59:13 -05:00
|
|
|
import { z } from "zod";
|
|
|
|
import { fromError } from "zod-validation-error";
|
2025-01-26 14:42:02 -05:00
|
|
|
|
|
|
|
// We'll see if this speeds anything up
|
|
|
|
const cache = new NodeCache({
|
|
|
|
stdTTL: 5 // seconds
|
|
|
|
});
|
2024-11-16 22:41:43 -05:00
|
|
|
|
|
|
|
const verifyResourceSessionSchema = z.object({
|
2024-11-27 00:07:40 -05:00
|
|
|
sessions: z.record(z.string()).optional(),
|
2024-11-16 22:41:43 -05:00
|
|
|
originalRequestURL: z.string().url(),
|
|
|
|
scheme: z.string(),
|
|
|
|
host: z.string(),
|
|
|
|
path: z.string(),
|
|
|
|
method: z.string(),
|
2025-01-11 19:47:07 -05:00
|
|
|
accessToken: z.string().optional(),
|
2025-01-27 22:43:32 -05:00
|
|
|
tls: z.boolean(),
|
|
|
|
requestIp: z.string().optional()
|
2024-11-16 22:41:43 -05:00
|
|
|
});
|
|
|
|
|
|
|
|
export type VerifyResourceSessionSchema = z.infer<
|
|
|
|
typeof verifyResourceSessionSchema
|
|
|
|
>;
|
|
|
|
|
|
|
|
export type VerifyUserResponse = {
|
|
|
|
valid: boolean;
|
|
|
|
redirectUrl?: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
export async function verifyResourceSession(
|
|
|
|
req: Request,
|
|
|
|
res: Response,
|
2024-12-15 17:47:07 -05:00
|
|
|
next: NextFunction
|
2024-11-16 22:41:43 -05:00
|
|
|
): Promise<any> {
|
2025-01-26 14:42:02 -05:00
|
|
|
logger.debug("Verify session: Badger sent", req.body); // remove when done testing
|
2024-11-23 17:56:21 -05:00
|
|
|
|
2024-11-17 22:44:11 -05:00
|
|
|
const parsedBody = verifyResourceSessionSchema.safeParse(req.body);
|
2024-11-16 22:41:43 -05:00
|
|
|
|
|
|
|
if (!parsedBody.success) {
|
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.BAD_REQUEST,
|
2024-12-15 17:47:07 -05:00
|
|
|
fromError(parsedBody.error).toString()
|
|
|
|
)
|
2024-11-16 22:41:43 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
try {
|
2025-01-26 14:42:02 -05:00
|
|
|
const {
|
|
|
|
sessions,
|
|
|
|
host,
|
|
|
|
originalRequestURL,
|
2025-01-27 22:43:32 -05:00
|
|
|
requestIp,
|
2025-02-06 21:42:18 -05:00
|
|
|
path,
|
2025-01-26 14:42:02 -05:00
|
|
|
accessToken: token
|
|
|
|
} = parsedBody.data;
|
|
|
|
|
2025-01-27 22:43:32 -05:00
|
|
|
const clientIp = requestIp?.split(":")[0];
|
|
|
|
|
2025-01-26 14:42:02 -05:00
|
|
|
const resourceCacheKey = `resource:${host}`;
|
|
|
|
let resourceData:
|
|
|
|
| {
|
|
|
|
resource: Resource | null;
|
|
|
|
pincode: ResourcePincode | null;
|
|
|
|
password: ResourcePassword | null;
|
|
|
|
}
|
|
|
|
| undefined = cache.get(resourceCacheKey);
|
|
|
|
|
|
|
|
if (!resourceData) {
|
|
|
|
const [result] = await db
|
|
|
|
.select()
|
|
|
|
.from(resources)
|
|
|
|
.leftJoin(
|
|
|
|
resourcePincode,
|
|
|
|
eq(resourcePincode.resourceId, resources.resourceId)
|
|
|
|
)
|
|
|
|
.leftJoin(
|
|
|
|
resourcePassword,
|
|
|
|
eq(resourcePassword.resourceId, resources.resourceId)
|
|
|
|
)
|
|
|
|
.where(eq(resources.fullDomain, host))
|
|
|
|
.limit(1);
|
|
|
|
|
|
|
|
if (!result) {
|
|
|
|
logger.debug("Resource not found", host);
|
|
|
|
return notAllowed(res);
|
|
|
|
}
|
2024-11-16 22:41:43 -05:00
|
|
|
|
2025-01-26 14:42:02 -05:00
|
|
|
resourceData = {
|
|
|
|
resource: result.resources,
|
|
|
|
pincode: result.resourcePincode,
|
|
|
|
password: result.resourcePassword
|
|
|
|
};
|
|
|
|
|
|
|
|
cache.set(resourceCacheKey, resourceData);
|
|
|
|
}
|
|
|
|
|
|
|
|
const { resource, pincode, password } = resourceData;
|
2024-11-16 22:41:43 -05:00
|
|
|
|
|
|
|
if (!resource) {
|
2024-11-24 14:28:23 -05:00
|
|
|
logger.debug("Resource not found", host);
|
2024-11-17 22:44:11 -05:00
|
|
|
return notAllowed(res);
|
2024-11-16 22:41:43 -05:00
|
|
|
}
|
|
|
|
|
2024-11-17 22:44:11 -05:00
|
|
|
const { sso, blockAccess } = resource;
|
|
|
|
|
|
|
|
if (blockAccess) {
|
2024-11-24 14:28:23 -05:00
|
|
|
logger.debug("Resource blocked", host);
|
2024-11-17 22:44:11 -05:00
|
|
|
return notAllowed(res);
|
|
|
|
}
|
|
|
|
|
2024-12-18 23:14:26 -05:00
|
|
|
if (
|
|
|
|
!resource.sso &&
|
|
|
|
!pincode &&
|
|
|
|
!password &&
|
|
|
|
!resource.emailWhitelistEnabled
|
|
|
|
) {
|
2024-11-24 14:28:23 -05:00
|
|
|
logger.debug("Resource allowed because no auth");
|
2024-11-16 22:41:43 -05:00
|
|
|
return allowed(res);
|
|
|
|
}
|
|
|
|
|
2025-02-06 21:42:18 -05:00
|
|
|
// check the rules
|
2025-02-09 10:50:43 -05:00
|
|
|
if (resource.applyRules) {
|
|
|
|
const action = await checkRules(
|
|
|
|
resource.resourceId,
|
|
|
|
clientIp,
|
|
|
|
path
|
|
|
|
);
|
|
|
|
|
|
|
|
if (action == "ACCEPT") {
|
|
|
|
logger.debug("Resource allowed by rule");
|
|
|
|
return allowed(res);
|
|
|
|
} else if (action == "DROP") {
|
|
|
|
logger.debug("Resource denied by rule");
|
|
|
|
return notAllowed(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
// otherwise its undefined and we pass
|
2025-02-06 21:42:18 -05:00
|
|
|
}
|
|
|
|
|
2025-02-11 23:59:13 -05:00
|
|
|
const redirectUrl = `${config.getRawConfig().app.dashboard_url}/auth/resource/${encodeURIComponent(
|
|
|
|
resource.resourceId
|
|
|
|
)}?redirect=${encodeURIComponent(originalRequestURL)}`;
|
2024-11-16 22:41:43 -05:00
|
|
|
|
2025-01-11 19:47:07 -05:00
|
|
|
// check for access token
|
|
|
|
let validAccessToken: ResourceAccessToken | undefined;
|
|
|
|
if (token) {
|
|
|
|
const [accessTokenId, accessToken] = token.split(".");
|
|
|
|
const { valid, error, tokenItem } = await verifyResourceAccessToken(
|
2025-02-11 23:59:13 -05:00
|
|
|
{ resource, accessTokenId, accessToken }
|
2025-01-11 19:47:07 -05:00
|
|
|
);
|
|
|
|
|
|
|
|
if (error) {
|
|
|
|
logger.debug("Access token invalid: " + error);
|
|
|
|
}
|
|
|
|
|
2025-01-27 22:43:32 -05:00
|
|
|
if (!valid) {
|
|
|
|
if (config.getRawConfig().app.log_failed_attempts) {
|
|
|
|
logger.info(
|
2025-02-11 23:59:13 -05:00
|
|
|
`Resource access token is invalid. Resource ID: ${
|
|
|
|
resource.resourceId
|
|
|
|
}. IP: ${clientIp}.`
|
2025-01-27 22:43:32 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-01-11 19:47:07 -05:00
|
|
|
if (valid && tokenItem) {
|
|
|
|
validAccessToken = tokenItem;
|
|
|
|
|
|
|
|
if (!sessions) {
|
|
|
|
return await createAccessTokenSession(
|
|
|
|
res,
|
|
|
|
resource,
|
|
|
|
tokenItem
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-11-27 00:07:40 -05:00
|
|
|
if (!sessions) {
|
2025-01-27 22:43:32 -05:00
|
|
|
if (config.getRawConfig().app.log_failed_attempts) {
|
|
|
|
logger.info(
|
2025-02-11 23:59:13 -05:00
|
|
|
`Missing resource sessions. Resource ID: ${
|
|
|
|
resource.resourceId
|
|
|
|
}. IP: ${clientIp}.`
|
2025-01-27 22:43:32 -05:00
|
|
|
);
|
|
|
|
}
|
2024-11-27 00:07:40 -05:00
|
|
|
return notAllowed(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
const resourceSessionToken =
|
|
|
|
sessions[
|
2025-02-11 23:59:13 -05:00
|
|
|
`${config.getRawConfig().server.session_cookie_name}${
|
|
|
|
resource.ssl ? "_s" : ""
|
|
|
|
}`
|
2024-11-27 00:07:40 -05:00
|
|
|
];
|
|
|
|
|
2024-12-18 23:14:26 -05:00
|
|
|
if (resourceSessionToken) {
|
2025-01-26 14:42:02 -05:00
|
|
|
const sessionCacheKey = `session:${resourceSessionToken}`;
|
|
|
|
let resourceSession: any = cache.get(sessionCacheKey);
|
|
|
|
|
|
|
|
if (!resourceSession) {
|
|
|
|
const result = await validateResourceSessionToken(
|
|
|
|
resourceSessionToken,
|
|
|
|
resource.resourceId
|
|
|
|
);
|
|
|
|
|
|
|
|
resourceSession = result?.resourceSession;
|
|
|
|
cache.set(sessionCacheKey, resourceSession);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (resourceSession?.isRequestToken) {
|
|
|
|
logger.debug(
|
|
|
|
"Resource not allowed because session is a temporary request token"
|
|
|
|
);
|
2025-01-27 22:43:32 -05:00
|
|
|
if (config.getRawConfig().app.log_failed_attempts) {
|
|
|
|
logger.info(
|
2025-02-11 23:59:13 -05:00
|
|
|
`Resource session is an exchange token. Resource ID: ${
|
|
|
|
resource.resourceId
|
|
|
|
}. IP: ${clientIp}.`
|
2025-01-27 22:43:32 -05:00
|
|
|
);
|
|
|
|
}
|
2025-01-26 14:42:02 -05:00
|
|
|
return notAllowed(res);
|
|
|
|
}
|
2024-11-27 00:07:40 -05:00
|
|
|
|
2024-11-17 22:44:11 -05:00
|
|
|
if (resourceSession) {
|
2024-12-21 21:01:12 -05:00
|
|
|
if (pincode && resourceSession.pincodeId) {
|
|
|
|
logger.debug(
|
|
|
|
"Resource allowed because pincode session is valid"
|
|
|
|
);
|
|
|
|
return allowed(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (password && resourceSession.passwordId) {
|
|
|
|
logger.debug(
|
|
|
|
"Resource allowed because password session is valid"
|
|
|
|
);
|
|
|
|
return allowed(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (
|
|
|
|
resource.emailWhitelistEnabled &&
|
|
|
|
resourceSession.whitelistId
|
|
|
|
) {
|
|
|
|
logger.debug(
|
|
|
|
"Resource allowed because whitelist session is valid"
|
|
|
|
);
|
|
|
|
return allowed(res);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (resourceSession.accessTokenId) {
|
|
|
|
logger.debug(
|
|
|
|
"Resource allowed because access token session is valid"
|
|
|
|
);
|
|
|
|
return allowed(res);
|
|
|
|
}
|
2025-01-26 14:42:02 -05:00
|
|
|
|
|
|
|
if (resourceSession.userSessionId && sso) {
|
2025-02-11 23:59:13 -05:00
|
|
|
const userAccessCacheKey = `userAccess:${
|
|
|
|
resourceSession.userSessionId
|
|
|
|
}:${resource.resourceId}`;
|
2025-01-26 14:42:02 -05:00
|
|
|
|
|
|
|
let isAllowed: boolean | undefined =
|
|
|
|
cache.get(userAccessCacheKey);
|
|
|
|
|
|
|
|
if (isAllowed === undefined) {
|
|
|
|
isAllowed = await isUserAllowedToAccessResource(
|
|
|
|
resourceSession.userSessionId,
|
|
|
|
resource
|
|
|
|
);
|
|
|
|
|
|
|
|
cache.set(userAccessCacheKey, isAllowed);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (isAllowed) {
|
|
|
|
logger.debug(
|
|
|
|
"Resource allowed because user session is valid"
|
|
|
|
);
|
|
|
|
return allowed(res);
|
|
|
|
}
|
|
|
|
}
|
2024-11-16 22:41:43 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-02-11 23:59:13 -05:00
|
|
|
// At this point we have checked all sessions, but since the access token is
|
|
|
|
// valid, we should allow access and create a new session.
|
2025-01-11 19:47:07 -05:00
|
|
|
if (validAccessToken) {
|
|
|
|
return await createAccessTokenSession(
|
|
|
|
res,
|
|
|
|
resource,
|
|
|
|
validAccessToken
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2024-11-24 14:28:23 -05:00
|
|
|
logger.debug("No more auth to check, resource not allowed");
|
2025-01-27 22:43:32 -05:00
|
|
|
|
|
|
|
if (config.getRawConfig().app.log_failed_attempts) {
|
|
|
|
logger.info(
|
2025-02-11 23:59:13 -05:00
|
|
|
`Resource access not allowed. Resource ID: ${
|
|
|
|
resource.resourceId
|
|
|
|
}. IP: ${clientIp}.`
|
2025-01-27 22:43:32 -05:00
|
|
|
);
|
|
|
|
}
|
2024-11-16 22:41:43 -05:00
|
|
|
return notAllowed(res, redirectUrl);
|
|
|
|
} catch (e) {
|
2024-11-24 14:28:23 -05:00
|
|
|
console.error(e);
|
2024-11-16 22:41:43 -05:00
|
|
|
return next(
|
|
|
|
createHttpError(
|
|
|
|
HttpCode.INTERNAL_SERVER_ERROR,
|
2024-12-15 17:47:07 -05:00
|
|
|
"Failed to verify session"
|
|
|
|
)
|
2024-11-16 22:41:43 -05:00
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
function notAllowed(res: Response, redirectUrl?: string) {
|
2024-11-24 14:28:23 -05:00
|
|
|
const data = {
|
2024-11-16 22:41:43 -05:00
|
|
|
data: { valid: false, redirectUrl },
|
|
|
|
success: true,
|
|
|
|
error: false,
|
|
|
|
message: "Access denied",
|
2024-12-15 17:47:07 -05:00
|
|
|
status: HttpCode.OK
|
2024-11-24 22:34:11 -05:00
|
|
|
};
|
2024-11-24 14:28:23 -05:00
|
|
|
logger.debug(JSON.stringify(data));
|
|
|
|
return response<VerifyUserResponse>(res, data);
|
2024-11-16 22:41:43 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
function allowed(res: Response) {
|
2024-11-24 14:28:23 -05:00
|
|
|
const data = {
|
2024-11-16 22:41:43 -05:00
|
|
|
data: { valid: true },
|
|
|
|
success: true,
|
|
|
|
error: false,
|
|
|
|
message: "Access allowed",
|
2024-12-15 17:47:07 -05:00
|
|
|
status: HttpCode.OK
|
2024-11-24 22:34:11 -05:00
|
|
|
};
|
2024-11-24 14:28:23 -05:00
|
|
|
logger.debug(JSON.stringify(data));
|
|
|
|
return response<VerifyUserResponse>(res, data);
|
2024-11-16 22:41:43 -05:00
|
|
|
}
|
2024-11-17 22:44:11 -05:00
|
|
|
|
2025-01-11 19:47:07 -05:00
|
|
|
async function createAccessTokenSession(
|
|
|
|
res: Response,
|
|
|
|
resource: Resource,
|
|
|
|
tokenItem: ResourceAccessToken
|
|
|
|
) {
|
|
|
|
const token = generateSessionToken();
|
|
|
|
await createResourceSession({
|
|
|
|
resourceId: resource.resourceId,
|
|
|
|
token,
|
|
|
|
accessTokenId: tokenItem.accessTokenId,
|
|
|
|
sessionLength: tokenItem.sessionLength,
|
|
|
|
expiresAt: tokenItem.expiresAt,
|
|
|
|
doNotExtend: tokenItem.expiresAt ? true : false
|
|
|
|
});
|
2025-01-26 14:42:02 -05:00
|
|
|
const cookieName = `${config.getRawConfig().server.session_cookie_name}`;
|
|
|
|
const cookie = serializeResourceSessionCookie(
|
|
|
|
cookieName,
|
2025-01-28 22:26:45 -05:00
|
|
|
resource.fullDomain!,
|
2025-01-26 14:42:02 -05:00
|
|
|
token,
|
|
|
|
!resource.ssl
|
|
|
|
);
|
2025-01-11 19:47:07 -05:00
|
|
|
res.appendHeader("Set-Cookie", cookie);
|
2025-01-26 14:42:02 -05:00
|
|
|
logger.debug("Access token is valid, creating new session");
|
2025-01-11 19:47:07 -05:00
|
|
|
return response<VerifyUserResponse>(res, {
|
|
|
|
data: { valid: true },
|
|
|
|
success: true,
|
|
|
|
error: false,
|
|
|
|
message: "Access allowed",
|
|
|
|
status: HttpCode.OK
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2024-11-17 22:44:11 -05:00
|
|
|
async function isUserAllowedToAccessResource(
|
2025-01-26 14:42:02 -05:00
|
|
|
userSessionId: string,
|
2024-12-15 17:47:07 -05:00
|
|
|
resource: Resource
|
2024-11-29 21:48:48 -05:00
|
|
|
): Promise<boolean> {
|
2025-01-26 14:42:02 -05:00
|
|
|
const [res] = await db
|
|
|
|
.select()
|
|
|
|
.from(sessions)
|
|
|
|
.leftJoin(users, eq(users.userId, sessions.userId))
|
|
|
|
.where(eq(sessions.sessionId, userSessionId));
|
|
|
|
|
|
|
|
const user = res.user;
|
|
|
|
const session = res.session;
|
|
|
|
|
|
|
|
if (!user || !session) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2025-01-11 19:47:07 -05:00
|
|
|
if (
|
|
|
|
config.getRawConfig().flags?.require_email_verification &&
|
|
|
|
!user.emailVerified
|
|
|
|
) {
|
2024-11-29 21:48:48 -05:00
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
2024-11-17 22:44:11 -05:00
|
|
|
const userOrgRole = await db
|
|
|
|
.select()
|
|
|
|
.from(userOrgs)
|
|
|
|
.where(
|
2024-11-24 14:28:23 -05:00
|
|
|
and(
|
2024-11-29 21:48:48 -05:00
|
|
|
eq(userOrgs.userId, user.userId),
|
2024-12-15 17:47:07 -05:00
|
|
|
eq(userOrgs.orgId, resource.orgId)
|
|
|
|
)
|
2024-11-17 22:44:11 -05:00
|
|
|
)
|
|
|
|
.limit(1);
|
|
|
|
|
|
|
|
if (userOrgRole.length === 0) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
const roleResourceAccess = await db
|
|
|
|
.select()
|
|
|
|
.from(roleResources)
|
|
|
|
.where(
|
|
|
|
and(
|
|
|
|
eq(roleResources.resourceId, resource.resourceId),
|
2024-12-15 17:47:07 -05:00
|
|
|
eq(roleResources.roleId, userOrgRole[0].roleId)
|
|
|
|
)
|
2024-11-17 22:44:11 -05:00
|
|
|
)
|
|
|
|
.limit(1);
|
|
|
|
|
|
|
|
if (roleResourceAccess.length > 0) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
const userResourceAccess = await db
|
|
|
|
.select()
|
|
|
|
.from(userResources)
|
|
|
|
.where(
|
|
|
|
and(
|
2024-11-29 21:48:48 -05:00
|
|
|
eq(userResources.userId, user.userId),
|
2024-12-15 17:47:07 -05:00
|
|
|
eq(userResources.resourceId, resource.resourceId)
|
|
|
|
)
|
2024-11-17 22:44:11 -05:00
|
|
|
)
|
|
|
|
.limit(1);
|
|
|
|
|
|
|
|
if (userResourceAccess.length > 0) {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
2025-02-06 21:42:18 -05:00
|
|
|
|
|
|
|
async function checkRules(
|
|
|
|
resourceId: number,
|
|
|
|
clientIp: string | undefined,
|
|
|
|
path: string | undefined
|
2025-02-09 10:50:43 -05:00
|
|
|
): Promise<"ACCEPT" | "DROP" | undefined> {
|
2025-02-06 21:42:18 -05:00
|
|
|
const ruleCacheKey = `rules:${resourceId}`;
|
|
|
|
|
2025-02-08 17:02:22 -05:00
|
|
|
let rules: ResourceRule[] | undefined = cache.get(ruleCacheKey);
|
2025-02-06 21:42:18 -05:00
|
|
|
|
|
|
|
if (!rules) {
|
|
|
|
rules = await db
|
|
|
|
.select()
|
2025-02-08 17:02:22 -05:00
|
|
|
.from(resourceRules)
|
|
|
|
.where(eq(resourceRules.resourceId, resourceId));
|
2025-02-06 21:42:18 -05:00
|
|
|
|
|
|
|
cache.set(ruleCacheKey, rules);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (rules.length === 0) {
|
|
|
|
logger.debug("No rules found for resource", resourceId);
|
2025-02-09 10:50:43 -05:00
|
|
|
return;
|
2025-02-06 21:42:18 -05:00
|
|
|
}
|
|
|
|
|
2025-02-11 23:59:13 -05:00
|
|
|
// sort rules by priority in ascending order
|
|
|
|
rules = rules.sort((a, b) => a.priority - b.priority);
|
2025-02-09 21:56:39 -05:00
|
|
|
|
2025-02-06 21:42:18 -05:00
|
|
|
for (const rule of rules) {
|
2025-02-11 23:59:13 -05:00
|
|
|
if (!rule.enabled) {
|
|
|
|
continue;
|
2025-02-09 21:56:39 -05:00
|
|
|
}
|
|
|
|
|
2025-02-11 23:59:13 -05:00
|
|
|
if (
|
|
|
|
clientIp &&
|
|
|
|
rule.match == "CIDR" &&
|
|
|
|
isIpInCidr(clientIp, rule.value)
|
|
|
|
) {
|
|
|
|
return rule.action as any;
|
|
|
|
} else if (clientIp && rule.match == "IP" && clientIp == rule.value) {
|
|
|
|
return rule.action as any;
|
|
|
|
} else if (
|
|
|
|
path &&
|
|
|
|
rule.match == "PATH" &&
|
|
|
|
isPathAllowed(rule.value, path)
|
|
|
|
) {
|
|
|
|
return rule.action as any;
|
2025-02-06 21:42:18 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2025-02-09 10:50:43 -05:00
|
|
|
return;
|
2025-02-06 21:42:18 -05:00
|
|
|
}
|
2025-02-08 17:54:01 -05:00
|
|
|
|
2025-02-11 23:59:13 -05:00
|
|
|
function isPathAllowed(pattern: string, path: string): boolean {
|
|
|
|
logger.debug(`\nMatching path "${path}" against pattern "${pattern}"`);
|
|
|
|
|
|
|
|
// Normalize and split paths into segments
|
|
|
|
const normalize = (p: string) => p.split("/").filter(Boolean);
|
|
|
|
const patternParts = normalize(pattern);
|
|
|
|
const pathParts = normalize(path);
|
|
|
|
|
|
|
|
logger.debug(`Normalized pattern parts: [${patternParts.join(", ")}]`);
|
|
|
|
logger.debug(`Normalized path parts: [${pathParts.join(", ")}]`);
|
|
|
|
|
|
|
|
// Recursive function to try different wildcard matches
|
|
|
|
function matchSegments(patternIndex: number, pathIndex: number): boolean {
|
|
|
|
const indent = " ".repeat(pathIndex); // Indent based on recursion depth
|
|
|
|
const currentPatternPart = patternParts[patternIndex];
|
|
|
|
const currentPathPart = pathParts[pathIndex];
|
|
|
|
|
|
|
|
logger.debug(
|
|
|
|
`${indent}Checking patternIndex=${patternIndex} (${currentPatternPart || "END"}) vs pathIndex=${pathIndex} (${currentPathPart || "END"})`
|
|
|
|
);
|
|
|
|
|
|
|
|
// If we've consumed all pattern parts, we should have consumed all path parts
|
|
|
|
if (patternIndex >= patternParts.length) {
|
|
|
|
const result = pathIndex >= pathParts.length;
|
|
|
|
logger.debug(
|
|
|
|
`${indent}Reached end of pattern, remaining path: ${pathParts.slice(pathIndex).join("/")} -> ${result}`
|
|
|
|
);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we've consumed all path parts but still have pattern parts
|
|
|
|
if (pathIndex >= pathParts.length) {
|
|
|
|
// The only way this can match is if all remaining pattern parts are wildcards
|
|
|
|
const remainingPattern = patternParts.slice(patternIndex);
|
|
|
|
const result = remainingPattern.every((p) => p === "*");
|
|
|
|
logger.debug(
|
|
|
|
`${indent}Reached end of path, remaining pattern: ${remainingPattern.join("/")} -> ${result}`
|
|
|
|
);
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
// For wildcards, try consuming different numbers of path segments
|
|
|
|
if (currentPatternPart === "*") {
|
|
|
|
logger.debug(
|
|
|
|
`${indent}Found wildcard at pattern index ${patternIndex}`
|
|
|
|
);
|
|
|
|
|
|
|
|
// Try consuming 0 segments (skip the wildcard)
|
|
|
|
logger.debug(
|
|
|
|
`${indent}Trying to skip wildcard (consume 0 segments)`
|
|
|
|
);
|
|
|
|
if (matchSegments(patternIndex + 1, pathIndex)) {
|
|
|
|
logger.debug(
|
|
|
|
`${indent}Successfully matched by skipping wildcard`
|
|
|
|
);
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try consuming current segment and recursively try rest
|
|
|
|
logger.debug(
|
|
|
|
`${indent}Trying to consume segment "${currentPathPart}" for wildcard`
|
|
|
|
);
|
|
|
|
if (matchSegments(patternIndex, pathIndex + 1)) {
|
|
|
|
logger.debug(
|
|
|
|
`${indent}Successfully matched by consuming segment for wildcard`
|
|
|
|
);
|
|
|
|
return true;
|
|
|
|
}
|
2025-02-09 10:50:43 -05:00
|
|
|
|
2025-02-11 23:59:13 -05:00
|
|
|
logger.debug(`${indent}Failed to match wildcard`);
|
|
|
|
return false;
|
|
|
|
}
|
2025-02-09 10:50:43 -05:00
|
|
|
|
2025-02-11 23:59:13 -05:00
|
|
|
// For regular segments, they must match exactly
|
|
|
|
if (currentPatternPart !== currentPathPart) {
|
|
|
|
logger.debug(
|
|
|
|
`${indent}Segment mismatch: "${currentPatternPart}" != "${currentPathPart}"`
|
|
|
|
);
|
|
|
|
return false;
|
|
|
|
}
|
2025-02-09 10:50:43 -05:00
|
|
|
|
2025-02-11 23:59:13 -05:00
|
|
|
logger.debug(
|
|
|
|
`${indent}Segments match: "${currentPatternPart}" = "${currentPathPart}"`
|
|
|
|
);
|
|
|
|
// Move to next segments in both pattern and path
|
|
|
|
return matchSegments(patternIndex + 1, pathIndex + 1);
|
|
|
|
}
|
|
|
|
|
|
|
|
const result = matchSegments(0, 0);
|
|
|
|
logger.debug(`Final result: ${result}`);
|
|
|
|
return result;
|
|
|
|
}
|