fosrl.pangolin/server/routers/badger/verifySession.ts

654 lines
20 KiB
TypeScript
Raw Normal View History

import { generateSessionToken } from "@server/auth/sessions/app";
import {
createResourceSession,
serializeResourceSessionCookie,
validateResourceSessionToken
} from "@server/auth/sessions/resource";
import { verifyResourceAccessToken } from "@server/auth/verifyResourceAccessToken";
import db from "@server/db";
import {
Resource,
2025-01-11 19:47:07 -05:00
ResourceAccessToken,
ResourcePassword,
resourcePassword,
ResourcePincode,
resourcePincode,
ResourceRule,
resourceRules,
resources,
roleResources,
sessions,
userOrgs,
userResources,
users
} from "@server/db/schema";
2025-01-01 21:41:31 -05:00
import config from "@server/lib/config";
import { isIpInCidr } from "@server/lib/ip";
import { response } from "@server/lib/response";
import logger from "@server/logger";
import HttpCode from "@server/types/HttpCode";
import { and, eq } from "drizzle-orm";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import NodeCache from "node-cache";
import { z } from "zod";
import { fromError } from "zod-validation-error";
// We'll see if this speeds anything up
const cache = new NodeCache({
stdTTL: 5 // seconds
});
const verifyResourceSessionSchema = z.object({
sessions: z.record(z.string()).optional(),
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()
});
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
): Promise<any> {
logger.debug("Verify session: Badger sent", req.body); // remove when done testing
const parsedBody = verifyResourceSessionSchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2024-12-15 17:47:07 -05:00
fromError(parsedBody.error).toString()
)
);
}
try {
const {
sessions,
host,
originalRequestURL,
2025-01-27 22:43:32 -05:00
requestIp,
2025-02-06 21:42:18 -05:00
path,
accessToken: token
} = parsedBody.data;
2025-01-27 22:43:32 -05:00
const clientIp = requestIp?.split(":")[0];
2025-02-15 17:48:27 -05:00
let cleanHost = host;
// if the host ends with :443 or :80 remove it
if (cleanHost.endsWith(":443")) {
cleanHost = cleanHost.slice(0, -4);
} else if (cleanHost.endsWith(":80")) {
cleanHost = cleanHost.slice(0, -3);
}
const resourceCacheKey = `resource:${cleanHost}`;
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)
)
2025-02-15 17:48:27 -05:00
.where(eq(resources.fullDomain, cleanHost))
.limit(1);
if (!result) {
2025-02-15 17:48:27 -05:00
logger.debug("Resource not found", cleanHost);
return notAllowed(res);
}
resourceData = {
resource: result.resources,
pincode: result.resourcePincode,
password: result.resourcePassword
};
cache.set(resourceCacheKey, resourceData);
}
const { resource, pincode, password } = resourceData;
if (!resource) {
2025-02-15 17:48:27 -05:00
logger.debug("Resource not found", cleanHost);
return notAllowed(res);
}
const { sso, blockAccess } = resource;
if (blockAccess) {
2024-11-24 14:28:23 -05:00
logger.debug("Resource blocked", host);
return notAllowed(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
}
if (
!resource.sso &&
!pincode &&
!password &&
!resource.emailWhitelistEnabled
) {
logger.debug("Resource allowed because no auth");
return allowed(res);
}
const redirectUrl = `${config.getRawConfig().app.dashboard_url}/auth/resource/${encodeURIComponent(
resource.resourceId
)}?redirect=${encodeURIComponent(originalRequestURL)}`;
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(
{ 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(
`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
);
}
}
}
if (!sessions) {
2025-01-27 22:43:32 -05:00
if (config.getRawConfig().app.log_failed_attempts) {
logger.info(
`Missing resource sessions. Resource ID: ${
resource.resourceId
}. IP: ${clientIp}.`
2025-01-27 22:43:32 -05:00
);
}
return notAllowed(res);
}
const resourceSessionToken =
sessions[
`${config.getRawConfig().server.session_cookie_name}${
resource.ssl ? "_s" : ""
}`
];
if (resourceSessionToken) {
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(
`Resource session is an exchange token. Resource ID: ${
resource.resourceId
}. IP: ${clientIp}.`
2025-01-27 22:43:32 -05:00
);
}
return notAllowed(res);
}
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);
}
if (resourceSession.userSessionId && sso) {
const userAccessCacheKey = `userAccess:${
resourceSession.userSessionId
}:${resource.resourceId}`;
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);
}
}
}
}
// 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(
`Resource access not allowed. Resource ID: ${
resource.resourceId
}. IP: ${clientIp}.`
2025-01-27 22:43:32 -05:00
);
}
return notAllowed(res, redirectUrl);
} catch (e) {
2024-11-24 14:28:23 -05:00
console.error(e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
2024-12-15 17:47:07 -05:00
"Failed to verify session"
)
);
}
}
function notAllowed(res: Response, redirectUrl?: string) {
2024-11-24 14:28:23 -05:00
const data = {
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 14:28:23 -05:00
logger.debug(JSON.stringify(data));
return response<VerifyUserResponse>(res, data);
}
function allowed(res: Response) {
2024-11-24 14:28:23 -05:00
const data = {
data: { valid: true },
success: true,
error: false,
message: "Access allowed",
2024-12-15 17:47:07 -05:00
status: HttpCode.OK
};
2024-11-24 14:28:23 -05:00
logger.debug(JSON.stringify(data));
return response<VerifyUserResponse>(res, data);
}
2025-01-11 19:47:07 -05:00
async function createAccessTokenSession(
res: Response,
resource: Resource,
tokenItem: ResourceAccessToken
) {
const token = generateSessionToken();
const sess = await createResourceSession({
2025-01-11 19:47:07 -05:00
resourceId: resource.resourceId,
token,
accessTokenId: tokenItem.accessTokenId,
sessionLength: tokenItem.sessionLength,
expiresAt: tokenItem.expiresAt,
doNotExtend: tokenItem.expiresAt ? true : false
});
const cookieName = `${config.getRawConfig().server.session_cookie_name}`;
const cookie = serializeResourceSessionCookie(
cookieName,
Squashed commit of the following: commit c276d2193da5dbe7af5197bdf7e2bcce6f87b0cf Author: Owen Schwartz <owen@txv.io> Date: Tue Jan 28 22:06:04 2025 -0500 Okay actually now commit 9afdc0aadc3f4fb4e811930bacff70a9e17eab9f Author: Owen Schwartz <owen@txv.io> Date: Tue Jan 28 21:58:44 2025 -0500 Migrations working finally commit a7336b3b2466fe74d650b9c253ecadbe1eff749d Merge: e7c7203 fdb1ab4 Author: Owen Schwartz <owen@txv.io> Date: Mon Jan 27 22:19:15 2025 -0500 Merge branch 'dev' into tcp-udp-traffic commit e7c7203330b1b08e570048b10ef314b55068e466 Author: Owen Schwartz <owen@txv.io> Date: Mon Jan 27 22:18:09 2025 -0500 Working on migration commit a4704dfd44b10647257c7c7054c0dae806d315bb Author: Owen Schwartz <owen@txv.io> Date: Mon Jan 27 21:40:52 2025 -0500 Add flag to allow raw resources commit d74f7a57ed11e2a6bf1a7e0c28c29fb07eb573a0 Merge: 6817788 d791b9b Author: Owen Schwartz <owen@txv.io> Date: Mon Jan 27 21:28:50 2025 -0500 Merge branch 'tcp-udp-traffic' of https://github.com/fosrl/pangolin into tcp-udp-traffic commit 68177882781b54ef30b62cca7dee8bbed7c5a2fa Author: Owen Schwartz <owen@txv.io> Date: Mon Jan 27 21:28:32 2025 -0500 Get everything working commit d791b9b47f9f6ca050d6edfd1d674438f8562d99 Author: Milo Schwartz <mschwartz10612@gmail.com> Date: Mon Jan 27 17:46:19 2025 -0500 fix orgId check in verifyAdmin commit 6ac30afd7a449a126190d311bd98d7f1048f73a4 Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 23:19:33 2025 -0500 Trying to figure out traefik... commit 9886b42272882f8bb6baff2efdbe26cee7cac2b6 Merge: 786e67e 85e9129 Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 21:53:32 2025 -0500 Merge branch 'tcp-udp-traffic' of https://github.com/fosrl/pangolin into tcp-udp-traffic commit 786e67eadd6df1ee8df24e77aed20c1f1fc9ca67 Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 21:51:37 2025 -0500 Bug fixing commit 85e9129ae313b2e4a460a8bc53a0af9f9fbbafb2 Author: Milo Schwartz <mschwartz10612@gmail.com> Date: Sun Jan 26 18:35:24 2025 -0500 rethrow errors in migration and remove permanent redirect commit bd82699505fc7510c27f72cd80ea0ce815d8c5ef Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 17:49:12 2025 -0500 Fix merge issue commit 933dbf3a02b1f19fd1f627410b2407fdf05cd9bf Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 17:46:13 2025 -0500 Add sql to update resources and targets commit f19437bad847c8dbf57fddd2c48cd17bab20ddb0 Merge: 58980eb 9f1f291 Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 17:19:51 2025 -0500 Merge branch 'dev' into tcp-udp-traffic commit 58980ebb64d1040b4d224c76beb38c2254f3c5d9 Merge: 1de682a d284d36 Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 17:10:09 2025 -0500 Merge branch 'dev' into tcp-udp-traffic commit 1de682a9f6039f40e05c8901c7381a94b0d018ed Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 17:08:29 2025 -0500 Working on migrations commit dc853d2bc02b11997be5c3c7ea789402716fb4c2 Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 16:56:49 2025 -0500 Finish config of resource pages commit 37c681c08d7ab73d2cad41e7ef1dbe3a8852e1f2 Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 16:07:25 2025 -0500 Finish up table commit 461c6650bbea0d7439cc042971ec13fdb52a7431 Author: Owen Schwartz <owen@txv.io> Date: Sun Jan 26 15:54:46 2025 -0500 Working toward having dual resource types commit f0894663627375e16ce6994370cb30b298efc2dc Author: Owen Schwartz <owen@txv.io> Date: Sat Jan 25 22:31:25 2025 -0500 Add qutoes commit edc535b79b94c2e65b290cd90a69fe17d27245e9 Author: Owen Schwartz <owen@txv.io> Date: Sat Jan 25 22:28:45 2025 -0500 Add readTimeout to allow long file uploads commit 194892fa14b505bd7c2b31873dc13d4b8996c0e1 Author: Owen Schwartz <owen@txv.io> Date: Sat Jan 25 20:37:34 2025 -0500 Rework traefik config generation commit ad3f896b5333e4706d610c3198f29dcd67610365 Author: Owen Schwartz <owen@txv.io> Date: Sat Jan 25 13:01:47 2025 -0500 Add proxy port to api commit ca6013b2ffda0924a696ec3141825a54a4e5297d Author: Owen Schwartz <owen@txv.io> Date: Sat Jan 25 12:58:01 2025 -0500 Add migration commit 2258d76cb3a49d3db7f05f76d8b8a9f1c248b5e4 Author: Owen Schwartz <owen@txv.io> Date: Sat Jan 25 12:55:02 2025 -0500 Add new proxy port
2025-01-28 22:26:45 -05:00
resource.fullDomain!,
token,
!resource.ssl,
new Date(sess.expiresAt)
);
2025-01-11 19:47:07 -05:00
res.appendHeader("Set-Cookie", cookie);
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
});
}
async function isUserAllowedToAccessResource(
userSessionId: string,
2024-12-15 17:47:07 -05:00
resource: Resource
): Promise<boolean> {
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
) {
return false;
}
const userOrgRole = await db
.select()
.from(userOrgs)
.where(
2024-11-24 14:28:23 -05:00
and(
eq(userOrgs.userId, user.userId),
2024-12-15 17:47:07 -05:00
eq(userOrgs.orgId, resource.orgId)
)
)
.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)
)
)
.limit(1);
if (roleResourceAccess.length > 0) {
return true;
}
const userResourceAccess = await db
.select()
.from(userResources)
.where(
and(
eq(userResources.userId, user.userId),
2024-12-15 17:47:07 -05:00
eq(userResources.resourceId, resource.resourceId)
)
)
.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}`;
let rules: ResourceRule[] | undefined = cache.get(ruleCacheKey);
2025-02-06 21:42:18 -05:00
if (!rules) {
rules = await db
.select()
.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
}
// 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) {
if (!rule.enabled) {
continue;
2025-02-09 21:56:39 -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
export 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 full segment 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
logger.debug(`${indent}Failed to match wildcard`);
return false;
}
2025-02-09 10:50:43 -05:00
// Check for in-segment wildcard (e.g., "prefix*" or "prefix*suffix")
if (currentPatternPart.includes("*")) {
logger.debug(
`${indent}Found in-segment wildcard in "${currentPatternPart}"`
);
// Convert the pattern segment to a regex pattern
const regexPattern = currentPatternPart
.replace(/\*/g, ".*") // Replace * with .* for regex wildcard
.replace(/\?/g, "."); // Replace ? with . for single character wildcard if needed
const regex = new RegExp(`^${regexPattern}$`);
if (regex.test(currentPathPart)) {
logger.debug(
`${indent}Segment with wildcard matches: "${currentPatternPart}" matches "${currentPathPart}"`
);
return matchSegments(patternIndex + 1, pathIndex + 1);
}
logger.debug(
`${indent}Segment with wildcard mismatch: "${currentPatternPart}" doesn't match "${currentPathPart}"`
);
return false;
}
// 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
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;
}