Compare commits

..

27 Commits

Author SHA1 Message Date
Owen
e05af54f76 Use standard component 2026-03-26 21:36:51 -07:00
Owen
19a686b3e4 Add restrictions around provisioning key 2026-03-26 16:49:43 -07:00
Owen
b4ca6432db Fix double id 2026-03-26 16:24:44 -07:00
Owen
c80c7df1d0 Batch set bandwidth 2026-03-25 20:44:08 -07:00
Owen
99a064b77a Fix import problems 2026-03-25 20:44:08 -07:00
Owen
9b84623d0c Cache token for thundering hurd 2026-03-25 20:44:08 -07:00
Owen
6bb6cf8a48 Clean up 2026-03-25 20:44:08 -07:00
Owen
348fcbcabf Try to solve th problem 2026-03-25 20:44:08 -07:00
Owen
1f4cde5f7f Add license script 2026-03-25 20:44:08 -07:00
Owen
3e3b02021c Add ssh access log 2026-03-25 20:44:08 -07:00
Owen
17eb93d045 Add better pooling controls 2026-03-25 20:44:08 -07:00
Owen
660420ddef Disable everything if not paid 2026-03-25 20:44:08 -07:00
miloschwartz
2091b5f359 Merge branch 'logging-provision' of https://github.com/fosrl/pangolin into logging-provision 2026-03-24 20:30:14 -07:00
miloschwartz
3525b367b3 move to private routes 2026-03-24 20:27:15 -07:00
Owen
0b5b6ed5a3 Adjust register endpoint 2026-03-24 18:26:10 -07:00
Owen
6fe9494df4 Merge branch 'logging-provision' of github.com:fosrl/pangolin into logging-provision 2026-03-24 18:17:42 -07:00
Owen
b2eab95a3b Pass at first endpoints 2026-03-24 18:17:33 -07:00
miloschwartz
212b7a104f Merge branch 'logging-provision' of https://github.com/fosrl/pangolin into logging-provision 2026-03-24 17:01:36 -07:00
miloschwartz
d21dfb750e ui for provisioning key 2026-03-24 17:01:20 -07:00
miloschwartz
7db58f920c add site provisioning key crud 2026-03-24 16:19:00 -07:00
Owen
7b78b91449 Fix resource link 2026-03-23 22:00:53 -07:00
Owen
f9bff5954f Add filters and refine table and query 2026-03-23 21:49:22 -07:00
Owen
2c6e9507b5 Connection log page working 2026-03-23 21:41:53 -07:00
Owen
6471571bc6 Add ui for connection logs 2026-03-23 20:18:03 -07:00
Owen
fe40ea58c1 Source client info into schema 2026-03-23 20:05:54 -07:00
Owen
0d4edcd1c7 make private 2026-03-23 17:23:51 -07:00
Owen
7d8797840a Add connection log 2026-03-23 17:01:34 -07:00
148 changed files with 5979 additions and 4630 deletions

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Изтрийте потребител",
"actionListUsers": "Изброяване на потребители",
"actionAddUserRole": "Добавяне на роля на потребител",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Генериране на токен за достъп",
"actionDeleteAccessToken": "Изтриване на токен за достъп",
"actionListAccessTokens": "Изброяване на токени за достъп",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Odstranit uživatele",
"actionListUsers": "Seznam uživatelů",
"actionAddUserRole": "Přidat uživatelskou roli",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Generovat přístupový token",
"actionDeleteAccessToken": "Odstranit přístupový token",
"actionListAccessTokens": "Seznam přístupových tokenů",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Benutzer entfernen",
"actionListUsers": "Benutzer auflisten",
"actionAddUserRole": "Benutzerrolle hinzufügen",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Zugriffstoken generieren",
"actionDeleteAccessToken": "Zugriffstoken löschen",
"actionListAccessTokens": "Zugriffstoken auflisten",

View File

@@ -323,6 +323,41 @@
"apiKeysDelete": "Delete API Key",
"apiKeysManage": "Manage API Keys",
"apiKeysDescription": "API keys are used to authenticate with the integration API",
"provisioningKeysTitle": "Provisioning Key",
"provisioningKeysManage": "Manage Provisioning Keys",
"provisioningKeysDescription": "Provisioning keys are used to authenticate automated site provisioning for your organization.",
"provisioningKeys": "Provisioning Keys",
"searchProvisioningKeys": "Search provisioning keys...",
"provisioningKeysAdd": "Generate Provisioning Key",
"provisioningKeysErrorDelete": "Error deleting provisioning key",
"provisioningKeysErrorDeleteMessage": "Error deleting provisioning key",
"provisioningKeysQuestionRemove": "Are you sure you want to remove this provisioning key from the organization?",
"provisioningKeysMessageRemove": "Once removed, the key can no longer be used for site provisioning.",
"provisioningKeysDeleteConfirm": "Confirm Delete Provisioning Key",
"provisioningKeysDelete": "Delete Provisioning key",
"provisioningKeysCreate": "Generate Provisioning Key",
"provisioningKeysCreateDescription": "Generate a new provisioning key for the organization",
"provisioningKeysSeeAll": "See all provisioning keys",
"provisioningKeysSave": "Save the provisioning key",
"provisioningKeysSaveDescription": "You will only be able to see this once. Copy it to a secure place.",
"provisioningKeysErrorCreate": "Error creating provisioning key",
"provisioningKeysList": "New provisioning key",
"provisioningKeysMaxBatchSize": "Max batch size",
"provisioningKeysUnlimitedBatchSize": "Unlimited batch size (no limit)",
"provisioningKeysMaxBatchUnlimited": "Unlimited",
"provisioningKeysMaxBatchSizeInvalid": "Enter a valid max batch size (11,000,000).",
"provisioningKeysValidUntil": "Valid until",
"provisioningKeysValidUntilHint": "Leave empty for no expiration.",
"provisioningKeysValidUntilInvalid": "Enter a valid date and time.",
"provisioningKeysNumUsed": "Times used",
"provisioningKeysLastUsed": "Last used",
"provisioningKeysNoExpiry": "No expiration",
"provisioningKeysNeverUsed": "Never",
"provisioningKeysEdit": "Edit Provisioning Key",
"provisioningKeysEditDescription": "Update the max batch size and expiration time for this key.",
"provisioningKeysUpdateError": "Error updating provisioning key",
"provisioningKeysUpdated": "Provisioning key updated",
"provisioningKeysUpdatedDescription": "Your changes have been saved.",
"apiKeysSettings": "{apiKeyName} Settings",
"userTitle": "Manage All Users",
"userDescription": "View and manage all users in the system",
@@ -509,12 +544,9 @@
"userSaved": "User saved",
"userSavedDescription": "The user has been updated.",
"autoProvisioned": "Auto Provisioned",
"autoProvisionSettings": "Auto Provision Settings",
"autoProvisionedDescription": "Allow this user to be automatically managed by identity provider",
"accessControlsDescription": "Manage what this user can access and do in the organization",
"accessControlsSubmit": "Save Access Controls",
"singleRolePerUserPlanNotice": "Your plan only supports one role per user.",
"singleRolePerUserEditionNotice": "This edition only supports one role per user.",
"roles": "Roles",
"accessUsersRoles": "Manage Users & Roles",
"accessUsersRolesDescription": "Invite users and add them to roles to manage access to the organization",
@@ -890,7 +922,7 @@
"defaultMappingsRole": "Default Role Mapping",
"defaultMappingsRoleDescription": "The result of this expression must return the role name as defined in the organization as a string.",
"defaultMappingsOrg": "Default Organization Mapping",
"defaultMappingsOrgDescription": "When set, this expression must return the organization ID or true for the user to access that organization. When unset, defining an organization policy for that org is enough: the user is allowed in as long as a valid role mapping can be resolved for them within the organization.",
"defaultMappingsOrgDescription": "This expression must return the org ID or true for the user to be allowed to access the organization.",
"defaultMappingsSubmit": "Save Default Mappings",
"orgPoliciesEdit": "Edit Organization Policy",
"org": "Organization",
@@ -1043,6 +1075,7 @@
"pageNotFoundDescription": "Oops! The page you're looking for doesn't exist.",
"overview": "Overview",
"home": "Home",
"accessControl": "Access Control",
"settings": "Settings",
"usersAll": "All Users",
"license": "License",
@@ -1152,7 +1185,6 @@
"actionRemoveUser": "Remove User",
"actionListUsers": "List Users",
"actionAddUserRole": "Add User Role",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Generate Access Token",
"actionDeleteAccessToken": "Delete Access Token",
"actionListAccessTokens": "List Access Tokens",
@@ -1269,6 +1301,7 @@
"sidebarRoles": "Roles",
"sidebarShareableLinks": "Links",
"sidebarApiKeys": "API Keys",
"sidebarProvisioning": "Provisioning",
"sidebarSettings": "Settings",
"sidebarAllUsers": "All Users",
"sidebarIdentityProviders": "Identity Providers",
@@ -1942,25 +1975,6 @@
"invalidValue": "Invalid value",
"idpTypeLabel": "Identity Provider Type",
"roleMappingExpressionPlaceholder": "e.g., contains(groups, 'admin') && 'Admin' || 'Member'",
"roleMappingModeFixedRoles": "Fixed Roles",
"roleMappingModeMappingBuilder": "Mapping Builder",
"roleMappingModeRawExpression": "Raw Expression",
"roleMappingFixedRolesPlaceholderSelect": "Select one or more roles",
"roleMappingFixedRolesPlaceholderFreeform": "Type role names (exact match per organization)",
"roleMappingFixedRolesDescriptionSameForAll": "Assign the same role set to every auto-provisioned user.",
"roleMappingFixedRolesDescriptionDefaultPolicy": "For default policies, type role names that exist in each organization where users are provisioned. Names must match exactly.",
"roleMappingClaimPath": "Claim Path",
"roleMappingClaimPathPlaceholder": "groups",
"roleMappingClaimPathDescription": "Path in the token payload that contains source values (for example, groups).",
"roleMappingMatchValue": "Match Value",
"roleMappingAssignRoles": "Assign Roles",
"roleMappingAddMappingRule": "Add Mapping Rule",
"roleMappingRawExpressionResultDescription": "Expression must evaluate to a string or string array.",
"roleMappingRawExpressionResultDescriptionSingleRole": "Expression must evaluate to a string (a single role name).",
"roleMappingMatchValuePlaceholder": "Match value (for example: admin)",
"roleMappingAssignRolesPlaceholderFreeform": "Type role names (exact per org)",
"roleMappingBuilderFreeformRowHint": "Role names must match a role in each target organization.",
"roleMappingRemoveRule": "Remove",
"idpGoogleConfiguration": "Google Configuration",
"idpGoogleConfigurationDescription": "Configure the Google OAuth2 credentials",
"idpGoogleClientIdDescription": "Google OAuth2 Client ID",
@@ -2367,6 +2381,12 @@
"logRetentionEndOfFollowingYear": "End of following year",
"actionLogsDescription": "View a history of actions performed in this organization",
"accessLogsDescription": "View access auth requests for resources in this organization",
"connectionLogs": "Connection Logs",
"connectionLogsDescription": "View connection logs for tunnels in this organization",
"sidebarLogsConnection": "Connection Logs",
"sourceAddress": "Source Address",
"destinationAddress": "Destination Address",
"duration": "Duration",
"licenseRequiredToUse": "An <enterpriseLicenseLink>Enterprise Edition</enterpriseLicenseLink> license or <pangolinCloudLink>Pangolin Cloud</pangolinCloudLink> is required to use this feature. <bookADemoLink>Book a demo or POC trial</bookADemoLink>.",
"ossEnterpriseEditionRequired": "The <enterpriseEditionLink>Enterprise Edition</enterpriseEditionLink> is required to use this feature. This feature is also available in <pangolinCloudLink>Pangolin Cloud</pangolinCloudLink>. <bookADemoLink>Book a demo or POC trial</bookADemoLink>.",
"certResolver": "Certificate Resolver",
@@ -2533,9 +2553,9 @@
"remoteExitNodeRegenerateCredentialsConfirmation": "Are you sure you want to regenerate the credentials for this remote exit node?",
"remoteExitNodeRegenerateCredentialsWarning": "This will regenerate the credentials. The remote exit node will stay connected until you manually restart it and use the new credentials.",
"agent": "Agent",
"personalUseOnly": "Personal Use Only",
"loginPageLicenseWatermark": "This instance is licensed for personal use only.",
"instanceIsUnlicensed": "This instance is unlicensed.",
"personalUseOnly": "Personal Use Only",
"loginPageLicenseWatermark": "This instance is licensed for personal use only.",
"instanceIsUnlicensed": "This instance is unlicensed.",
"portRestrictions": "Port Restrictions",
"allPorts": "All",
"custom": "Custom",
@@ -2589,7 +2609,7 @@
"automaticModeDescription": " Show maintenance page only when all backend targets are down or unhealthy. Your resource continues working normally as long as at least one target is healthy.",
"forced": "Forced",
"forcedModeDescription": "Always show the maintenance page regardless of backend health. Use this for planned maintenance when you want to prevent all access.",
"warning:": "Warning:",
"warning:" : "Warning:",
"forcedeModeWarning": "All traffic will be directed to the maintenance page. Your backend resources will not receive any requests.",
"pageTitle": "Page Title",
"pageTitleDescription": "The main heading displayed on the maintenance page",
@@ -2706,6 +2726,5 @@
"approvalsEmptyStateStep2Description": "Edit a role and enable the 'Require Device Approvals' option. Users with this role will need admin approval for new devices.",
"approvalsEmptyStatePreviewDescription": "Preview: When enabled, pending device requests will appear here for review",
"approvalsEmptyStateButtonText": "Manage Roles",
"domainErrorTitle": "We are having trouble verifying your domain",
"idpAdminAutoProvisionPoliciesTabHint": "Configure role mapping and organization policies on the <policiesTabLink>Auto Provision Settings</policiesTabLink> tab."
"domainErrorTitle": "We are having trouble verifying your domain"
}

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Eliminar usuario",
"actionListUsers": "Listar usuarios",
"actionAddUserRole": "Añadir rol de usuario",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Generar token de acceso",
"actionDeleteAccessToken": "Eliminar token de acceso",
"actionListAccessTokens": "Lista de Tokens de Acceso",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Supprimer un utilisateur",
"actionListUsers": "Lister les utilisateurs",
"actionAddUserRole": "Ajouter un rôle utilisateur",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Générer un jeton d'accès",
"actionDeleteAccessToken": "Supprimer un jeton d'accès",
"actionListAccessTokens": "Lister les jetons d'accès",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Rimuovi Utente",
"actionListUsers": "Elenca Utenti",
"actionAddUserRole": "Aggiungi Ruolo Utente",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Genera Token di Accesso",
"actionDeleteAccessToken": "Elimina Token di Accesso",
"actionListAccessTokens": "Elenca Token di Accesso",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "사용자 제거",
"actionListUsers": "사용자 목록",
"actionAddUserRole": "사용자 역할 추가",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "액세스 토큰 생성",
"actionDeleteAccessToken": "액세스 토큰 삭제",
"actionListAccessTokens": "액세스 토큰 목록",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Fjern bruker",
"actionListUsers": "List opp brukere",
"actionAddUserRole": "Legg til brukerrolle",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Generer tilgangstoken",
"actionDeleteAccessToken": "Slett tilgangstoken",
"actionListAccessTokens": "List opp tilgangstokener",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Gebruiker verwijderen",
"actionListUsers": "Gebruikers weergeven",
"actionAddUserRole": "Gebruikersrol toevoegen",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Genereer Toegangstoken",
"actionDeleteAccessToken": "Verwijder toegangstoken",
"actionListAccessTokens": "Lijst toegangstokens",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Usuń użytkownika",
"actionListUsers": "Lista użytkowników",
"actionAddUserRole": "Dodaj rolę użytkownika",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Wygeneruj token dostępu",
"actionDeleteAccessToken": "Usuń token dostępu",
"actionListAccessTokens": "Lista tokenów dostępu",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Remover Utilizador",
"actionListUsers": "Listar Utilizadores",
"actionAddUserRole": "Adicionar Função ao Utilizador",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Gerar Token de Acesso",
"actionDeleteAccessToken": "Eliminar Token de Acesso",
"actionListAccessTokens": "Listar Tokens de Acesso",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Удалить пользователя",
"actionListUsers": "Список пользователей",
"actionAddUserRole": "Добавить роль пользователя",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Сгенерировать токен доступа",
"actionDeleteAccessToken": "Удалить токен доступа",
"actionListAccessTokens": "Список токенов доступа",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "Kullanıcıyı Kaldır",
"actionListUsers": "Kullanıcıları Listele",
"actionAddUserRole": "Kullanıcı Rolü Ekle",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "Erişim Jetonu Oluştur",
"actionDeleteAccessToken": "Erişim Jetonunu Sil",
"actionListAccessTokens": "Erişim Jetonlarını Listele",

View File

@@ -1148,7 +1148,6 @@
"actionRemoveUser": "删除用户",
"actionListUsers": "列出用户",
"actionAddUserRole": "添加用户角色",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "生成访问令牌",
"actionDeleteAccessToken": "删除访问令牌",
"actionListAccessTokens": "访问令牌",

View File

@@ -1091,7 +1091,6 @@
"actionRemoveUser": "刪除用戶",
"actionListUsers": "列出用戶",
"actionAddUserRole": "添加用戶角色",
"actionSetUserOrgRoles": "Set User Roles",
"actionGenerateAccessToken": "生成訪問令牌",
"actionDeleteAccessToken": "刪除訪問令牌",
"actionListAccessTokens": "訪問令牌",

View File

@@ -1,10 +1,9 @@
import { Request } from "express";
import { db } from "@server/db";
import { userActions, roleActions } from "@server/db";
import { and, eq, inArray } from "drizzle-orm";
import { userActions, roleActions, userOrgs } from "@server/db";
import { and, eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export enum ActionsEnum {
createOrgUser = "createOrgUser",
@@ -54,8 +53,6 @@ export enum ActionsEnum {
listRoleResources = "listRoleResources",
// listRoleActions = "listRoleActions",
addUserRole = "addUserRole",
removeUserRole = "removeUserRole",
setUserOrgRoles = "setUserOrgRoles",
// addUserSite = "addUserSite",
// addUserAction = "addUserAction",
// removeUserAction = "removeUserAction",
@@ -112,6 +109,10 @@ export enum ActionsEnum {
listApiKeyActions = "listApiKeyActions",
listApiKeys = "listApiKeys",
getApiKey = "getApiKey",
createSiteProvisioningKey = "createSiteProvisioningKey",
listSiteProvisioningKeys = "listSiteProvisioningKeys",
updateSiteProvisioningKey = "updateSiteProvisioningKey",
deleteSiteProvisioningKey = "deleteSiteProvisioningKey",
getCertificate = "getCertificate",
restartCertificate = "restartCertificate",
billing = "billing",
@@ -157,16 +158,29 @@ export async function checkUserActionPermission(
}
try {
let userOrgRoleIds = req.userOrgRoleIds;
let userOrgRoleId = req.userOrgRoleId;
if (userOrgRoleIds === undefined) {
userOrgRoleIds = await getUserOrgRoleIds(userId, req.userOrgId!);
if (userOrgRoleIds.length === 0) {
// If userOrgRoleId is not available on the request, fetch it
if (userOrgRoleId === undefined) {
const userOrgRole = await db
.select()
.from(userOrgs)
.where(
and(
eq(userOrgs.userId, userId),
eq(userOrgs.orgId, req.userOrgId!)
)
)
.limit(1);
if (userOrgRole.length === 0) {
throw createHttpError(
HttpCode.FORBIDDEN,
"User does not have access to this organization"
);
}
userOrgRoleId = userOrgRole[0].roleId;
}
// Check if the user has direct permission for the action in the current org
@@ -177,7 +191,7 @@ export async function checkUserActionPermission(
and(
eq(userActions.userId, userId),
eq(userActions.actionId, actionId),
eq(userActions.orgId, req.userOrgId!)
eq(userActions.orgId, req.userOrgId!) // TODO: we cant pass the org id if we are not checking the org
)
)
.limit(1);
@@ -186,14 +200,14 @@ export async function checkUserActionPermission(
return true;
}
// If no direct permission, check role-based permission (any of user's roles)
// If no direct permission, check role-based permission
const roleActionPermission = await db
.select()
.from(roleActions)
.where(
and(
eq(roleActions.actionId, actionId),
inArray(roleActions.roleId, userOrgRoleIds),
eq(roleActions.roleId, userOrgRoleId!),
eq(roleActions.orgId, req.userOrgId!)
)
)

View File

@@ -1,29 +1,26 @@
import { db } from "@server/db";
import { and, eq, inArray } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import { roleResources, userResources } from "@server/db";
export async function canUserAccessResource({
userId,
resourceId,
roleIds
roleId
}: {
userId: string;
resourceId: number;
roleIds: number[];
roleId: number;
}): Promise<boolean> {
const roleResourceAccess =
roleIds.length > 0
? await db
.select()
.from(roleResources)
.where(
and(
eq(roleResources.resourceId, resourceId),
inArray(roleResources.roleId, roleIds)
)
)
.limit(1)
: [];
const roleResourceAccess = await db
.select()
.from(roleResources)
.where(
and(
eq(roleResources.resourceId, resourceId),
eq(roleResources.roleId, roleId)
)
)
.limit(1);
if (roleResourceAccess.length > 0) {
return true;

View File

@@ -1,29 +1,26 @@
import { db } from "@server/db";
import { and, eq, inArray } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import { roleSiteResources, userSiteResources } from "@server/db";
export async function canUserAccessSiteResource({
userId,
resourceId,
roleIds
roleId
}: {
userId: string;
resourceId: number;
roleIds: number[];
roleId: number;
}): Promise<boolean> {
const roleResourceAccess =
roleIds.length > 0
? await db
.select()
.from(roleSiteResources)
.where(
and(
eq(roleSiteResources.siteResourceId, resourceId),
inArray(roleSiteResources.roleId, roleIds)
)
)
.limit(1)
: [];
const roleResourceAccess = await db
.select()
.from(roleSiteResources)
.where(
and(
eq(roleSiteResources.siteResourceId, resourceId),
eq(roleSiteResources.roleId, roleId)
)
)
.limit(1);
if (roleResourceAccess.length > 0) {
return true;

View File

@@ -1,4 +1,5 @@
import { flushBandwidthToDb } from "@server/routers/newt/handleReceiveBandwidthMessage";
import { flushConnectionLogToDb } from "#dynamic/routers/newt";
import { flushSiteBandwidthToDb } from "@server/routers/gerbil/receiveBandwidth";
import { stopPingAccumulator } from "@server/routers/newt/pingAccumulator";
import { cleanup as wsCleanup } from "#dynamic/routers/ws";
@@ -6,6 +7,7 @@ import { cleanup as wsCleanup } from "#dynamic/routers/ws";
async function cleanup() {
await stopPingAccumulator();
await flushBandwidthToDb();
await flushConnectionLogToDb();
await flushSiteBandwidthToDb();
await wsCleanup();
@@ -16,4 +18,4 @@ export async function initCleanup() {
// Handle process termination
process.on("SIGTERM", () => cleanup());
process.on("SIGINT", () => cleanup());
}
}

View File

@@ -7,7 +7,8 @@ import {
bigint,
real,
text,
index
index,
primaryKey
} from "drizzle-orm/pg-core";
import { InferSelectModel } from "drizzle-orm";
import {
@@ -17,7 +18,9 @@ import {
users,
exitNodes,
sessions,
clients
clients,
siteResources,
sites
} from "./schema";
export const certificates = pgTable("certificates", {
@@ -89,7 +92,9 @@ export const subscriptions = pgTable("subscriptions", {
export const subscriptionItems = pgTable("subscriptionItems", {
subscriptionItemId: serial("subscriptionItemId").primaryKey(),
stripeSubscriptionItemId: varchar("stripeSubscriptionItemId", { length: 255 }),
stripeSubscriptionItemId: varchar("stripeSubscriptionItemId", {
length: 255
}),
subscriptionId: varchar("subscriptionId", { length: 255 })
.notNull()
.references(() => subscriptions.subscriptionId, {
@@ -302,6 +307,45 @@ export const accessAuditLog = pgTable(
]
);
export const connectionAuditLog = pgTable(
"connectionAuditLog",
{
id: serial("id").primaryKey(),
sessionId: text("sessionId").notNull(),
siteResourceId: integer("siteResourceId").references(
() => siteResources.siteResourceId,
{ onDelete: "cascade" }
),
orgId: text("orgId").references(() => orgs.orgId, {
onDelete: "cascade"
}),
siteId: integer("siteId").references(() => sites.siteId, {
onDelete: "cascade"
}),
clientId: integer("clientId").references(() => clients.clientId, {
onDelete: "cascade"
}),
userId: text("userId").references(() => users.userId, {
onDelete: "cascade"
}),
sourceAddr: text("sourceAddr").notNull(),
destAddr: text("destAddr").notNull(),
protocol: text("protocol").notNull(),
startedAt: integer("startedAt").notNull(),
endedAt: integer("endedAt"),
bytesTx: integer("bytesTx"),
bytesRx: integer("bytesRx")
},
(table) => [
index("idx_accessAuditLog_startedAt").on(table.startedAt),
index("idx_accessAuditLog_org_startedAt").on(
table.orgId,
table.startedAt
),
index("idx_accessAuditLog_siteResourceId").on(table.siteResourceId)
]
);
export const approvals = pgTable("approvals", {
approvalId: serial("approvalId").primaryKey(),
timestamp: integer("timestamp").notNull(), // this is EPOCH time in seconds
@@ -329,13 +373,48 @@ export const approvals = pgTable("approvals", {
});
export const bannedEmails = pgTable("bannedEmails", {
email: varchar("email", { length: 255 }).primaryKey(),
email: varchar("email", { length: 255 }).primaryKey()
});
export const bannedIps = pgTable("bannedIps", {
ip: varchar("ip", { length: 255 }).primaryKey(),
ip: varchar("ip", { length: 255 }).primaryKey()
});
export const siteProvisioningKeys = pgTable("siteProvisioningKeys", {
siteProvisioningKeyId: varchar("siteProvisioningKeyId", {
length: 255
}).primaryKey(),
name: varchar("name", { length: 255 }).notNull(),
siteProvisioningKeyHash: text("siteProvisioningKeyHash").notNull(),
lastChars: varchar("lastChars", { length: 4 }).notNull(),
createdAt: varchar("dateCreated", { length: 255 }).notNull(),
lastUsed: varchar("lastUsed", { length: 255 }),
maxBatchSize: integer("maxBatchSize"), // null = no limit
numUsed: integer("numUsed").notNull().default(0),
validUntil: varchar("validUntil", { length: 255 })
});
export const siteProvisioningKeyOrg = pgTable(
"siteProvisioningKeyOrg",
{
siteProvisioningKeyId: varchar("siteProvisioningKeyId", {
length: 255
})
.notNull()
.references(() => siteProvisioningKeys.siteProvisioningKeyId, {
onDelete: "cascade"
}),
orgId: varchar("orgId", { length: 255 })
.notNull()
.references(() => orgs.orgId, { onDelete: "cascade" })
},
(table) => [
primaryKey({
columns: [table.siteProvisioningKeyId, table.orgId]
})
]
);
export type Approval = InferSelectModel<typeof approvals>;
export type Limit = InferSelectModel<typeof limits>;
export type Account = InferSelectModel<typeof account>;
@@ -357,3 +436,4 @@ export type LoginPage = InferSelectModel<typeof loginPage>;
export type LoginPageBranding = InferSelectModel<typeof loginPageBranding>;
export type ActionAuditLog = InferSelectModel<typeof actionAuditLog>;
export type AccessAuditLog = InferSelectModel<typeof accessAuditLog>;
export type ConnectionAuditLog = InferSelectModel<typeof connectionAuditLog>;

View File

@@ -9,7 +9,6 @@ import {
real,
serial,
text,
unique,
varchar
} from "drizzle-orm/pg-core";
@@ -56,6 +55,9 @@ export const orgs = pgTable("orgs", {
settingsLogRetentionDaysAction: integer("settingsLogRetentionDaysAction") // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year
.notNull()
.default(0),
settingsLogRetentionDaysConnection: integer("settingsLogRetentionDaysConnection") // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year
.notNull()
.default(0),
sshCaPrivateKey: text("sshCaPrivateKey"), // Encrypted SSH CA private key (PEM format)
sshCaPublicKey: text("sshCaPublicKey"), // SSH CA public key (OpenSSH format)
isBillingOrg: boolean("isBillingOrg"),
@@ -336,6 +338,9 @@ export const userOrgs = pgTable("userOrgs", {
onDelete: "cascade"
})
.notNull(),
roleId: integer("roleId")
.notNull()
.references(() => roles.roleId),
isOwner: boolean("isOwner").notNull().default(false),
autoProvisioned: boolean("autoProvisioned").default(false),
pamUsername: varchar("pamUsername") // cleaned username for ssh and such
@@ -384,22 +389,6 @@ export const roles = pgTable("roles", {
sshUnixGroups: text("sshUnixGroups").default("[]")
});
export const userOrgRoles = pgTable(
"userOrgRoles",
{
userId: varchar("userId")
.notNull()
.references(() => users.userId, { onDelete: "cascade" }),
orgId: varchar("orgId")
.notNull()
.references(() => orgs.orgId, { onDelete: "cascade" }),
roleId: integer("roleId")
.notNull()
.references(() => roles.roleId, { onDelete: "cascade" })
},
(t) => [unique().on(t.userId, t.orgId, t.roleId)]
);
export const roleActions = pgTable("roleActions", {
roleId: integer("roleId")
.notNull()
@@ -1049,7 +1038,6 @@ export type RoleResource = InferSelectModel<typeof roleResources>;
export type UserResource = InferSelectModel<typeof userResources>;
export type UserInvite = InferSelectModel<typeof userInvites>;
export type UserOrg = InferSelectModel<typeof userOrgs>;
export type UserOrgRole = InferSelectModel<typeof userOrgRoles>;
export type ResourceSession = InferSelectModel<typeof resourceSessions>;
export type ResourcePincode = InferSelectModel<typeof resourcePincode>;
export type ResourcePassword = InferSelectModel<typeof resourcePassword>;

View File

@@ -1,12 +1,4 @@
import {
db,
loginPage,
LoginPage,
loginPageOrg,
Org,
orgs,
roles
} from "@server/db";
import { db, loginPage, LoginPage, loginPageOrg, Org, orgs, roles } from "@server/db";
import {
Resource,
ResourcePassword,
@@ -20,12 +12,13 @@ import {
resources,
roleResources,
sessions,
userOrgs,
userResources,
users,
ResourceHeaderAuthExtendedCompatibility,
resourceHeaderAuthExtendedCompatibility
} from "@server/db";
import { and, eq, inArray } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
export type ResourceWithAuth = {
resource: Resource | null;
@@ -111,15 +104,24 @@ export async function getUserSessionWithUser(
}
/**
* Get role name by role ID (for display).
* Get user organization role
*/
export async function getRoleName(roleId: number): Promise<string | null> {
const [row] = await db
.select({ name: roles.name })
.from(roles)
.where(eq(roles.roleId, roleId))
export async function getUserOrgRole(userId: string, orgId: string) {
const userOrgRole = await db
.select({
userId: userOrgs.userId,
orgId: userOrgs.orgId,
roleId: userOrgs.roleId,
isOwner: userOrgs.isOwner,
autoProvisioned: userOrgs.autoProvisioned,
roleName: roles.name
})
.from(userOrgs)
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
.limit(1);
return row?.name ?? null;
return userOrgRole.length > 0 ? userOrgRole[0] : null;
}
/**
@@ -127,7 +129,7 @@ export async function getRoleName(roleId: number): Promise<string | null> {
*/
export async function getRoleResourceAccess(
resourceId: number,
roleIds: number[]
roleId: number
) {
const roleResourceAccess = await db
.select()
@@ -135,11 +137,12 @@ export async function getRoleResourceAccess(
.where(
and(
eq(roleResources.resourceId, resourceId),
inArray(roleResources.roleId, roleIds)
eq(roleResources.roleId, roleId)
)
);
)
.limit(1);
return roleResourceAccess.length > 0 ? roleResourceAccess : null;
return roleResourceAccess.length > 0 ? roleResourceAccess[0] : null;
}
/**

View File

@@ -2,11 +2,12 @@ import { InferSelectModel } from "drizzle-orm";
import {
index,
integer,
primaryKey,
real,
sqliteTable,
text
} from "drizzle-orm/sqlite-core";
import { clients, domains, exitNodes, orgs, sessions, users } from "./schema";
import { clients, domains, exitNodes, orgs, sessions, siteResources, sites, users } from "./schema";
export const certificates = sqliteTable("certificates", {
certId: integer("certId").primaryKey({ autoIncrement: true }),
@@ -294,6 +295,45 @@ export const accessAuditLog = sqliteTable(
]
);
export const connectionAuditLog = sqliteTable(
"connectionAuditLog",
{
id: integer("id").primaryKey({ autoIncrement: true }),
sessionId: text("sessionId").notNull(),
siteResourceId: integer("siteResourceId").references(
() => siteResources.siteResourceId,
{ onDelete: "cascade" }
),
orgId: text("orgId").references(() => orgs.orgId, {
onDelete: "cascade"
}),
siteId: integer("siteId").references(() => sites.siteId, {
onDelete: "cascade"
}),
clientId: integer("clientId").references(() => clients.clientId, {
onDelete: "cascade"
}),
userId: text("userId").references(() => users.userId, {
onDelete: "cascade"
}),
sourceAddr: text("sourceAddr").notNull(),
destAddr: text("destAddr").notNull(),
protocol: text("protocol").notNull(),
startedAt: integer("startedAt").notNull(),
endedAt: integer("endedAt"),
bytesTx: integer("bytesTx"),
bytesRx: integer("bytesRx")
},
(table) => [
index("idx_accessAuditLog_startedAt").on(table.startedAt),
index("idx_accessAuditLog_org_startedAt").on(
table.orgId,
table.startedAt
),
index("idx_accessAuditLog_siteResourceId").on(table.siteResourceId)
]
);
export const approvals = sqliteTable("approvals", {
approvalId: integer("approvalId").primaryKey({ autoIncrement: true }),
timestamp: integer("timestamp").notNull(), // this is EPOCH time in seconds
@@ -318,7 +358,6 @@ export const approvals = sqliteTable("approvals", {
.notNull()
});
export const bannedEmails = sqliteTable("bannedEmails", {
email: text("email").primaryKey()
});
@@ -327,6 +366,37 @@ export const bannedIps = sqliteTable("bannedIps", {
ip: text("ip").primaryKey()
});
export const siteProvisioningKeys = sqliteTable("siteProvisioningKeys", {
siteProvisioningKeyId: text("siteProvisioningKeyId").primaryKey(),
name: text("name").notNull(),
siteProvisioningKeyHash: text("siteProvisioningKeyHash").notNull(),
lastChars: text("lastChars").notNull(),
createdAt: text("dateCreated").notNull(),
lastUsed: text("lastUsed"),
maxBatchSize: integer("maxBatchSize"), // null = no limit
numUsed: integer("numUsed").notNull().default(0),
validUntil: text("validUntil")
});
export const siteProvisioningKeyOrg = sqliteTable(
"siteProvisioningKeyOrg",
{
siteProvisioningKeyId: text("siteProvisioningKeyId")
.notNull()
.references(() => siteProvisioningKeys.siteProvisioningKeyId, {
onDelete: "cascade"
}),
orgId: text("orgId")
.notNull()
.references(() => orgs.orgId, { onDelete: "cascade" })
},
(table) => [
primaryKey({
columns: [table.siteProvisioningKeyId, table.orgId]
})
]
);
export type Approval = InferSelectModel<typeof approvals>;
export type Limit = InferSelectModel<typeof limits>;
export type Account = InferSelectModel<typeof account>;
@@ -348,3 +418,4 @@ export type LoginPage = InferSelectModel<typeof loginPage>;
export type LoginPageBranding = InferSelectModel<typeof loginPageBranding>;
export type ActionAuditLog = InferSelectModel<typeof actionAuditLog>;
export type AccessAuditLog = InferSelectModel<typeof accessAuditLog>;
export type ConnectionAuditLog = InferSelectModel<typeof connectionAuditLog>;

View File

@@ -1,12 +1,6 @@
import { randomUUID } from "crypto";
import { InferSelectModel } from "drizzle-orm";
import {
index,
integer,
sqliteTable,
text,
unique
} from "drizzle-orm/sqlite-core";
import { index, integer, sqliteTable, text } from "drizzle-orm/sqlite-core";
export const domains = sqliteTable("domains", {
domainId: text("domainId").primaryKey(),
@@ -53,6 +47,9 @@ export const orgs = sqliteTable("orgs", {
settingsLogRetentionDaysAction: integer("settingsLogRetentionDaysAction") // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year
.notNull()
.default(0),
settingsLogRetentionDaysConnection: integer("settingsLogRetentionDaysConnection") // where 0 = dont keep logs and -1 = keep forever and 9001 = end of the following year
.notNull()
.default(0),
sshCaPrivateKey: text("sshCaPrivateKey"), // Encrypted SSH CA private key (PEM format)
sshCaPublicKey: text("sshCaPublicKey"), // SSH CA public key (OpenSSH format)
isBillingOrg: integer("isBillingOrg", { mode: "boolean" }),
@@ -649,6 +646,9 @@ export const userOrgs = sqliteTable("userOrgs", {
onDelete: "cascade"
})
.notNull(),
roleId: integer("roleId")
.notNull()
.references(() => roles.roleId),
isOwner: integer("isOwner", { mode: "boolean" }).notNull().default(false),
autoProvisioned: integer("autoProvisioned", {
mode: "boolean"
@@ -703,22 +703,6 @@ export const roles = sqliteTable("roles", {
sshUnixGroups: text("sshUnixGroups").default("[]")
});
export const userOrgRoles = sqliteTable(
"userOrgRoles",
{
userId: text("userId")
.notNull()
.references(() => users.userId, { onDelete: "cascade" }),
orgId: text("orgId")
.notNull()
.references(() => orgs.orgId, { onDelete: "cascade" }),
roleId: integer("roleId")
.notNull()
.references(() => roles.roleId, { onDelete: "cascade" })
},
(t) => [unique().on(t.userId, t.orgId, t.roleId)]
);
export const roleActions = sqliteTable("roleActions", {
roleId: integer("roleId")
.notNull()
@@ -1153,7 +1137,6 @@ export type RoleResource = InferSelectModel<typeof roleResources>;
export type UserResource = InferSelectModel<typeof userResources>;
export type UserInvite = InferSelectModel<typeof userInvites>;
export type UserOrg = InferSelectModel<typeof userOrgs>;
export type UserOrgRole = InferSelectModel<typeof userOrgRoles>;
export type ResourceSession = InferSelectModel<typeof resourceSessions>;
export type ResourcePincode = InferSelectModel<typeof resourcePincode>;
export type ResourcePassword = InferSelectModel<typeof resourcePassword>;

View File

@@ -74,7 +74,7 @@ declare global {
session: Session;
userOrg?: UserOrg;
apiKeyOrg?: ApiKeyOrg;
userOrgRoleIds?: number[];
userOrgRoleId?: number;
userOrgId?: string;
userOrgIds?: string[];
remoteExitNode?: RemoteExitNode;

View File

@@ -8,6 +8,7 @@ export enum TierFeature {
LogExport = "logExport",
AccessLogs = "accessLogs", // set the retention period to none on downgrade
ActionLogs = "actionLogs", // set the retention period to none on downgrade
ConnectionLogs = "connectionLogs",
RotateCredentials = "rotateCredentials",
MaintencePage = "maintencePage", // handle downgrade
DevicePosture = "devicePosture",
@@ -16,7 +17,7 @@ export enum TierFeature {
PasswordExpirationPolicies = "passwordExpirationPolicies", // handle downgrade by setting to default duration
AutoProvisioning = "autoProvisioning", // handle downgrade by disabling auto provisioning
SshPam = "sshPam",
FullRbac = "fullRbac"
SiteProvisioningKeys = "siteProvisioningKeys" // handle downgrade by revoking keys if needed
}
export const tierMatrix: Record<TierFeature, Tier[]> = {
@@ -27,6 +28,7 @@ export const tierMatrix: Record<TierFeature, Tier[]> = {
[TierFeature.LogExport]: ["tier3", "enterprise"],
[TierFeature.AccessLogs]: ["tier2", "tier3", "enterprise"],
[TierFeature.ActionLogs]: ["tier2", "tier3", "enterprise"],
[TierFeature.ConnectionLogs]: ["tier2", "tier3", "enterprise"],
[TierFeature.RotateCredentials]: ["tier1", "tier2", "tier3", "enterprise"],
[TierFeature.MaintencePage]: ["tier1", "tier2", "tier3", "enterprise"],
[TierFeature.DevicePosture]: ["tier2", "tier3", "enterprise"],
@@ -50,5 +52,5 @@ export const tierMatrix: Record<TierFeature, Tier[]> = {
],
[TierFeature.AutoProvisioning]: ["tier1", "tier3", "enterprise"],
[TierFeature.SshPam]: ["tier1", "tier3", "enterprise"],
[TierFeature.FullRbac]: ["tier1", "tier2", "tier3", "enterprise"]
[TierFeature.SiteProvisioningKeys]: ["enterprise"]
};

View File

@@ -10,7 +10,6 @@ import {
roles,
Transaction,
userClients,
userOrgRoles,
userOrgs
} from "@server/db";
import { getUniqueClientName } from "@server/db/names";
@@ -40,36 +39,20 @@ export async function calculateUserClientsForOrgs(
return;
}
// Get all user orgs with all roles (for org list and role-based logic)
const userOrgRoleRows = await transaction
// Get all user orgs
const allUserOrgs = await transaction
.select()
.from(userOrgs)
.innerJoin(
userOrgRoles,
and(
eq(userOrgs.userId, userOrgRoles.userId),
eq(userOrgs.orgId, userOrgRoles.orgId)
)
)
.innerJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
.innerJoin(roles, eq(roles.roleId, userOrgs.roleId))
.where(eq(userOrgs.userId, userId));
const userOrgIds = [...new Set(userOrgRoleRows.map((r) => r.userOrgs.orgId))];
const orgIdToRoleRows = new Map<
string,
(typeof userOrgRoleRows)[0][]
>();
for (const r of userOrgRoleRows) {
const list = orgIdToRoleRows.get(r.userOrgs.orgId) ?? [];
list.push(r);
orgIdToRoleRows.set(r.userOrgs.orgId, list);
}
const userOrgIds = allUserOrgs.map(({ userOrgs: uo }) => uo.orgId);
// For each OLM, ensure there's a client in each org the user is in
for (const olm of userOlms) {
for (const orgId of orgIdToRoleRows.keys()) {
const roleRowsForOrg = orgIdToRoleRows.get(orgId)!;
const userOrg = roleRowsForOrg[0].userOrgs;
for (const userRoleOrg of allUserOrgs) {
const { userOrgs: userOrg, roles: role } = userRoleOrg;
const orgId = userOrg.orgId;
const [org] = await transaction
.select()
@@ -213,7 +196,7 @@ export async function calculateUserClientsForOrgs(
const requireApproval =
build !== "oss" &&
isOrgLicensed &&
roleRowsForOrg.some((r) => r.roles.requireDeviceApproval);
role.requireDeviceApproval;
const newClientData: InferInsertModel<typeof clients> = {
userId,

View File

@@ -2,6 +2,7 @@ import { db, orgs } from "@server/db";
import { cleanUpOldLogs as cleanUpOldAccessLogs } from "#dynamic/lib/logAccessAudit";
import { cleanUpOldLogs as cleanUpOldActionLogs } from "#dynamic/middlewares/logActionAudit";
import { cleanUpOldLogs as cleanUpOldRequestLogs } from "@server/routers/badger/logRequestAudit";
import { cleanUpOldLogs as cleanUpOldConnectionLogs } from "#dynamic/routers/newt";
import { gt, or } from "drizzle-orm";
import { cleanUpOldFingerprintSnapshots } from "@server/routers/olm/fingerprintingUtils";
import { build } from "@server/build";
@@ -20,14 +21,17 @@ export function initLogCleanupInterval() {
settingsLogRetentionDaysAccess:
orgs.settingsLogRetentionDaysAccess,
settingsLogRetentionDaysRequest:
orgs.settingsLogRetentionDaysRequest
orgs.settingsLogRetentionDaysRequest,
settingsLogRetentionDaysConnection:
orgs.settingsLogRetentionDaysConnection
})
.from(orgs)
.where(
or(
gt(orgs.settingsLogRetentionDaysAction, 0),
gt(orgs.settingsLogRetentionDaysAccess, 0),
gt(orgs.settingsLogRetentionDaysRequest, 0)
gt(orgs.settingsLogRetentionDaysRequest, 0),
gt(orgs.settingsLogRetentionDaysConnection, 0)
)
);
@@ -37,7 +41,8 @@ export function initLogCleanupInterval() {
orgId,
settingsLogRetentionDaysAction,
settingsLogRetentionDaysAccess,
settingsLogRetentionDaysRequest
settingsLogRetentionDaysRequest,
settingsLogRetentionDaysConnection
} = org;
if (settingsLogRetentionDaysAction > 0) {
@@ -60,6 +65,13 @@ export function initLogCleanupInterval() {
settingsLogRetentionDaysRequest
);
}
if (settingsLogRetentionDaysConnection > 0) {
await cleanUpOldConnectionLogs(
orgId,
settingsLogRetentionDaysConnection
);
}
}
await cleanUpOldFingerprintSnapshots(365);

View File

@@ -581,6 +581,7 @@ export type SubnetProxyTargetV2 = {
max: number;
protocol: "tcp" | "udp";
}[];
resourceId?: number;
};
export function generateSubnetProxyTargetV2(
@@ -617,7 +618,8 @@ export function generateSubnetProxyTargetV2(
sourcePrefixes: [],
destPrefix: destination,
portRange,
disableIcmp
disableIcmp,
resourceId: siteResource.siteResourceId,
};
}
@@ -628,7 +630,8 @@ export function generateSubnetProxyTargetV2(
destPrefix: `${siteResource.aliasAddress}/32`,
rewriteTo: destination,
portRange,
disableIcmp
disableIcmp,
resourceId: siteResource.siteResourceId,
};
}
} else if (siteResource.mode == "cidr") {
@@ -636,7 +639,8 @@ export function generateSubnetProxyTargetV2(
sourcePrefixes: [],
destPrefix: siteResource.destination,
portRange,
disableIcmp
disableIcmp,
resourceId: siteResource.siteResourceId,
};
}

View File

@@ -79,7 +79,6 @@ export const configSchema = z
.default(3001)
.transform(stoi)
.pipe(portSchema),
badger_override: z.string().optional(),
next_port: portSchema
.optional()
.default(3002)

View File

@@ -14,7 +14,6 @@ import {
siteResources,
sites,
Transaction,
userOrgRoles,
userOrgs,
userSiteResources
} from "@server/db";
@@ -78,10 +77,10 @@ export async function getClientSiteResourceAccess(
// get all of the users in these roles
const userIdsFromRoles = await trx
.select({
userId: userOrgRoles.userId
userId: userOrgs.userId
})
.from(userOrgRoles)
.where(inArray(userOrgRoles.roleId, roleIds))
.from(userOrgs)
.where(inArray(userOrgs.roleId, roleIds))
.then((rows) => rows.map((row) => row.userId));
const newAllUserIds = Array.from(
@@ -815,12 +814,12 @@ export async function rebuildClientAssociationsFromClient(
// Role-based access
const roleIds = await trx
.select({ roleId: userOrgRoles.roleId })
.from(userOrgRoles)
.select({ roleId: userOrgs.roleId })
.from(userOrgs)
.where(
and(
eq(userOrgRoles.userId, client.userId),
eq(userOrgRoles.orgId, client.orgId)
eq(userOrgs.userId, client.userId),
eq(userOrgs.orgId, client.orgId)
)
) // this needs to be locked onto this org or else cross-org access could happen
.then((rows) => rows.map((row) => row.roleId));

View File

@@ -6,7 +6,7 @@ import {
siteResources,
sites,
Transaction,
userOrgRoles,
UserOrg,
userOrgs,
userResources,
userSiteResources,
@@ -19,15 +19,9 @@ import { FeatureId } from "@server/lib/billing";
export async function assignUserToOrg(
org: Org,
values: typeof userOrgs.$inferInsert,
roleId: number,
trx: Transaction | typeof db = db
) {
const [userOrg] = await trx.insert(userOrgs).values(values).returning();
await trx.insert(userOrgRoles).values({
userId: userOrg.userId,
orgId: userOrg.orgId,
roleId
});
// calculate if the user is in any other of the orgs before we count it as an add to the billing org
if (org.billingOrgId) {
@@ -64,14 +58,6 @@ export async function removeUserFromOrg(
userId: string,
trx: Transaction | typeof db = db
) {
await trx
.delete(userOrgRoles)
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, org.orgId)
)
);
await trx
.delete(userOrgs)
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, org.orgId)));

View File

@@ -1,36 +0,0 @@
import { db, roles, userOrgRoles } from "@server/db";
import { and, eq } from "drizzle-orm";
/**
* Get all role IDs a user has in an organization.
* Returns empty array if the user has no roles in the org (callers must treat as no access).
*/
export async function getUserOrgRoleIds(
userId: string,
orgId: string
): Promise<number[]> {
const rows = await db
.select({ roleId: userOrgRoles.roleId })
.from(userOrgRoles)
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, orgId)
)
);
return rows.map((r) => r.roleId);
}
export async function getUserOrgRoles(
userId: string,
orgId: string
): Promise<{ roleId: number; roleName: string }[]> {
const rows = await db
.select({ roleId: userOrgRoles.roleId, roleName: roles.name })
.from(userOrgRoles)
.innerJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
.where(
and(eq(userOrgRoles.userId, userId), eq(userOrgRoles.orgId, orgId))
);
return rows;
}

View File

@@ -21,7 +21,8 @@ export async function getUserOrgs(
try {
const userOrganizations = await db
.select({
orgId: userOrgs.orgId
orgId: userOrgs.orgId,
roleId: userOrgs.roleId
})
.from(userOrgs)
.where(eq(userOrgs.userId, userId));

View File

@@ -17,7 +17,6 @@ export * from "./verifyAccessTokenAccess";
export * from "./requestTimeout";
export * from "./verifyClientAccess";
export * from "./verifyUserHasAction";
export * from "./verifyUserCanSetUserOrgRoles";
export * from "./verifyUserIsServerAdmin";
export * from "./verifyIsLoggedInUser";
export * from "./verifyIsLoggedInUser";
@@ -25,6 +24,7 @@ export * from "./verifyClientAccess";
export * from "./integration";
export * from "./verifyUserHasAction";
export * from "./verifyApiKeyAccess";
export * from "./verifySiteProvisioningKeyAccess";
export * from "./verifyDomainAccess";
export * from "./verifyUserIsOrgOwner";
export * from "./verifySiteResourceAccess";

View File

@@ -1,7 +1,6 @@
export * from "./verifyApiKey";
export * from "./verifyApiKeyOrgAccess";
export * from "./verifyApiKeyHasAction";
export * from "./verifyApiKeyCanSetUserOrgRoles";
export * from "./verifyApiKeySiteAccess";
export * from "./verifyApiKeyResourceAccess";
export * from "./verifyApiKeyTargetAccess";

View File

@@ -1,74 +0,0 @@
import { Request, Response, NextFunction } from "express";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import logger from "@server/logger";
import { ActionsEnum } from "@server/auth/actions";
import { db } from "@server/db";
import { apiKeyActions } from "@server/db";
import { and, eq } from "drizzle-orm";
async function apiKeyHasAction(apiKeyId: string, actionId: ActionsEnum) {
const [row] = await db
.select()
.from(apiKeyActions)
.where(
and(
eq(apiKeyActions.apiKeyId, apiKeyId),
eq(apiKeyActions.actionId, actionId)
)
);
return !!row;
}
/**
* Allows setUserOrgRoles on the key, or both addUserRole and removeUserRole.
*/
export function verifyApiKeyCanSetUserOrgRoles() {
return async function (
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
if (!req.apiKey) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"API Key not authenticated"
)
);
}
const keyId = req.apiKey.apiKeyId;
if (await apiKeyHasAction(keyId, ActionsEnum.setUserOrgRoles)) {
return next();
}
const hasAdd = await apiKeyHasAction(keyId, ActionsEnum.addUserRole);
const hasRemove = await apiKeyHasAction(
keyId,
ActionsEnum.removeUserRole
);
if (hasAdd && hasRemove) {
return next();
}
return next(
createHttpError(
HttpCode.FORBIDDEN,
"Key does not have permission perform this action"
)
);
} catch (error) {
logger.error("Error verifying API key set user org roles:", error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Error verifying key action access"
)
);
}
};
}

View File

@@ -6,7 +6,6 @@ import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { canUserAccessResource } from "@server/auth/canUserAccessResource";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyAccessTokenAccess(
req: Request,
@@ -94,10 +93,7 @@ export async function verifyAccessTokenAccess(
)
);
} else {
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
resource[0].orgId!
);
req.userOrgRoleId = req.userOrg.roleId;
req.userOrgId = resource[0].orgId!;
}
@@ -122,7 +118,7 @@ export async function verifyAccessTokenAccess(
const resourceAllowed = await canUserAccessResource({
userId,
resourceId,
roleIds: req.userOrgRoleIds ?? []
roleId: req.userOrgRoleId!
});
if (!resourceAllowed) {

View File

@@ -1,11 +1,10 @@
import { Request, Response, NextFunction } from "express";
import { db } from "@server/db";
import { roles, userOrgs } from "@server/db";
import { and, eq, inArray } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyAdmin(
req: Request,
@@ -63,29 +62,13 @@ export async function verifyAdmin(
}
}
req.userOrgRoleIds = await getUserOrgRoleIds(req.userOrg.userId, orgId!);
if (req.userOrgRoleIds.length === 0) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have Admin access"
)
);
}
const userAdminRoles = await db
const userRole = await db
.select()
.from(roles)
.where(
and(
inArray(roles.roleId, req.userOrgRoleIds),
eq(roles.isAdmin, true)
)
)
.where(eq(roles.roleId, req.userOrg.roleId))
.limit(1);
if (userAdminRoles.length === 0) {
if (userRole.length === 0 || !userRole[0].isAdmin) {
return next(
createHttpError(
HttpCode.FORBIDDEN,

View File

@@ -1,11 +1,10 @@
import { Request, Response, NextFunction } from "express";
import { db } from "@server/db";
import { userOrgs, apiKeys, apiKeyOrg } from "@server/db";
import { and, eq } from "drizzle-orm";
import { and, eq, or } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyApiKeyAccess(
req: Request,
@@ -104,10 +103,8 @@ export async function verifyApiKeyAccess(
}
}
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
orgId
);
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
return next();
} catch (error) {

View File

@@ -1,12 +1,11 @@
import { Request, Response, NextFunction } from "express";
import { Client, db } from "@server/db";
import { userOrgs, clients, roleClients, userClients } from "@server/db";
import { and, eq, inArray } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import logger from "@server/logger";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyClientAccess(
req: Request,
@@ -114,30 +113,21 @@ export async function verifyClientAccess(
}
}
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
client.orgId
);
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
req.userOrgId = client.orgId;
// Check role-based client access (any of user's roles)
const roleClientAccessList =
(req.userOrgRoleIds?.length ?? 0) > 0
? await db
.select()
.from(roleClients)
.where(
and(
eq(roleClients.clientId, client.clientId),
inArray(
roleClients.roleId,
req.userOrgRoleIds!
)
)
)
.limit(1)
: [];
const [roleClientAccess] = roleClientAccessList;
// Check role-based site access first
const [roleClientAccess] = await db
.select()
.from(roleClients)
.where(
and(
eq(roleClients.clientId, client.clientId),
eq(roleClients.roleId, userOrgRoleId)
)
)
.limit(1);
if (roleClientAccess) {
// User has access to the site through their role

View File

@@ -1,11 +1,10 @@
import { Request, Response, NextFunction } from "express";
import { db, domains, orgDomains } from "@server/db";
import { userOrgs } from "@server/db";
import { userOrgs, apiKeyOrg } from "@server/db";
import { and, eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyDomainAccess(
req: Request,
@@ -64,7 +63,7 @@ export async function verifyDomainAccess(
.where(
and(
eq(userOrgs.userId, userId),
eq(userOrgs.orgId, orgId)
eq(userOrgs.orgId, apiKeyOrg.orgId)
)
)
.limit(1);
@@ -98,7 +97,8 @@ export async function verifyDomainAccess(
}
}
req.userOrgRoleIds = await getUserOrgRoleIds(req.userOrg.userId, orgId);
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
return next();
} catch (error) {

View File

@@ -1,11 +1,10 @@
import { Request, Response, NextFunction } from "express";
import { db } from "@server/db";
import { db, orgs } from "@server/db";
import { userOrgs } from "@server/db";
import { and, eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyOrgAccess(
req: Request,
@@ -65,8 +64,8 @@ export async function verifyOrgAccess(
}
}
// User has access, attach the user's role(s) to the request for potential future use
req.userOrgRoleIds = await getUserOrgRoleIds(req.userOrg.userId, orgId);
// User has access, attach the user's role to the request for potential future use
req.userOrgRoleId = req.userOrg.roleId;
req.userOrgId = orgId;
return next();

View File

@@ -1,11 +1,10 @@
import { Request, Response, NextFunction } from "express";
import { db, Resource } from "@server/db";
import { resources, userOrgs, userResources, roleResources } from "@server/db";
import { and, eq, inArray } from "drizzle-orm";
import { and, eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyResourceAccess(
req: Request,
@@ -108,28 +107,20 @@ export async function verifyResourceAccess(
}
}
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
resource.orgId
);
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
req.userOrgId = resource.orgId;
const roleResourceAccess =
(req.userOrgRoleIds?.length ?? 0) > 0
? await db
.select()
.from(roleResources)
.where(
and(
eq(roleResources.resourceId, resource.resourceId),
inArray(
roleResources.roleId,
req.userOrgRoleIds!
)
)
)
.limit(1)
: [];
const roleResourceAccess = await db
.select()
.from(roleResources)
.where(
and(
eq(roleResources.resourceId, resource.resourceId),
eq(roleResources.roleId, userOrgRoleId)
)
)
.limit(1);
if (roleResourceAccess.length > 0) {
return next();

View File

@@ -6,7 +6,6 @@ import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import logger from "@server/logger";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyRoleAccess(
req: Request,
@@ -100,6 +99,7 @@ export async function verifyRoleAccess(
}
if (!req.userOrg) {
// get the userORg
const userOrg = await db
.select()
.from(userOrgs)
@@ -109,7 +109,7 @@ export async function verifyRoleAccess(
.limit(1);
req.userOrg = userOrg[0];
req.userOrgRoleIds = await getUserOrgRoleIds(userId, orgId!);
req.userOrgRoleId = userOrg[0].roleId;
}
if (!req.userOrg) {

View File

@@ -1,11 +1,10 @@
import { Request, Response, NextFunction } from "express";
import { db } from "@server/db";
import { sites, Site, userOrgs, userSites, roleSites, roles } from "@server/db";
import { and, eq, inArray, or } from "drizzle-orm";
import { and, eq, or } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifySiteAccess(
req: Request,
@@ -113,29 +112,21 @@ export async function verifySiteAccess(
}
}
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
site.orgId
);
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
req.userOrgId = site.orgId;
// Check role-based site access first (any of user's roles)
const roleSiteAccess =
(req.userOrgRoleIds?.length ?? 0) > 0
? await db
.select()
.from(roleSites)
.where(
and(
eq(roleSites.siteId, site.siteId),
inArray(
roleSites.roleId,
req.userOrgRoleIds!
)
)
)
.limit(1)
: [];
// Check role-based site access first
const roleSiteAccess = await db
.select()
.from(roleSites)
.where(
and(
eq(roleSites.siteId, site.siteId),
eq(roleSites.roleId, userOrgRoleId)
)
)
.limit(1);
if (roleSiteAccess.length > 0) {
// User's role has access to the site

View File

@@ -0,0 +1,131 @@
import { Request, Response, NextFunction } from "express";
import { db, userOrgs, siteProvisioningKeys, siteProvisioningKeyOrg } from "@server/db";
import { and, eq } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
export async function verifySiteProvisioningKeyAccess(
req: Request,
res: Response,
next: NextFunction
) {
try {
const userId = req.user!.userId;
const siteProvisioningKeyId = req.params.siteProvisioningKeyId;
const orgId = req.params.orgId;
if (!userId) {
return next(
createHttpError(HttpCode.UNAUTHORIZED, "User not authenticated")
);
}
if (!orgId) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Invalid organization ID")
);
}
if (!siteProvisioningKeyId) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Invalid key ID")
);
}
const [row] = await db
.select()
.from(siteProvisioningKeys)
.innerJoin(
siteProvisioningKeyOrg,
and(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyOrg.siteProvisioningKeyId
),
eq(siteProvisioningKeyOrg.orgId, orgId)
)
)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
)
.limit(1);
if (!row?.siteProvisioningKeys) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Site provisioning key with ID ${siteProvisioningKeyId} not found`
)
);
}
if (!row.siteProvisioningKeyOrg.orgId) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
`Site provisioning key with ID ${siteProvisioningKeyId} does not have an organization ID`
)
);
}
if (!req.userOrg) {
const userOrgRole = await db
.select()
.from(userOrgs)
.where(
and(
eq(userOrgs.userId, userId),
eq(
userOrgs.orgId,
row.siteProvisioningKeyOrg.orgId
)
)
)
.limit(1);
req.userOrg = userOrgRole[0];
}
if (!req.userOrg) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have access to this organization"
)
);
}
if (req.orgPolicyAllowed === undefined && req.userOrg.orgId) {
const policyCheck = await checkOrgAccessPolicy({
orgId: req.userOrg.orgId,
userId,
session: req.session
});
req.orgPolicyAllowed = policyCheck.allowed;
if (!policyCheck.allowed || policyCheck.error) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"Failed organization access policy check: " +
(policyCheck.error || "Unknown error")
)
);
}
}
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
return next();
} catch (error) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Error verifying site provisioning key access"
)
);
}
}

View File

@@ -1,12 +1,11 @@
import { Request, Response, NextFunction } from "express";
import { db, roleSiteResources, userOrgs, userSiteResources } from "@server/db";
import { siteResources } from "@server/db";
import { eq, and, inArray } from "drizzle-orm";
import { eq, and } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import logger from "@server/logger";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifySiteResourceAccess(
req: Request,
@@ -110,34 +109,23 @@ export async function verifySiteResourceAccess(
}
}
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
siteResource.orgId
);
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
req.userOrgId = siteResource.orgId;
// Attach the siteResource to the request for use in the next middleware/route
req.siteResource = siteResource;
const roleResourceAccess =
(req.userOrgRoleIds?.length ?? 0) > 0
? await db
.select()
.from(roleSiteResources)
.where(
and(
eq(
roleSiteResources.siteResourceId,
siteResourceIdNum
),
inArray(
roleSiteResources.roleId,
req.userOrgRoleIds!
)
)
)
.limit(1)
: [];
const roleResourceAccess = await db
.select()
.from(roleSiteResources)
.where(
and(
eq(roleSiteResources.siteResourceId, siteResourceIdNum),
eq(roleSiteResources.roleId, userOrgRoleId)
)
)
.limit(1);
if (roleResourceAccess.length > 0) {
return next();

View File

@@ -6,7 +6,6 @@ import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { canUserAccessResource } from "../auth/canUserAccessResource";
import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyTargetAccess(
req: Request,
@@ -100,10 +99,7 @@ export async function verifyTargetAccess(
)
);
} else {
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
resource[0].orgId!
);
req.userOrgRoleId = req.userOrg.roleId;
req.userOrgId = resource[0].orgId!;
}
@@ -130,7 +126,7 @@ export async function verifyTargetAccess(
const resourceAllowed = await canUserAccessResource({
userId,
resourceId,
roleIds: req.userOrgRoleIds ?? []
roleId: req.userOrgRoleId!
});
if (!resourceAllowed) {

View File

@@ -1,54 +0,0 @@
import { Request, Response, NextFunction } from "express";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import logger from "@server/logger";
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
/**
* Allows the new setUserOrgRoles action, or legacy permission pair addUserRole + removeUserRole.
*/
export function verifyUserCanSetUserOrgRoles() {
return async function (
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const canSet = await checkUserActionPermission(
ActionsEnum.setUserOrgRoles,
req
);
if (canSet) {
return next();
}
const canAdd = await checkUserActionPermission(
ActionsEnum.addUserRole,
req
);
const canRemove = await checkUserActionPermission(
ActionsEnum.removeUserRole,
req
);
if (canAdd && canRemove) {
return next();
}
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User does not have permission perform this action"
)
);
} catch (error) {
logger.error("Error verifying set user org roles access:", error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Error verifying role access"
)
);
}
};
}

View File

@@ -12,7 +12,7 @@ export async function verifyUserInRole(
const roleId = parseInt(
req.params.roleId || req.body.roleId || req.query.roleId
);
const userOrgRoleIds = req.userOrgRoleIds ?? [];
const userRoleId = req.userOrgRoleId;
if (isNaN(roleId)) {
return next(
@@ -20,7 +20,7 @@ export async function verifyUserInRole(
);
}
if (userOrgRoleIds.length === 0) {
if (!userRoleId) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
@@ -29,7 +29,7 @@ export async function verifyUserInRole(
);
}
if (!userOrgRoleIds.includes(roleId)) {
if (userRoleId !== roleId) {
return next(
createHttpError(
HttpCode.FORBIDDEN,

View File

@@ -14,12 +14,14 @@
import { rateLimitService } from "#private/lib/rateLimit";
import { cleanup as wsCleanup } from "#private/routers/ws";
import { flushBandwidthToDb } from "@server/routers/newt/handleReceiveBandwidthMessage";
import { flushConnectionLogToDb } from "#dynamic/routers/newt";
import { flushSiteBandwidthToDb } from "@server/routers/gerbil/receiveBandwidth";
import { stopPingAccumulator } from "@server/routers/newt/pingAccumulator";
async function cleanup() {
await stopPingAccumulator();
await flushBandwidthToDb();
await flushConnectionLogToDb();
await flushSiteBandwidthToDb();
await rateLimitService.cleanup();
await wsCleanup();
@@ -31,4 +33,4 @@ export async function initCleanup() {
// Handle process termination
process.on("SIGTERM", () => cleanup());
process.on("SIGINT", () => cleanup());
}
}

View File

@@ -13,10 +13,9 @@
import { Request, Response, NextFunction } from "express";
import { userOrgs, db, idp, idpOrg } from "@server/db";
import { and, eq } from "drizzle-orm";
import { and, eq, or } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyIdpAccess(
req: Request,
@@ -85,10 +84,8 @@ export async function verifyIdpAccess(
);
}
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
idpRes.idpOrg.orgId
);
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
return next();
} catch (error) {

View File

@@ -12,12 +12,11 @@
*/
import { Request, Response, NextFunction } from "express";
import { db, exitNodeOrgs, remoteExitNodes } from "@server/db";
import { userOrgs } from "@server/db";
import { and, eq } from "drizzle-orm";
import { db, exitNodeOrgs, exitNodes, remoteExitNodes } from "@server/db";
import { sites, userOrgs, userSites, roleSites, roles } from "@server/db";
import { and, eq, or } from "drizzle-orm";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { getUserOrgRoleIds } from "@server/lib/userOrgRoles";
export async function verifyRemoteExitNodeAccess(
req: Request,
@@ -104,10 +103,8 @@ export async function verifyRemoteExitNodeAccess(
);
}
req.userOrgRoleIds = await getUserOrgRoleIds(
req.userOrg.userId,
exitNodeOrg.orgId
);
const userOrgRoleId = req.userOrg.roleId;
req.userOrgRoleId = userOrgRoleId;
return next();
} catch (error) {

View File

@@ -0,0 +1,99 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { registry } from "@server/openApi";
import { NextFunction } from "express";
import { Request, Response } from "express";
import { OpenAPITags } from "@server/openApi";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { fromError } from "zod-validation-error";
import logger from "@server/logger";
import {
queryConnectionAuditLogsParams,
queryConnectionAuditLogsQuery,
queryConnection,
countConnectionQuery
} from "./queryConnectionAuditLog";
import { generateCSV } from "@server/routers/auditLogs/generateCSV";
import { MAX_EXPORT_LIMIT } from "@server/routers/auditLogs";
registry.registerPath({
method: "get",
path: "/org/{orgId}/logs/connection/export",
description: "Export the connection audit log for an organization as CSV",
tags: [OpenAPITags.Logs],
request: {
query: queryConnectionAuditLogsQuery,
params: queryConnectionAuditLogsParams
},
responses: {}
});
export async function exportConnectionAuditLogs(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = queryConnectionAuditLogsQuery.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error)
)
);
}
const parsedParams = queryConnectionAuditLogsParams.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error)
)
);
}
const data = { ...parsedQuery.data, ...parsedParams.data };
const [{ count }] = await countConnectionQuery(data);
if (count > MAX_EXPORT_LIMIT) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
`Export limit exceeded. Your selection contains ${count} rows, but the maximum is ${MAX_EXPORT_LIMIT} rows. Please select a shorter time range to reduce the data.`
)
);
}
const baseQuery = queryConnection(data);
const log = await baseQuery.limit(data.limit).offset(data.offset);
const csvData = generateCSV(log);
res.setHeader("Content-Type", "text/csv");
res.setHeader(
"Content-Disposition",
`attachment; filename="connection-audit-logs-${data.orgId}-${Date.now()}.csv"`
);
return res.send(csvData);
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -15,3 +15,5 @@ export * from "./queryActionAuditLog";
export * from "./exportActionAuditLog";
export * from "./queryAccessAuditLog";
export * from "./exportAccessAuditLog";
export * from "./queryConnectionAuditLog";
export * from "./exportConnectionAuditLog";

View File

@@ -0,0 +1,524 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import {
connectionAuditLog,
logsDb,
siteResources,
sites,
clients,
users,
primaryDb
} from "@server/db";
import { registry } from "@server/openApi";
import { NextFunction } from "express";
import { Request, Response } from "express";
import { eq, gt, lt, and, count, desc, inArray } from "drizzle-orm";
import { OpenAPITags } from "@server/openApi";
import { z } from "zod";
import createHttpError from "http-errors";
import HttpCode from "@server/types/HttpCode";
import { fromError } from "zod-validation-error";
import { QueryConnectionAuditLogResponse } from "@server/routers/auditLogs/types";
import response from "@server/lib/response";
import logger from "@server/logger";
import { getSevenDaysAgo } from "@app/lib/getSevenDaysAgo";
export const queryConnectionAuditLogsQuery = z.object({
// iso string just validate its a parseable date
timeStart: z
.string()
.refine((val) => !isNaN(Date.parse(val)), {
error: "timeStart must be a valid ISO date string"
})
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
.prefault(() => getSevenDaysAgo().toISOString())
.openapi({
type: "string",
format: "date-time",
description:
"Start time as ISO date string (defaults to 7 days ago)"
}),
timeEnd: z
.string()
.refine((val) => !isNaN(Date.parse(val)), {
error: "timeEnd must be a valid ISO date string"
})
.transform((val) => Math.floor(new Date(val).getTime() / 1000))
.optional()
.prefault(() => new Date().toISOString())
.openapi({
type: "string",
format: "date-time",
description:
"End time as ISO date string (defaults to current time)"
}),
protocol: z.string().optional(),
sourceAddr: z.string().optional(),
destAddr: z.string().optional(),
clientId: z
.string()
.optional()
.transform(Number)
.pipe(z.int().positive())
.optional(),
siteId: z
.string()
.optional()
.transform(Number)
.pipe(z.int().positive())
.optional(),
siteResourceId: z
.string()
.optional()
.transform(Number)
.pipe(z.int().positive())
.optional(),
userId: z.string().optional(),
limit: z
.string()
.optional()
.default("1000")
.transform(Number)
.pipe(z.int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.int().nonnegative())
});
export const queryConnectionAuditLogsParams = z.object({
orgId: z.string()
});
export const queryConnectionAuditLogsCombined =
queryConnectionAuditLogsQuery.merge(queryConnectionAuditLogsParams);
type Q = z.infer<typeof queryConnectionAuditLogsCombined>;
function getWhere(data: Q) {
return and(
gt(connectionAuditLog.startedAt, data.timeStart),
lt(connectionAuditLog.startedAt, data.timeEnd),
eq(connectionAuditLog.orgId, data.orgId),
data.protocol
? eq(connectionAuditLog.protocol, data.protocol)
: undefined,
data.sourceAddr
? eq(connectionAuditLog.sourceAddr, data.sourceAddr)
: undefined,
data.destAddr
? eq(connectionAuditLog.destAddr, data.destAddr)
: undefined,
data.clientId
? eq(connectionAuditLog.clientId, data.clientId)
: undefined,
data.siteId
? eq(connectionAuditLog.siteId, data.siteId)
: undefined,
data.siteResourceId
? eq(connectionAuditLog.siteResourceId, data.siteResourceId)
: undefined,
data.userId
? eq(connectionAuditLog.userId, data.userId)
: undefined
);
}
export function queryConnection(data: Q) {
return logsDb
.select({
sessionId: connectionAuditLog.sessionId,
siteResourceId: connectionAuditLog.siteResourceId,
orgId: connectionAuditLog.orgId,
siteId: connectionAuditLog.siteId,
clientId: connectionAuditLog.clientId,
userId: connectionAuditLog.userId,
sourceAddr: connectionAuditLog.sourceAddr,
destAddr: connectionAuditLog.destAddr,
protocol: connectionAuditLog.protocol,
startedAt: connectionAuditLog.startedAt,
endedAt: connectionAuditLog.endedAt,
bytesTx: connectionAuditLog.bytesTx,
bytesRx: connectionAuditLog.bytesRx
})
.from(connectionAuditLog)
.where(getWhere(data))
.orderBy(
desc(connectionAuditLog.startedAt),
desc(connectionAuditLog.id)
);
}
export function countConnectionQuery(data: Q) {
const countQuery = logsDb
.select({ count: count() })
.from(connectionAuditLog)
.where(getWhere(data));
return countQuery;
}
async function enrichWithDetails(
logs: Awaited<ReturnType<typeof queryConnection>>
) {
// Collect unique IDs from logs
const siteResourceIds = [
...new Set(
logs
.map((log) => log.siteResourceId)
.filter((id): id is number => id !== null && id !== undefined)
)
];
const siteIds = [
...new Set(
logs
.map((log) => log.siteId)
.filter((id): id is number => id !== null && id !== undefined)
)
];
const clientIds = [
...new Set(
logs
.map((log) => log.clientId)
.filter((id): id is number => id !== null && id !== undefined)
)
];
const userIds = [
...new Set(
logs
.map((log) => log.userId)
.filter((id): id is string => id !== null && id !== undefined)
)
];
// Fetch resource details from main database
const resourceMap = new Map<
number,
{ name: string; niceId: string }
>();
if (siteResourceIds.length > 0) {
const resourceDetails = await primaryDb
.select({
siteResourceId: siteResources.siteResourceId,
name: siteResources.name,
niceId: siteResources.niceId
})
.from(siteResources)
.where(inArray(siteResources.siteResourceId, siteResourceIds));
for (const r of resourceDetails) {
resourceMap.set(r.siteResourceId, {
name: r.name,
niceId: r.niceId
});
}
}
// Fetch site details from main database
const siteMap = new Map<number, { name: string; niceId: string }>();
if (siteIds.length > 0) {
const siteDetails = await primaryDb
.select({
siteId: sites.siteId,
name: sites.name,
niceId: sites.niceId
})
.from(sites)
.where(inArray(sites.siteId, siteIds));
for (const s of siteDetails) {
siteMap.set(s.siteId, { name: s.name, niceId: s.niceId });
}
}
// Fetch client details from main database
const clientMap = new Map<
number,
{ name: string; niceId: string; type: string }
>();
if (clientIds.length > 0) {
const clientDetails = await primaryDb
.select({
clientId: clients.clientId,
name: clients.name,
niceId: clients.niceId,
type: clients.type
})
.from(clients)
.where(inArray(clients.clientId, clientIds));
for (const c of clientDetails) {
clientMap.set(c.clientId, {
name: c.name,
niceId: c.niceId,
type: c.type
});
}
}
// Fetch user details from main database
const userMap = new Map<
string,
{ email: string | null }
>();
if (userIds.length > 0) {
const userDetails = await primaryDb
.select({
userId: users.userId,
email: users.email
})
.from(users)
.where(inArray(users.userId, userIds));
for (const u of userDetails) {
userMap.set(u.userId, { email: u.email });
}
}
// Enrich logs with details
return logs.map((log) => ({
...log,
resourceName: log.siteResourceId
? resourceMap.get(log.siteResourceId)?.name ?? null
: null,
resourceNiceId: log.siteResourceId
? resourceMap.get(log.siteResourceId)?.niceId ?? null
: null,
siteName: log.siteId
? siteMap.get(log.siteId)?.name ?? null
: null,
siteNiceId: log.siteId
? siteMap.get(log.siteId)?.niceId ?? null
: null,
clientName: log.clientId
? clientMap.get(log.clientId)?.name ?? null
: null,
clientNiceId: log.clientId
? clientMap.get(log.clientId)?.niceId ?? null
: null,
clientType: log.clientId
? clientMap.get(log.clientId)?.type ?? null
: null,
userEmail: log.userId
? userMap.get(log.userId)?.email ?? null
: null
}));
}
async function queryUniqueFilterAttributes(
timeStart: number,
timeEnd: number,
orgId: string
) {
const baseConditions = and(
gt(connectionAuditLog.startedAt, timeStart),
lt(connectionAuditLog.startedAt, timeEnd),
eq(connectionAuditLog.orgId, orgId)
);
// Get unique protocols
const uniqueProtocols = await logsDb
.selectDistinct({
protocol: connectionAuditLog.protocol
})
.from(connectionAuditLog)
.where(baseConditions);
// Get unique destination addresses
const uniqueDestAddrs = await logsDb
.selectDistinct({
destAddr: connectionAuditLog.destAddr
})
.from(connectionAuditLog)
.where(baseConditions);
// Get unique client IDs
const uniqueClients = await logsDb
.selectDistinct({
clientId: connectionAuditLog.clientId
})
.from(connectionAuditLog)
.where(baseConditions);
// Get unique resource IDs
const uniqueResources = await logsDb
.selectDistinct({
siteResourceId: connectionAuditLog.siteResourceId
})
.from(connectionAuditLog)
.where(baseConditions);
// Get unique user IDs
const uniqueUsers = await logsDb
.selectDistinct({
userId: connectionAuditLog.userId
})
.from(connectionAuditLog)
.where(baseConditions);
// Enrich client IDs with names from main database
const clientIds = uniqueClients
.map((row) => row.clientId)
.filter((id): id is number => id !== null);
let clientsWithNames: Array<{ id: number; name: string }> = [];
if (clientIds.length > 0) {
const clientDetails = await primaryDb
.select({
clientId: clients.clientId,
name: clients.name
})
.from(clients)
.where(inArray(clients.clientId, clientIds));
clientsWithNames = clientDetails.map((c) => ({
id: c.clientId,
name: c.name
}));
}
// Enrich resource IDs with names from main database
const resourceIds = uniqueResources
.map((row) => row.siteResourceId)
.filter((id): id is number => id !== null);
let resourcesWithNames: Array<{ id: number; name: string | null }> = [];
if (resourceIds.length > 0) {
const resourceDetails = await primaryDb
.select({
siteResourceId: siteResources.siteResourceId,
name: siteResources.name
})
.from(siteResources)
.where(inArray(siteResources.siteResourceId, resourceIds));
resourcesWithNames = resourceDetails.map((r) => ({
id: r.siteResourceId,
name: r.name
}));
}
// Enrich user IDs with emails from main database
const userIdsList = uniqueUsers
.map((row) => row.userId)
.filter((id): id is string => id !== null);
let usersWithEmails: Array<{ id: string; email: string | null }> = [];
if (userIdsList.length > 0) {
const userDetails = await primaryDb
.select({
userId: users.userId,
email: users.email
})
.from(users)
.where(inArray(users.userId, userIdsList));
usersWithEmails = userDetails.map((u) => ({
id: u.userId,
email: u.email
}));
}
return {
protocols: uniqueProtocols
.map((row) => row.protocol)
.filter((protocol): protocol is string => protocol !== null),
destAddrs: uniqueDestAddrs
.map((row) => row.destAddr)
.filter((addr): addr is string => addr !== null),
clients: clientsWithNames,
resources: resourcesWithNames,
users: usersWithEmails
};
}
registry.registerPath({
method: "get",
path: "/org/{orgId}/logs/connection",
description: "Query the connection audit log for an organization",
tags: [OpenAPITags.Logs],
request: {
query: queryConnectionAuditLogsQuery,
params: queryConnectionAuditLogsParams
},
responses: {}
});
export async function queryConnectionAuditLogs(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedQuery = queryConnectionAuditLogsQuery.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error)
)
);
}
const parsedParams = queryConnectionAuditLogsParams.safeParse(
req.params
);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error)
)
);
}
const data = { ...parsedQuery.data, ...parsedParams.data };
const baseQuery = queryConnection(data);
const logsRaw = await baseQuery.limit(data.limit).offset(data.offset);
// Enrich with resource, site, client, and user details
const log = await enrichWithDetails(logsRaw);
const totalCountResult = await countConnectionQuery(data);
const totalCount = totalCountResult[0].count;
const filterAttributes = await queryUniqueFilterAttributes(
data.timeStart,
data.timeEnd,
data.orgId
);
return response<QueryConnectionAuditLogResponse>(res, {
data: {
log: log,
pagination: {
total: totalCount,
limit: data.limit,
offset: data.offset
},
filterAttributes
},
success: true,
error: false,
message: "Connection audit logs retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -26,8 +26,9 @@ import {
orgs,
resources,
roles,
siteResources,
userOrgRoles
siteProvisioningKeyOrg,
siteProvisioningKeys,
siteResources
} from "@server/db";
import { and, eq } from "drizzle-orm";
@@ -292,8 +293,8 @@ async function disableFeature(
await disableSshPam(orgId);
break;
case TierFeature.FullRbac:
await disableFullRbac(orgId);
case TierFeature.SiteProvisioningKeys:
await disableSiteProvisioningKeys(orgId);
break;
default:
@@ -331,8 +332,55 @@ async function disableSshPam(orgId: string): Promise<void> {
);
}
async function disableFullRbac(orgId: string): Promise<void> {
logger.info(`Disabled full RBAC for org ${orgId}`);
async function disableSiteProvisioningKeys(orgId: string): Promise<void> {
const rows = await db
.select({
siteProvisioningKeyId:
siteProvisioningKeyOrg.siteProvisioningKeyId
})
.from(siteProvisioningKeyOrg)
.where(eq(siteProvisioningKeyOrg.orgId, orgId));
for (const { siteProvisioningKeyId } of rows) {
await db.transaction(async (trx) => {
await trx
.delete(siteProvisioningKeyOrg)
.where(
and(
eq(
siteProvisioningKeyOrg.siteProvisioningKeyId,
siteProvisioningKeyId
),
eq(siteProvisioningKeyOrg.orgId, orgId)
)
);
const remaining = await trx
.select()
.from(siteProvisioningKeyOrg)
.where(
eq(
siteProvisioningKeyOrg.siteProvisioningKeyId,
siteProvisioningKeyId
)
);
if (remaining.length === 0) {
await trx
.delete(siteProvisioningKeys)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
);
}
});
}
logger.info(
`Removed site provisioning keys for org ${orgId} after tier downgrade`
);
}
async function disableLoginPageBranding(orgId: string): Promise<void> {

View File

@@ -26,7 +26,7 @@ import * as misc from "#private/routers/misc";
import * as reKey from "#private/routers/re-key";
import * as approval from "#private/routers/approvals";
import * as ssh from "#private/routers/ssh";
import * as user from "#private/routers/user";
import * as siteProvisioning from "#private/routers/siteProvisioning";
import {
verifyOrgAccess,
@@ -35,9 +35,7 @@ import {
verifySiteAccess,
verifyClientAccess,
verifyLimits,
verifyRoleAccess,
verifyUserAccess,
verifyUserCanSetUserOrgRoles
verifySiteProvisioningKeyAccess
} from "@server/middlewares";
import { ActionsEnum } from "@server/auth/actions";
import {
@@ -482,6 +480,25 @@ authenticated.get(
logs.exportAccessAuditLogs
);
authenticated.get(
"/org/:orgId/logs/connection",
verifyValidLicense,
verifyValidSubscription(tierMatrix.connectionLogs),
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.exportLogs),
logs.queryConnectionAuditLogs
);
authenticated.get(
"/org/:orgId/logs/connection/export",
verifyValidLicense,
verifyValidSubscription(tierMatrix.logExport),
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.exportLogs),
logActionAudit(ActionsEnum.exportLogs),
logs.exportConnectionAuditLogs
);
authenticated.post(
"/re-key/:clientId/regenerate-client-secret",
verifyClientAccess, // this is first to set the org id
@@ -523,32 +540,44 @@ authenticated.post(
ssh.signSshKey
);
authenticated.post(
"/user/:userId/add-role/:roleId",
verifyRoleAccess,
verifyUserAccess,
authenticated.put(
"/org/:orgId/site-provisioning-key",
verifyValidLicense,
verifyValidSubscription(tierMatrix.siteProvisioningKeys),
verifyOrgAccess,
verifyLimits,
verifyUserHasAction(ActionsEnum.addUserRole),
logActionAudit(ActionsEnum.addUserRole),
user.addUserRole
verifyUserHasAction(ActionsEnum.createSiteProvisioningKey),
logActionAudit(ActionsEnum.createSiteProvisioningKey),
siteProvisioning.createSiteProvisioningKey
);
authenticated.get(
"/org/:orgId/site-provisioning-keys",
verifyValidLicense,
verifyValidSubscription(tierMatrix.siteProvisioningKeys),
verifyOrgAccess,
verifyUserHasAction(ActionsEnum.listSiteProvisioningKeys),
siteProvisioning.listSiteProvisioningKeys
);
authenticated.delete(
"/user/:userId/remove-role/:roleId",
verifyRoleAccess,
verifyUserAccess,
verifyLimits,
verifyUserHasAction(ActionsEnum.removeUserRole),
logActionAudit(ActionsEnum.removeUserRole),
user.removeUserRole
"/org/:orgId/site-provisioning-key/:siteProvisioningKeyId",
verifyValidLicense,
verifyValidSubscription(tierMatrix.siteProvisioningKeys),
verifyOrgAccess,
verifySiteProvisioningKeyAccess,
verifyUserHasAction(ActionsEnum.deleteSiteProvisioningKey),
logActionAudit(ActionsEnum.deleteSiteProvisioningKey),
siteProvisioning.deleteSiteProvisioningKey
);
authenticated.post(
"/user/:userId/org/:orgId/roles",
authenticated.patch(
"/org/:orgId/site-provisioning-key/:siteProvisioningKeyId",
verifyValidLicense,
verifyValidSubscription(tierMatrix.siteProvisioningKeys),
verifyOrgAccess,
verifyUserAccess,
verifyLimits,
verifyUserCanSetUserOrgRoles(),
logActionAudit(ActionsEnum.setUserOrgRoles),
user.setUserOrgRoles
verifySiteProvisioningKeyAccess,
verifyUserHasAction(ActionsEnum.updateSiteProvisioningKey),
logActionAudit(ActionsEnum.updateSiteProvisioningKey),
siteProvisioning.updateSiteProvisioningKey
);

View File

@@ -52,9 +52,7 @@ import {
userOrgs,
roleResources,
userResources,
resourceRules,
userOrgRoles,
roles
resourceRules
} from "@server/db";
import { eq, and, inArray, isNotNull, ne } from "drizzle-orm";
import { response } from "@server/lib/response";
@@ -106,13 +104,6 @@ const getUserOrgSessionVerifySchema = z.strictObject({
sessionId: z.string().min(1, "Session ID is required")
});
const getRoleNameParamsSchema = z.strictObject({
roleId: z
.string()
.transform(Number)
.pipe(z.int().positive("Role ID must be a positive integer"))
});
const getRoleResourceAccessParamsSchema = z.strictObject({
roleId: z
.string()
@@ -124,23 +115,6 @@ const getRoleResourceAccessParamsSchema = z.strictObject({
.pipe(z.int().positive("Resource ID must be a positive integer"))
});
const getResourceAccessParamsSchema = z.strictObject({
resourceId: z
.string()
.transform(Number)
.pipe(z.int().positive("Resource ID must be a positive integer"))
});
const getResourceAccessQuerySchema = z.strictObject({
roleIds: z
.union([z.array(z.string()), z.string()])
.transform((val) =>
(Array.isArray(val) ? val : [val])
.map(Number)
.filter((n) => !isNaN(n))
)
});
const getUserResourceAccessParamsSchema = z.strictObject({
userId: z.string().min(1, "User ID is required"),
resourceId: z
@@ -786,7 +760,7 @@ hybridRouter.get(
// Get user organization role
hybridRouter.get(
"/user/:userId/org/:orgId/roles",
"/user/:userId/org/:orgId/role",
async (req: Request, res: Response, next: NextFunction) => {
try {
const parsedParams = getUserOrgRoleParamsSchema.safeParse(
@@ -822,129 +796,23 @@ hybridRouter.get(
);
}
const userOrgRoleRows = await db
.select({ roleId: userOrgRoles.roleId, roleName: roles.name })
.from(userOrgRoles)
.innerJoin(roles, eq(roles.roleId, userOrgRoles.roleId))
const userOrgRole = await db
.select()
.from(userOrgs)
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, orgId)
)
);
logger.debug(`User ${userId} has roles in org ${orgId}:`, userOrgRoleRows);
return response<{ roleId: number, roleName: string }[]>(res, {
data: userOrgRoleRows,
success: true,
error: false,
message:
userOrgRoleRows.length > 0
? "User org roles retrieved successfully"
: "User has no roles in this organization",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to get user org role"
and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId))
)
);
}
}
);
.limit(1);
// DEPRICATED Get user organization role
// used for backward compatibility with old remote nodes
hybridRouter.get(
"/user/:userId/org/:orgId/role", // <- note the missing s
async (req: Request, res: Response, next: NextFunction) => {
try {
const parsedParams = getUserOrgRoleParamsSchema.safeParse(
req.params
);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const result = userOrgRole.length > 0 ? userOrgRole[0] : null;
const { userId, orgId } = parsedParams.data;
const remoteExitNode = req.remoteExitNode;
if (!remoteExitNode || !remoteExitNode.exitNodeId) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Remote exit node not found"
)
);
}
if (await checkExitNodeOrg(remoteExitNode.exitNodeId, orgId)) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"User is not authorized to access this organization"
)
);
}
// get the roles on the user
const userOrgRoleRows = await db
.select({ roleId: userOrgRoles.roleId })
.from(userOrgRoles)
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, orgId)
)
);
const roleIds = userOrgRoleRows.map((r) => r.roleId);
let roleId: number | null = null;
if (userOrgRoleRows.length === 0) {
// User has no roles in this organization
roleId = null;
} else if (userOrgRoleRows.length === 1) {
// User has exactly one role, return it
roleId = userOrgRoleRows[0].roleId;
} else {
// User has multiple roles
// Check if any of these roles are also assigned to a resource
// If we find a match, prefer that role; otherwise return the first role
// Get all resources that have any of these roles assigned
const roleResourceMatches = await db
.select({ roleId: roleResources.roleId })
.from(roleResources)
.where(inArray(roleResources.roleId, roleIds))
.limit(1);
if (roleResourceMatches.length > 0) {
// Return the first role that's also on a resource
roleId = roleResourceMatches[0].roleId;
} else {
// No resource match found, return the first role
roleId = userOrgRoleRows[0].roleId;
}
}
return response<{ roleId: number | null }>(res, {
data: { roleId },
return response<typeof userOrgs.$inferSelect | null>(res, {
data: result,
success: true,
error: false,
message:
roleIds.length > 0
? "User org roles retrieved successfully"
: "User has no roles in this organization",
message: result
? "User org role retrieved successfully"
: "User org role not found",
status: HttpCode.OK
});
} catch (error) {
@@ -1022,60 +890,6 @@ hybridRouter.get(
}
);
// Get role name by ID
hybridRouter.get(
"/role/:roleId/name",
async (req: Request, res: Response, next: NextFunction) => {
try {
const parsedParams = getRoleNameParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { roleId } = parsedParams.data;
const remoteExitNode = req.remoteExitNode;
if (!remoteExitNode?.exitNodeId) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Remote exit node not found"
)
);
}
const [role] = await db
.select({ name: roles.name })
.from(roles)
.where(eq(roles.roleId, roleId))
.limit(1);
return response<string | null>(res, {
data: role?.name ?? null,
success: true,
error: false,
message: role
? "Role name retrieved successfully"
: "Role not found",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to get role name"
)
);
}
}
);
// Check if role has access to resource
hybridRouter.get(
"/role/:roleId/resource/:resourceId/access",
@@ -1161,101 +975,6 @@ hybridRouter.get(
}
);
// Check if role has access to resource
hybridRouter.get(
"/resource/:resourceId/access",
async (req: Request, res: Response, next: NextFunction) => {
try {
const parsedParams = getResourceAccessParamsSchema.safeParse(
req.params
);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { resourceId } = parsedParams.data;
const parsedQuery = getResourceAccessQuerySchema.safeParse(
req.query
);
const roleIds = parsedQuery.success ? parsedQuery.data.roleIds : [];
const remoteExitNode = req.remoteExitNode;
if (!remoteExitNode?.exitNodeId) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Remote exit node not found"
)
);
}
const [resource] = await db
.select()
.from(resources)
.where(eq(resources.resourceId, resourceId))
.limit(1);
if (
await checkExitNodeOrg(
remoteExitNode.exitNodeId,
resource.orgId
)
) {
// If the exit node is not allowed for the org, return an error
return next(
createHttpError(
HttpCode.FORBIDDEN,
"Exit node not allowed for this organization"
)
);
}
const roleResourceAccess = await db
.select({
resourceId: roleResources.resourceId,
roleId: roleResources.roleId
})
.from(roleResources)
.where(
and(
eq(roleResources.resourceId, resourceId),
inArray(roleResources.roleId, roleIds)
)
);
const result =
roleResourceAccess.length > 0 ? roleResourceAccess : null;
return response<{ resourceId: number; roleId: number }[] | null>(
res,
{
data: result,
success: true,
error: false,
message: result
? "Role resource access retrieved successfully"
: "Role resource access not found",
status: HttpCode.OK
}
);
} catch (error) {
logger.error(error);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to get role resource access"
)
);
}
}
);
// Check if user has direct access to resource
hybridRouter.get(
"/user/:userId/resource/:resourceId/access",
@@ -2154,8 +1873,7 @@ hybridRouter.post(
// userAgent: data.userAgent, // TODO: add this
// headers: data.body.headers,
// query: data.body.query,
originalRequestURL:
sanitizeString(logEntry.originalRequestURL) ?? "",
originalRequestURL: sanitizeString(logEntry.originalRequestURL) ?? "",
scheme: sanitizeString(logEntry.scheme) ?? "",
host: sanitizeString(logEntry.host) ?? "",
path: sanitizeString(logEntry.path) ?? "",

View File

@@ -20,11 +20,8 @@ import {
verifyApiKeyIsRoot,
verifyApiKeyOrgAccess,
verifyApiKeyIdpAccess,
verifyApiKeyRoleAccess,
verifyApiKeyUserAccess,
verifyLimits
} from "@server/middlewares";
import * as user from "#private/routers/user";
import {
verifyValidSubscription,
verifyValidLicense
@@ -94,6 +91,25 @@ authenticated.get(
logs.exportAccessAuditLogs
);
authenticated.get(
"/org/:orgId/logs/connection",
verifyValidLicense,
verifyValidSubscription(tierMatrix.connectionLogs),
verifyApiKeyOrgAccess,
verifyApiKeyHasAction(ActionsEnum.exportLogs),
logs.queryConnectionAuditLogs
);
authenticated.get(
"/org/:orgId/logs/connection/export",
verifyValidLicense,
verifyValidSubscription(tierMatrix.logExport),
verifyApiKeyOrgAccess,
verifyApiKeyHasAction(ActionsEnum.exportLogs),
logActionAudit(ActionsEnum.exportLogs),
logs.exportConnectionAuditLogs
);
authenticated.put(
"/org/:orgId/idp/oidc",
verifyValidLicense,
@@ -143,23 +159,3 @@ authenticated.get(
verifyApiKeyHasAction(ActionsEnum.listIdps),
orgIdp.listOrgIdps
);
authenticated.post(
"/user/:userId/add-role/:roleId",
verifyApiKeyRoleAccess,
verifyApiKeyUserAccess,
verifyLimits,
verifyApiKeyHasAction(ActionsEnum.addUserRole),
logActionAudit(ActionsEnum.addUserRole),
user.addUserRole
);
authenticated.delete(
"/user/:userId/remove-role/:roleId",
verifyApiKeyRoleAccess,
verifyApiKeyUserAccess,
verifyLimits,
verifyApiKeyHasAction(ActionsEnum.removeUserRole),
logActionAudit(ActionsEnum.removeUserRole),
user.removeUserRole
);

View File

@@ -0,0 +1,394 @@
import { db, logsDb } from "@server/db";
import { MessageHandler } from "@server/routers/ws";
import { connectionAuditLog, sites, Newt, clients, orgs } from "@server/db";
import { and, eq, lt, inArray } from "drizzle-orm";
import logger from "@server/logger";
import { inflate } from "zlib";
import { promisify } from "util";
import { calculateCutoffTimestamp } from "@server/lib/cleanupLogs";
const zlibInflate = promisify(inflate);
// Retry configuration for deadlock handling
const MAX_RETRIES = 3;
const BASE_DELAY_MS = 50;
// How often to flush accumulated connection log data to the database
const FLUSH_INTERVAL_MS = 30_000; // 30 seconds
// Maximum number of records to buffer before forcing a flush
const MAX_BUFFERED_RECORDS = 500;
// Maximum number of records to insert in a single batch
const INSERT_BATCH_SIZE = 100;
interface ConnectionSessionData {
sessionId: string;
resourceId: number;
sourceAddr: string;
destAddr: string;
protocol: string;
startedAt: string; // ISO 8601 timestamp
endedAt?: string; // ISO 8601 timestamp
bytesTx?: number;
bytesRx?: number;
}
interface ConnectionLogRecord {
sessionId: string;
siteResourceId: number;
orgId: string;
siteId: number;
clientId: number | null;
userId: string | null;
sourceAddr: string;
destAddr: string;
protocol: string;
startedAt: number; // epoch seconds
endedAt: number | null;
bytesTx: number | null;
bytesRx: number | null;
}
// In-memory buffer of records waiting to be flushed
let buffer: ConnectionLogRecord[] = [];
/**
* Check if an error is a deadlock error
*/
function isDeadlockError(error: any): boolean {
return (
error?.code === "40P01" ||
error?.cause?.code === "40P01" ||
(error?.message && error.message.includes("deadlock"))
);
}
/**
* Execute a function with retry logic for deadlock handling
*/
async function withDeadlockRetry<T>(
operation: () => Promise<T>,
context: string
): Promise<T> {
let attempt = 0;
while (true) {
try {
return await operation();
} catch (error: any) {
if (isDeadlockError(error) && attempt < MAX_RETRIES) {
attempt++;
const baseDelay = Math.pow(2, attempt - 1) * BASE_DELAY_MS;
const jitter = Math.random() * baseDelay;
const delay = baseDelay + jitter;
logger.warn(
`Deadlock detected in ${context}, retrying attempt ${attempt}/${MAX_RETRIES} after ${delay.toFixed(0)}ms`
);
await new Promise((resolve) => setTimeout(resolve, delay));
continue;
}
throw error;
}
}
}
/**
* Decompress a base64-encoded zlib-compressed string into parsed JSON.
*/
async function decompressConnectionLog(
compressed: string
): Promise<ConnectionSessionData[]> {
const compressedBuffer = Buffer.from(compressed, "base64");
const decompressed = await zlibInflate(compressedBuffer);
const jsonString = decompressed.toString("utf-8");
const parsed = JSON.parse(jsonString);
if (!Array.isArray(parsed)) {
throw new Error("Decompressed connection log data is not an array");
}
return parsed;
}
/**
* Convert an ISO 8601 timestamp string to epoch seconds.
* Returns null if the input is falsy.
*/
function toEpochSeconds(isoString: string | undefined | null): number | null {
if (!isoString) {
return null;
}
const ms = new Date(isoString).getTime();
if (isNaN(ms)) {
return null;
}
return Math.floor(ms / 1000);
}
/**
* Flush all buffered connection log records to the database.
*
* Swaps out the buffer before writing so that any records added during the
* flush are captured in the new buffer rather than being lost. Entries that
* fail to write are re-queued back into the buffer so they will be retried
* on the next flush.
*
* This function is exported so that the application's graceful-shutdown
* cleanup handler can call it before the process exits.
*/
export async function flushConnectionLogToDb(): Promise<void> {
if (buffer.length === 0) {
return;
}
// Atomically swap out the buffer so new data keeps flowing in
const snapshot = buffer;
buffer = [];
logger.debug(
`Flushing ${snapshot.length} connection log record(s) to the database`
);
// Insert in batches to avoid overly large SQL statements
for (let i = 0; i < snapshot.length; i += INSERT_BATCH_SIZE) {
const batch = snapshot.slice(i, i + INSERT_BATCH_SIZE);
try {
await withDeadlockRetry(async () => {
await logsDb.insert(connectionAuditLog).values(batch);
}, `flush connection log batch (${batch.length} records)`);
} catch (error) {
logger.error(
`Failed to flush connection log batch of ${batch.length} records:`,
error
);
// Re-queue the failed batch so it is retried on the next flush
buffer = [...batch, ...buffer];
// Cap buffer to prevent unbounded growth if DB is unreachable
if (buffer.length > MAX_BUFFERED_RECORDS * 5) {
const dropped = buffer.length - MAX_BUFFERED_RECORDS * 5;
buffer = buffer.slice(0, MAX_BUFFERED_RECORDS * 5);
logger.warn(
`Connection log buffer overflow, dropped ${dropped} oldest records`
);
}
// Stop trying further batches from this snapshot — they'll be
// picked up by the next flush via the re-queued records above
const remaining = snapshot.slice(i + INSERT_BATCH_SIZE);
if (remaining.length > 0) {
buffer = [...remaining, ...buffer];
}
break;
}
}
}
const flushTimer = setInterval(async () => {
try {
await flushConnectionLogToDb();
} catch (error) {
logger.error(
"Unexpected error during periodic connection log flush:",
error
);
}
}, FLUSH_INTERVAL_MS);
// Calling unref() means this timer will not keep the Node.js event loop alive
// on its own — the process can still exit normally when there is no other work
// left. The graceful-shutdown path will call flushConnectionLogToDb() explicitly
// before process.exit(), so no data is lost.
flushTimer.unref();
export async function cleanUpOldLogs(orgId: string, retentionDays: number) {
const cutoffTimestamp = calculateCutoffTimestamp(retentionDays);
try {
await logsDb
.delete(connectionAuditLog)
.where(
and(
lt(connectionAuditLog.startedAt, cutoffTimestamp),
eq(connectionAuditLog.orgId, orgId)
)
);
// logger.debug(
// `Cleaned up connection audit logs older than ${retentionDays} days`
// );
} catch (error) {
logger.error("Error cleaning up old connection audit logs:", error);
}
}
export const handleConnectionLogMessage: MessageHandler = async (context) => {
const { message, client } = context;
const newt = client as Newt;
if (!newt) {
logger.warn("Connection log received but no newt client in context");
return;
}
if (!newt.siteId) {
logger.warn("Connection log received but newt has no siteId");
return;
}
if (!message.data?.compressed) {
logger.warn("Connection log message missing compressed data");
return;
}
// Look up the org for this site
const [site] = await db
.select({ orgId: sites.orgId, orgSubnet: orgs.subnet })
.from(sites)
.innerJoin(orgs, eq(sites.orgId, orgs.orgId))
.where(eq(sites.siteId, newt.siteId));
if (!site) {
logger.warn(
`Connection log received but site ${newt.siteId} not found in database`
);
return;
}
const orgId = site.orgId;
// Extract the CIDR suffix (e.g. "/16") from the org subnet so we can
// reconstruct the exact subnet string stored on each client record.
const cidrSuffix = site.orgSubnet?.includes("/")
? site.orgSubnet.substring(site.orgSubnet.indexOf("/"))
: null;
let sessions: ConnectionSessionData[];
try {
sessions = await decompressConnectionLog(message.data.compressed);
} catch (error) {
logger.error("Failed to decompress connection log data:", error);
return;
}
if (sessions.length === 0) {
return;
}
logger.debug(`Sessions: ${JSON.stringify(sessions)}`)
// Build a map from sourceAddr → { clientId, userId } by querying clients
// whose subnet field matches exactly. Client subnets are stored with the
// org's CIDR suffix (e.g. "100.90.128.5/16"), so we reconstruct that from
// each unique sourceAddr + the org's CIDR suffix and do a targeted IN query.
const ipToClient = new Map<string, { clientId: number; userId: string | null }>();
if (cidrSuffix) {
// Collect unique source addresses so we only query for what we need
const uniqueSourceAddrs = new Set<string>();
for (const session of sessions) {
if (session.sourceAddr) {
uniqueSourceAddrs.add(session.sourceAddr);
}
}
if (uniqueSourceAddrs.size > 0) {
// Construct the exact subnet strings as stored in the DB
const subnetQueries = Array.from(uniqueSourceAddrs).map(
(addr) => {
// Strip port if present (e.g. "100.90.128.1:38004" → "100.90.128.1")
const ip = addr.includes(":") ? addr.split(":")[0] : addr;
return `${ip}${cidrSuffix}`;
}
);
logger.debug(`Subnet queries: ${JSON.stringify(subnetQueries)}`);
const matchedClients = await db
.select({
clientId: clients.clientId,
userId: clients.userId,
subnet: clients.subnet
})
.from(clients)
.where(
and(
eq(clients.orgId, orgId),
inArray(clients.subnet, subnetQueries)
)
);
for (const c of matchedClients) {
const ip = c.subnet.split("/")[0];
logger.debug(`Client ${c.clientId} subnet ${c.subnet} matches ${ip}`);
ipToClient.set(ip, { clientId: c.clientId, userId: c.userId });
}
}
}
// Convert to DB records and add to the buffer
for (const session of sessions) {
// Validate required fields
if (
!session.sessionId ||
!session.resourceId ||
!session.sourceAddr ||
!session.destAddr ||
!session.protocol
) {
logger.debug(
`Skipping connection log session with missing required fields: ${JSON.stringify(session)}`
);
continue;
}
const startedAt = toEpochSeconds(session.startedAt);
if (startedAt === null) {
logger.debug(
`Skipping connection log session with invalid startedAt: ${session.startedAt}`
);
continue;
}
// Match the source address to a client. The sourceAddr is the
// client's IP on the WireGuard network, which corresponds to the IP
// portion of the client's subnet CIDR (e.g. "100.90.128.5/24").
// Strip port if present (e.g. "100.90.128.1:38004" → "100.90.128.1")
const sourceIp = session.sourceAddr.includes(":") ? session.sourceAddr.split(":")[0] : session.sourceAddr;
const clientInfo = ipToClient.get(sourceIp) ?? null;
buffer.push({
sessionId: session.sessionId,
siteResourceId: session.resourceId,
orgId,
siteId: newt.siteId,
clientId: clientInfo?.clientId ?? null,
userId: clientInfo?.userId ?? null,
sourceAddr: session.sourceAddr,
destAddr: session.destAddr,
protocol: session.protocol,
startedAt,
endedAt: toEpochSeconds(session.endedAt),
bytesTx: session.bytesTx ?? null,
bytesRx: session.bytesRx ?? null
});
}
logger.debug(
`Buffered ${sessions.length} connection log session(s) from newt ${newt.newtId} (site ${newt.siteId})`
);
// If the buffer has grown large enough, trigger an immediate flush
if (buffer.length >= MAX_BUFFERED_RECORDS) {
// Fire and forget — errors are handled inside flushConnectionLogToDb
flushConnectionLogToDb().catch((error) => {
logger.error(
"Unexpected error during size-triggered connection log flush:",
error
);
});
}
};

View File

@@ -0,0 +1 @@
export * from "./handleConnectionLogMessage";

View File

@@ -14,7 +14,7 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { userOrgs, userOrgRoles, users, roles, orgs } from "@server/db";
import { userOrgs, users, roles, orgs } from "@server/db";
import { eq, and, or } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
@@ -95,14 +95,7 @@ async function getOrgAdmins(orgId: string) {
})
.from(userOrgs)
.innerJoin(users, eq(userOrgs.userId, users.userId))
.leftJoin(
userOrgRoles,
and(
eq(userOrgs.userId, userOrgRoles.userId),
eq(userOrgs.orgId, userOrgRoles.orgId)
)
)
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
.where(
and(
eq(userOrgs.orgId, orgId),
@@ -110,11 +103,8 @@ async function getOrgAdmins(orgId: string) {
)
);
// Dedupe by userId (user may have multiple roles)
const byUserId = new Map(
admins.map((a) => [a.userId, a])
);
const orgAdmins = Array.from(byUserId.values()).filter(
// Filter to only include users with verified emails
const orgAdmins = admins.filter(
(admin) => admin.email && admin.email.length > 0
);

View File

@@ -79,7 +79,7 @@ export async function createRemoteExitNode(
const { remoteExitNodeId, secret } = parsedBody.data;
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
if (req.user && !req.userOrgRoleId) {
return next(
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
);

View File

@@ -0,0 +1,146 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { NextFunction, Request, Response } from "express";
import { db, siteProvisioningKeyOrg, siteProvisioningKeys } from "@server/db";
import HttpCode from "@server/types/HttpCode";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import createHttpError from "http-errors";
import response from "@server/lib/response";
import moment from "moment";
import {
generateId,
generateIdFromEntropySize
} from "@server/auth/sessions/app";
import logger from "@server/logger";
import { hashPassword } from "@server/auth/password";
import type { CreateSiteProvisioningKeyResponse } from "@server/routers/siteProvisioning/types";
const paramsSchema = z.object({
orgId: z.string().nonempty()
});
const bodySchema = z
.strictObject({
name: z.string().min(1).max(255),
maxBatchSize: z.union([
z.null(),
z.coerce.number().int().positive().max(1_000_000)
]),
validUntil: z.string().max(255).optional()
})
.superRefine((data, ctx) => {
const v = data.validUntil;
if (v == null || v.trim() === "") {
return;
}
if (Number.isNaN(Date.parse(v))) {
ctx.addIssue({
code: "custom",
message: "Invalid validUntil",
path: ["validUntil"]
});
}
});
export type CreateSiteProvisioningKeyBody = z.infer<typeof bodySchema>;
export async function createSiteProvisioningKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { orgId } = parsedParams.data;
const { name, maxBatchSize } = parsedBody.data;
const vuRaw = parsedBody.data.validUntil;
const validUntil =
vuRaw == null || vuRaw.trim() === ""
? null
: new Date(Date.parse(vuRaw)).toISOString();
const siteProvisioningKeyId = `spk-${generateId(15)}`;
const siteProvisioningKey = generateIdFromEntropySize(25);
const siteProvisioningKeyHash = await hashPassword(siteProvisioningKey);
const lastChars = siteProvisioningKey.slice(-4);
const createdAt = moment().toISOString();
const provisioningKey = `${siteProvisioningKeyId}.${siteProvisioningKey}`;
await db.transaction(async (trx) => {
await trx.insert(siteProvisioningKeys).values({
siteProvisioningKeyId,
name,
siteProvisioningKeyHash,
createdAt,
lastChars,
lastUsed: null,
maxBatchSize,
numUsed: 0,
validUntil
});
await trx.insert(siteProvisioningKeyOrg).values({
siteProvisioningKeyId,
orgId
});
});
try {
return response<CreateSiteProvisioningKeyResponse>(res, {
data: {
siteProvisioningKeyId,
orgId,
name,
siteProvisioningKey: provisioningKey,
lastChars,
createdAt,
lastUsed: null,
maxBatchSize,
numUsed: 0,
validUntil
},
success: true,
error: false,
message: "Site provisioning key created",
status: HttpCode.CREATED
});
} catch (e) {
logger.error(e);
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to create site provisioning key"
)
);
}
}

View File

@@ -0,0 +1,129 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import {
db,
siteProvisioningKeyOrg,
siteProvisioningKeys
} 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";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
const paramsSchema = z.object({
siteProvisioningKeyId: z.string().nonempty(),
orgId: z.string().nonempty()
});
export async function deleteSiteProvisioningKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { siteProvisioningKeyId, orgId } = parsedParams.data;
const [row] = await db
.select()
.from(siteProvisioningKeys)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
)
.innerJoin(
siteProvisioningKeyOrg,
and(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyOrg.siteProvisioningKeyId
),
eq(siteProvisioningKeyOrg.orgId, orgId)
)
)
.limit(1);
if (!row) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Site provisioning key with ID ${siteProvisioningKeyId} not found`
)
);
}
await db.transaction(async (trx) => {
await trx
.delete(siteProvisioningKeyOrg)
.where(
and(
eq(
siteProvisioningKeyOrg.siteProvisioningKeyId,
siteProvisioningKeyId
),
eq(siteProvisioningKeyOrg.orgId, orgId)
)
);
const siteProvisioningKeyOrgs = await trx
.select()
.from(siteProvisioningKeyOrg)
.where(
eq(
siteProvisioningKeyOrg.siteProvisioningKeyId,
siteProvisioningKeyId
)
);
if (siteProvisioningKeyOrgs.length === 0) {
await trx
.delete(siteProvisioningKeys)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
);
}
});
return response(res, {
data: null,
success: true,
error: false,
message: "Site provisioning key deleted successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -11,6 +11,7 @@
* This file is not licensed under the AGPLv3.
*/
export * from "./addUserRole";
export * from "./removeUserRole";
export * from "./setUserOrgRoles";
export * from "./createSiteProvisioningKey";
export * from "./listSiteProvisioningKeys";
export * from "./deleteSiteProvisioningKey";
export * from "./updateSiteProvisioningKey";

View File

@@ -0,0 +1,126 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import {
db,
siteProvisioningKeyOrg,
siteProvisioningKeys
} from "@server/db";
import logger from "@server/logger";
import HttpCode from "@server/types/HttpCode";
import response from "@server/lib/response";
import { NextFunction, Request, Response } from "express";
import createHttpError from "http-errors";
import { z } from "zod";
import { fromError } from "zod-validation-error";
import { eq } from "drizzle-orm";
import type { ListSiteProvisioningKeysResponse } from "@server/routers/siteProvisioning/types";
const paramsSchema = z.object({
orgId: z.string().nonempty()
});
const querySchema = z.object({
limit: z
.string()
.optional()
.default("1000")
.transform(Number)
.pipe(z.int().positive()),
offset: z
.string()
.optional()
.default("0")
.transform(Number)
.pipe(z.int().nonnegative())
});
function querySiteProvisioningKeys(orgId: string) {
return db
.select({
siteProvisioningKeyId:
siteProvisioningKeys.siteProvisioningKeyId,
orgId: siteProvisioningKeyOrg.orgId,
lastChars: siteProvisioningKeys.lastChars,
createdAt: siteProvisioningKeys.createdAt,
name: siteProvisioningKeys.name,
lastUsed: siteProvisioningKeys.lastUsed,
maxBatchSize: siteProvisioningKeys.maxBatchSize,
numUsed: siteProvisioningKeys.numUsed,
validUntil: siteProvisioningKeys.validUntil
})
.from(siteProvisioningKeyOrg)
.innerJoin(
siteProvisioningKeys,
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyOrg.siteProvisioningKeyId
)
)
.where(eq(siteProvisioningKeyOrg.orgId, orgId));
}
export async function listSiteProvisioningKeys(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error)
)
);
}
const parsedQuery = querySchema.safeParse(req.query);
if (!parsedQuery.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedQuery.error)
)
);
}
const { orgId } = parsedParams.data;
const { limit, offset } = parsedQuery.data;
const siteProvisioningKeysList = await querySiteProvisioningKeys(orgId)
.limit(limit)
.offset(offset);
return response<ListSiteProvisioningKeysResponse>(res, {
data: {
siteProvisioningKeys: siteProvisioningKeysList,
pagination: {
total: siteProvisioningKeysList.length,
limit,
offset
}
},
success: true,
error: false,
message: "Site provisioning keys retrieved successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -0,0 +1,199 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import {
db,
siteProvisioningKeyOrg,
siteProvisioningKeys
} 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";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import type { UpdateSiteProvisioningKeyResponse } from "@server/routers/siteProvisioning/types";
const paramsSchema = z.object({
siteProvisioningKeyId: z.string().nonempty(),
orgId: z.string().nonempty()
});
const bodySchema = z
.strictObject({
maxBatchSize: z
.union([
z.null(),
z.coerce.number().int().positive().max(1_000_000)
])
.optional(),
validUntil: z.string().max(255).optional()
})
.superRefine((data, ctx) => {
if (
data.maxBatchSize === undefined &&
data.validUntil === undefined
) {
ctx.addIssue({
code: "custom",
message: "Provide maxBatchSize and/or validUntil",
path: ["maxBatchSize"]
});
}
const v = data.validUntil;
if (v == null || v.trim() === "") {
return;
}
if (Number.isNaN(Date.parse(v))) {
ctx.addIssue({
code: "custom",
message: "Invalid validUntil",
path: ["validUntil"]
});
}
});
export type UpdateSiteProvisioningKeyBody = z.infer<typeof bodySchema>;
export async function updateSiteProvisioningKey(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = paramsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { siteProvisioningKeyId, orgId } = parsedParams.data;
const body = parsedBody.data;
const [row] = await db
.select()
.from(siteProvisioningKeys)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
)
.innerJoin(
siteProvisioningKeyOrg,
and(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyOrg.siteProvisioningKeyId
),
eq(siteProvisioningKeyOrg.orgId, orgId)
)
)
.limit(1);
if (!row) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
`Site provisioning key with ID ${siteProvisioningKeyId} not found`
)
);
}
const setValues: {
maxBatchSize?: number | null;
validUntil?: string | null;
} = {};
if (body.maxBatchSize !== undefined) {
setValues.maxBatchSize = body.maxBatchSize;
}
if (body.validUntil !== undefined) {
setValues.validUntil =
body.validUntil.trim() === ""
? null
: new Date(Date.parse(body.validUntil)).toISOString();
}
await db
.update(siteProvisioningKeys)
.set(setValues)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
);
const [updated] = await db
.select({
siteProvisioningKeyId:
siteProvisioningKeys.siteProvisioningKeyId,
name: siteProvisioningKeys.name,
lastChars: siteProvisioningKeys.lastChars,
createdAt: siteProvisioningKeys.createdAt,
lastUsed: siteProvisioningKeys.lastUsed,
maxBatchSize: siteProvisioningKeys.maxBatchSize,
numUsed: siteProvisioningKeys.numUsed,
validUntil: siteProvisioningKeys.validUntil
})
.from(siteProvisioningKeys)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyId
)
)
.limit(1);
if (!updated) {
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to load updated site provisioning key"
)
);
}
return response<UpdateSiteProvisioningKeyResponse>(res, {
data: {
...updated,
orgId
},
success: true,
error: false,
message: "Site provisioning key updated successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -32,7 +32,7 @@ import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
import { fromError } from "zod-validation-error";
import { and, eq, inArray, or } from "drizzle-orm";
import { eq, or, and } from "drizzle-orm";
import { canUserAccessSiteResource } from "@server/auth/canUserAccessSiteResource";
import { signPublicKey, getOrgCAKeys } from "@server/lib/sshCA";
import config from "@server/lib/config";
@@ -126,7 +126,7 @@ export async function signSshKey(
resource: resourceQueryString
} = parsedBody.data;
const userId = req.user?.userId;
const roleIds = req.userOrgRoleIds ?? [];
const roleId = req.userOrgRoleId!;
if (!userId) {
return next(
@@ -134,15 +134,6 @@ export async function signSshKey(
);
}
if (roleIds.length === 0) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User has no role in organization"
)
);
}
const [userOrg] = await db
.select()
.from(userOrgs)
@@ -349,7 +340,7 @@ export async function signSshKey(
const hasAccess = await canUserAccessSiteResource({
userId: userId,
resourceId: resource.siteResourceId,
roleIds
roleId: roleId
});
if (!hasAccess) {
@@ -361,39 +352,28 @@ export async function signSshKey(
);
}
const roleRows = await db
const [roleRow] = await db
.select()
.from(roles)
.where(inArray(roles.roleId, roleIds));
.where(eq(roles.roleId, roleId))
.limit(1);
const parsedSudoCommands: string[] = [];
const parsedGroupsSet = new Set<string>();
let homedir: boolean | null = null;
const sudoModeOrder = { none: 0, commands: 1, all: 2 };
let sudoMode: "none" | "commands" | "all" = "none";
for (const roleRow of roleRows) {
try {
const cmds = JSON.parse(roleRow?.sshSudoCommands ?? "[]");
if (Array.isArray(cmds)) parsedSudoCommands.push(...cmds);
} catch {
// skip
}
try {
const grps = JSON.parse(roleRow?.sshUnixGroups ?? "[]");
if (Array.isArray(grps)) grps.forEach((g: string) => parsedGroupsSet.add(g));
} catch {
// skip
}
if (roleRow?.sshCreateHomeDir === true) homedir = true;
const m = roleRow?.sshSudoMode ?? "none";
if (sudoModeOrder[m as keyof typeof sudoModeOrder] > sudoModeOrder[sudoMode]) {
sudoMode = m as "none" | "commands" | "all";
}
let parsedSudoCommands: string[] = [];
let parsedGroups: string[] = [];
try {
parsedSudoCommands = JSON.parse(roleRow?.sshSudoCommands ?? "[]");
if (!Array.isArray(parsedSudoCommands)) parsedSudoCommands = [];
} catch {
parsedSudoCommands = [];
}
const parsedGroups = Array.from(parsedGroupsSet);
if (homedir === null && roleRows.length > 0) {
homedir = roleRows[0].sshCreateHomeDir ?? null;
try {
parsedGroups = JSON.parse(roleRow?.sshUnixGroups ?? "[]");
if (!Array.isArray(parsedGroups)) parsedGroups = [];
} catch {
parsedGroups = [];
}
const homedir = roleRow?.sshCreateHomeDir ?? null;
const sudoMode = roleRow?.sshSudoMode ?? "none";
// get the site
const [newt] = await db

View File

@@ -1,171 +0,0 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import stoi from "@server/lib/stoi";
import { db } from "@server/db";
import { userOrgRoles, userOrgs, roles, clients } from "@server/db";
import { eq, and } from "drizzle-orm";
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 { OpenAPITags, registry } from "@server/openApi";
import { rebuildClientAssociationsFromClient } from "@server/lib/rebuildClientAssociations";
const removeUserRoleParamsSchema = z.strictObject({
userId: z.string(),
roleId: z.string().transform(stoi).pipe(z.number())
});
registry.registerPath({
method: "delete",
path: "/user/{userId}/remove-role/{roleId}",
description:
"Remove a role from a user. User must have at least one role left in the org.",
tags: [OpenAPITags.Role, OpenAPITags.User],
request: {
params: removeUserRoleParamsSchema
},
responses: {}
});
export async function removeUserRole(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = removeUserRoleParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const { userId, roleId } = parsedParams.data;
if (req.user && !req.userOrg) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"You do not have access to this organization"
)
);
}
const [role] = await db
.select()
.from(roles)
.where(eq(roles.roleId, roleId))
.limit(1);
if (!role) {
return next(
createHttpError(HttpCode.BAD_REQUEST, "Invalid role ID")
);
}
const [existingUser] = await db
.select()
.from(userOrgs)
.where(
and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, role.orgId))
)
.limit(1);
if (!existingUser) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
"User not found or does not belong to the specified organization"
)
);
}
if (existingUser.isOwner) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"Cannot change the roles of the owner of the organization"
)
);
}
const remainingRoles = await db
.select({ roleId: userOrgRoles.roleId })
.from(userOrgRoles)
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, role.orgId)
)
);
if (remainingRoles.length <= 1) {
const hasThisRole = remainingRoles.some((r) => r.roleId === roleId);
if (hasThisRole) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"User must have at least one role in the organization. Remove the last role is not allowed."
)
);
}
}
await db.transaction(async (trx) => {
await trx
.delete(userOrgRoles)
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, role.orgId),
eq(userOrgRoles.roleId, roleId)
)
);
const orgClients = await trx
.select()
.from(clients)
.where(
and(
eq(clients.userId, userId),
eq(clients.orgId, role.orgId)
)
);
for (const orgClient of orgClients) {
await rebuildClientAssociationsFromClient(orgClient, trx);
}
});
return response(res, {
data: { userId, orgId: role.orgId, roleId },
success: true,
error: false,
message: "Role removed from user successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -1,163 +0,0 @@
/*
* This file is part of a proprietary work.
*
* Copyright (c) 2025 Fossorial, Inc.
* All rights reserved.
*
* This file is licensed under the Fossorial Commercial License.
* You may not use this file except in compliance with the License.
* Unauthorized use, copying, modification, or distribution is strictly prohibited.
*
* This file is not licensed under the AGPLv3.
*/
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { clients, db } from "@server/db";
import { userOrgRoles, userOrgs, roles } from "@server/db";
import { eq, and, inArray } from "drizzle-orm";
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 { rebuildClientAssociationsFromClient } from "@server/lib/rebuildClientAssociations";
const setUserOrgRolesParamsSchema = z.strictObject({
orgId: z.string(),
userId: z.string()
});
const setUserOrgRolesBodySchema = z.strictObject({
roleIds: z.array(z.int().positive()).min(1)
});
export async function setUserOrgRoles(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedParams = setUserOrgRolesParamsSchema.safeParse(req.params);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedParams.error).toString()
)
);
}
const parsedBody = setUserOrgRolesBodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { orgId, userId } = parsedParams.data;
const { roleIds } = parsedBody.data;
if (req.user && !req.userOrg) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"You do not have access to this organization"
)
);
}
const uniqueRoleIds = [...new Set(roleIds)];
const [existingUser] = await db
.select()
.from(userOrgs)
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.limit(1);
if (!existingUser) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
"User not found in this organization"
)
);
}
if (existingUser.isOwner) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"Cannot change the roles of the owner of the organization"
)
);
}
const orgRoles = await db
.select({ roleId: roles.roleId })
.from(roles)
.where(
and(
eq(roles.orgId, orgId),
inArray(roles.roleId, uniqueRoleIds)
)
);
if (orgRoles.length !== uniqueRoleIds.length) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"One or more role IDs are invalid for this organization"
)
);
}
await db.transaction(async (trx) => {
await trx
.delete(userOrgRoles)
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, orgId)
)
);
if (uniqueRoleIds.length > 0) {
await trx.insert(userOrgRoles).values(
uniqueRoleIds.map((roleId) => ({
userId,
orgId,
roleId
}))
);
}
const orgClients = await trx
.select()
.from(clients)
.where(
and(eq(clients.userId, userId), eq(clients.orgId, orgId))
);
for (const orgClient of orgClients) {
await rebuildClientAssociationsFromClient(orgClient, trx);
}
});
return response(res, {
data: { userId, orgId, roleIds: uniqueRoleIds },
success: true,
error: false,
message: "User roles set successfully",
status: HttpCode.OK
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -18,10 +18,12 @@ import {
} from "#private/routers/remoteExitNode";
import { MessageHandler } from "@server/routers/ws";
import { build } from "@server/build";
import { handleConnectionLogMessage } from "#dynamic/routers/newt";
export const messageHandlers: Record<string, MessageHandler> = {
"remoteExitNode/register": handleRemoteExitNodeRegisterMessage,
"remoteExitNode/ping": handleRemoteExitNodePingMessage
"remoteExitNode/ping": handleRemoteExitNodePingMessage,
"newt/access-log": handleConnectionLogMessage,
};
if (build != "saas") {

View File

@@ -208,7 +208,7 @@ export async function listAccessTokens(
.where(
or(
eq(userResources.userId, req.user!.userId),
inArray(roleResources.roleId, req.userOrgRoleIds!)
eq(roleResources.roleId, req.userOrgRoleId!)
)
);
} else {

View File

@@ -91,3 +91,50 @@ export type QueryAccessAuditLogResponse = {
locations: string[];
};
};
export type QueryConnectionAuditLogResponse = {
log: {
sessionId: string;
siteResourceId: number | null;
orgId: string | null;
siteId: number | null;
clientId: number | null;
userId: string | null;
sourceAddr: string;
destAddr: string;
protocol: string;
startedAt: number;
endedAt: number | null;
bytesTx: number | null;
bytesRx: number | null;
resourceName: string | null;
resourceNiceId: string | null;
siteName: string | null;
siteNiceId: string | null;
clientName: string | null;
clientNiceId: string | null;
clientType: string | null;
userEmail: string | null;
}[];
pagination: {
total: number;
limit: number;
offset: number;
};
filterAttributes: {
protocols: string[];
destAddrs: string[];
clients: {
id: number;
name: string;
}[];
resources: {
id: number;
name: string | null;
}[];
users: {
id: string;
email: string | null;
}[];
};
};

View File

@@ -4,11 +4,11 @@ import {
getResourceByDomain,
getResourceRules,
getRoleResourceAccess,
getUserOrgRole,
getUserResourceAccess,
getOrgLoginPage,
getUserSessionWithUser
} from "@server/db/queries/verifySessionQueries";
import { getUserOrgRoles } from "@server/lib/userOrgRoles";
import {
LoginPage,
Org,
@@ -30,6 +30,7 @@ import { z } from "zod";
import { fromError } from "zod-validation-error";
import { getCountryCodeForIp } from "@server/lib/geoip";
import { getAsnForIp } from "@server/lib/asn";
import { getOrgTierData } from "#dynamic/lib/billing";
import { verifyPassword } from "@server/auth/password";
import {
checkOrgAccessPolicy,
@@ -796,8 +797,7 @@ async function notAllowed(
) {
let loginPage: LoginPage | null = null;
if (orgId) {
const subscribed = await isSubscribed(
// this is fine because the org login page is only a saas feature
const subscribed = await isSubscribed( // this is fine because the org login page is only a saas feature
orgId,
tierMatrix.loginPageDomain
);
@@ -854,10 +854,7 @@ async function headerAuthChallenged(
) {
let loginPage: LoginPage | null = null;
if (orgId) {
const subscribed = await isSubscribed(
orgId,
tierMatrix.loginPageDomain
); // this is fine because the org login page is only a saas feature
const subscribed = await isSubscribed(orgId, tierMatrix.loginPageDomain); // this is fine because the org login page is only a saas feature
if (subscribed) {
loginPage = await getOrgLoginPage(orgId);
}
@@ -919,9 +916,9 @@ async function isUserAllowedToAccessResource(
return null;
}
const userOrgRoles = await getUserOrgRoles(user.userId, resource.orgId);
const userOrgRole = await getUserOrgRole(user.userId, resource.orgId);
if (!userOrgRoles.length) {
if (!userOrgRole) {
return null;
}
@@ -939,14 +936,15 @@ async function isUserAllowedToAccessResource(
const roleResourceAccess = await getRoleResourceAccess(
resource.resourceId,
userOrgRoles.map((r) => r.roleId)
userOrgRole.roleId
);
if (roleResourceAccess && roleResourceAccess.length > 0) {
if (roleResourceAccess) {
return {
username: user.username,
email: user.email,
name: user.name,
role: userOrgRoles.map((r) => r.roleName).join(", ")
role: userOrgRole.roleName
};
}
@@ -960,7 +958,7 @@ async function isUserAllowedToAccessResource(
username: user.username,
email: user.email,
name: user.name,
role: userOrgRoles.map((r) => r.roleName).join(", ")
role: userOrgRole.roleName
};
}

View File

@@ -92,7 +92,7 @@ export async function createClient(
const { orgId } = parsedParams.data;
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
if (req.user && !req.userOrgRoleId) {
return next(
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
);
@@ -234,7 +234,7 @@ export async function createClient(
clientId: newClient.clientId
});
if (req.user && !req.userOrgRoleIds?.includes(adminRole.roleId)) {
if (req.user && req.userOrgRoleId != adminRole.roleId) {
// make sure the user can access the client
trx.insert(userClients).values({
userId: req.user.userId,

View File

@@ -297,7 +297,7 @@ export async function listClients(
.where(
or(
eq(userClients.userId, req.user!.userId),
inArray(roleClients.roleId, req.userOrgRoleIds!)
eq(roleClients.roleId, req.userOrgRoleId!)
)
);
} else {

View File

@@ -316,7 +316,7 @@ export async function listUserDevices(
.where(
or(
eq(userClients.userId, req.user!.userId),
inArray(roleClients.roleId, req.userOrgRoleIds!)
eq(roleClients.roleId, req.userOrgRoleId!)
)
);
} else {

View File

@@ -102,6 +102,8 @@ authenticated.put(
logActionAudit(ActionsEnum.createSite),
site.createSite
);
authenticated.get(
"/org/:orgId/sites",
verifyOrgAccess,
@@ -644,7 +646,6 @@ authenticated.delete(
logActionAudit(ActionsEnum.deleteRole),
role.deleteRole
);
authenticated.post(
"/role/:roleId/add/:userId",
verifyRoleAccess,
@@ -652,7 +653,7 @@ authenticated.post(
verifyLimits,
verifyUserHasAction(ActionsEnum.addUserRole),
logActionAudit(ActionsEnum.addUserRole),
user.addUserRoleLegacy
user.addUserRole
);
authenticated.post(
@@ -1203,6 +1204,22 @@ authRouter.post(
}),
newt.getNewtToken
);
authRouter.post(
"/newt/register",
rateLimit({
windowMs: 15 * 60 * 1000,
max: 30,
keyGenerator: (req) =>
`newtRegister:${req.body.provisioningKey?.split(".")[0] || ipKeyGenerator(req.ip || "")}`,
handler: (req, res, next) => {
const message = `You can only register a newt ${30} times every ${15} minutes. Please try again later.`;
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
},
store: createStore()
}),
newt.registerNewt
);
authRouter.post(
"/olm/get-token",
rateLimit({

View File

@@ -25,8 +25,7 @@ const bodySchema = z.strictObject({
namePath: z.string().optional(),
scopes: z.string().nonempty(),
autoProvision: z.boolean().optional(),
tags: z.string().optional(),
variant: z.enum(["oidc", "google", "azure"]).optional().default("oidc")
tags: z.string().optional()
});
export type CreateIdpResponse = {
@@ -78,8 +77,7 @@ export async function createOidcIdp(
namePath,
name,
autoProvision,
tags,
variant
tags
} = parsedBody.data;
if (
@@ -123,8 +121,7 @@ export async function createOidcIdp(
scopes,
identifierPath,
emailPath,
namePath,
variant
namePath
});
});

View File

@@ -31,8 +31,7 @@ const bodySchema = z.strictObject({
autoProvision: z.boolean().optional(),
defaultRoleMapping: z.string().optional(),
defaultOrgMapping: z.string().optional(),
tags: z.string().optional(),
variant: z.enum(["oidc", "google", "azure"]).optional()
tags: z.string().optional()
});
export type UpdateIdpResponse = {
@@ -97,8 +96,7 @@ export async function updateOidcIdp(
autoProvision,
defaultRoleMapping,
defaultOrgMapping,
tags,
variant
tags
} = parsedBody.data;
if (process.env.IDENTITY_PROVIDER_MODE === "org") {
@@ -161,8 +159,7 @@ export async function updateOidcIdp(
scopes,
identifierPath,
emailPath,
namePath,
variant
namePath
};
keysToUpdate = Object.keys(configData).filter(

View File

@@ -13,7 +13,6 @@ import {
orgs,
Role,
roles,
userOrgRoles,
userOrgs,
users
} from "@server/db";
@@ -36,13 +35,11 @@ import { usageService } from "@server/lib/billing/usageService";
import { build } from "@server/build";
import { calculateUserClientsForOrgs } from "@server/lib/calculateUserClientsForOrgs";
import { isSubscribed } from "#dynamic/lib/isSubscribed";
import { isLicensedOrSubscribed } from "#dynamic/lib/isLicencedOrSubscribed";
import { tierMatrix } from "@server/lib/billing/tierMatrix";
import {
assignUserToOrg,
removeUserFromOrg
} from "@server/lib/userOrg";
import { unwrapRoleMapping } from "@app/lib/idpRoleMapping";
const ensureTrailingSlash = (url: string): string => {
return url;
@@ -369,7 +366,7 @@ export async function validateOidcCallback(
const defaultRoleMapping = existingIdp.idp.defaultRoleMapping;
const defaultOrgMapping = existingIdp.idp.defaultOrgMapping;
const userOrgInfo: { orgId: string; roleIds: number[] }[] = [];
const userOrgInfo: { orgId: string; roleId: number }[] = [];
for (const org of allOrgs) {
const [idpOrgRes] = await db
.select()
@@ -381,6 +378,8 @@ export async function validateOidcCallback(
)
);
let roleId: number | undefined = undefined;
const orgMapping = idpOrgRes?.orgMapping || defaultOrgMapping;
const hydratedOrgMapping = hydrateOrgMapping(
orgMapping,
@@ -405,55 +404,38 @@ export async function validateOidcCallback(
idpOrgRes?.roleMapping || defaultRoleMapping;
if (roleMapping) {
logger.debug("Role Mapping", { roleMapping });
const roleMappingJmes = unwrapRoleMapping(
roleMapping
).evaluationExpression;
const roleMappingResult = jmespath.search(
claims,
roleMappingJmes
);
const roleNames = normalizeRoleMappingResult(
roleMappingResult
);
const roleName = jmespath.search(claims, roleMapping);
const supportsMultiRole = await isLicensedOrSubscribed(
org.orgId,
tierMatrix.fullRbac
);
const effectiveRoleNames = supportsMultiRole
? roleNames
: roleNames.slice(0, 1);
if (!effectiveRoleNames.length) {
logger.error("Role mapping returned no valid roles", {
roleMappingResult
if (!roleName) {
logger.error("Role name not found in the ID token", {
roleName
});
continue;
}
const roleRes = await db
const [roleRes] = await db
.select()
.from(roles)
.where(
and(
eq(roles.orgId, org.orgId),
inArray(roles.name, effectiveRoleNames)
eq(roles.name, roleName)
)
);
if (!roleRes.length) {
logger.error("No mapped roles found in organization", {
if (!roleRes) {
logger.error("Role not found", {
orgId: org.orgId,
roleNames: effectiveRoleNames
roleName
});
continue;
}
const roleIds = [...new Set(roleRes.map((r) => r.roleId))];
roleId = roleRes.roleId;
userOrgInfo.push({
orgId: org.orgId,
roleIds
roleId
});
}
}
@@ -588,28 +570,32 @@ export async function validateOidcCallback(
}
}
// Sync roles 1:1 with IdP policy for existing auto-provisioned orgs
for (const currentOrg of autoProvisionedOrgs) {
const newRole = userOrgInfo.find(
(newOrg) => newOrg.orgId === currentOrg.orgId
);
if (!newRole) continue;
await trx
.delete(userOrgRoles)
.where(
and(
eq(userOrgRoles.userId, userId!),
eq(userOrgRoles.orgId, currentOrg.orgId)
)
// Update roles for existing auto-provisioned orgs where the role has changed
const orgsToUpdate = autoProvisionedOrgs.filter(
(currentOrg) => {
const newOrg = userOrgInfo.find(
(newOrg) => newOrg.orgId === currentOrg.orgId
);
return newOrg && newOrg.roleId !== currentOrg.roleId;
}
);
for (const roleId of newRole.roleIds) {
await trx.insert(userOrgRoles).values({
userId: userId!,
orgId: currentOrg.orgId,
roleId
});
if (orgsToUpdate.length > 0) {
for (const org of orgsToUpdate) {
const newRole = userOrgInfo.find(
(newOrg) => newOrg.orgId === org.orgId
);
if (newRole) {
await trx
.update(userOrgs)
.set({ roleId: newRole.roleId })
.where(
and(
eq(userOrgs.userId, userId!),
eq(userOrgs.orgId, org.orgId)
)
);
}
}
}
@@ -623,12 +609,6 @@ export async function validateOidcCallback(
if (orgsToAdd.length > 0) {
for (const org of orgsToAdd) {
const [initialRoleId, ...additionalRoleIds] =
org.roleIds;
if (!initialRoleId) {
continue;
}
const [fullOrg] = await trx
.select()
.from(orgs)
@@ -639,19 +619,11 @@ export async function validateOidcCallback(
{
orgId: org.orgId,
userId: userId!,
roleId: org.roleId,
autoProvisioned: true,
},
initialRoleId,
trx
);
for (const roleId of additionalRoleIds) {
await trx.insert(userOrgRoles).values({
userId: userId!,
orgId: org.orgId,
roleId
});
}
}
}
}
@@ -776,25 +748,3 @@ function hydrateOrgMapping(
}
return orgMapping.split("{{orgId}}").join(orgId);
}
function normalizeRoleMappingResult(
result: unknown
): string[] {
if (typeof result === "string") {
const role = result.trim();
return role ? [role] : [];
}
if (Array.isArray(result)) {
return [
...new Set(
result
.filter((value): value is string => typeof value === "string")
.map((value) => value.trim())
.filter(Boolean)
)
];
}
return [];
}

View File

@@ -16,7 +16,6 @@ import {
verifyApiKey,
verifyApiKeyOrgAccess,
verifyApiKeyHasAction,
verifyApiKeyCanSetUserOrgRoles,
verifyApiKeySiteAccess,
verifyApiKeyResourceAccess,
verifyApiKeyTargetAccess,
@@ -596,7 +595,7 @@ authenticated.post(
verifyLimits,
verifyApiKeyHasAction(ActionsEnum.addUserRole),
logActionAudit(ActionsEnum.addUserRole),
user.addUserRoleLegacy
user.addUserRole
);
authenticated.post(

View File

@@ -46,7 +46,7 @@ export async function createNewt(
const { newtId, secret } = parsedBody.data;
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
if (req.user && !req.userOrgRoleId) {
return next(
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
);

View File

@@ -0,0 +1,13 @@
import { MessageHandler } from "@server/routers/ws";
export async function flushConnectionLogToDb(): Promise<void> {
return;
}
export async function cleanUpOldLogs(orgId: string, retentionDays: number) {
return;
}
export const handleConnectionLogMessage: MessageHandler = async (context) => {
return;
};

View File

@@ -8,3 +8,5 @@ export * from "./handleNewtPingRequestMessage";
export * from "./handleApplyBlueprintMessage";
export * from "./handleNewtPingMessage";
export * from "./handleNewtDisconnectingMessage";
export * from "./handleConnectionLogMessage";
export * from "./registerNewt";

View File

@@ -0,0 +1,266 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import {
siteProvisioningKeys,
siteProvisioningKeyOrg,
newts,
orgs,
roles,
roleSites,
sites
} 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 { eq, and, sql } from "drizzle-orm";
import { fromError } from "zod-validation-error";
import { verifyPassword, hashPassword } from "@server/auth/password";
import {
generateId,
generateIdFromEntropySize
} from "@server/auth/sessions/app";
import { getUniqueSiteName } from "@server/db/names";
import moment from "moment";
import { build } from "@server/build";
import { usageService } from "@server/lib/billing/usageService";
import { FeatureId } from "@server/lib/billing";
import { INSPECT_MAX_BYTES } from "buffer";
import { v } from "@faker-js/faker/dist/airline-Dz1uGqgJ";
const bodySchema = z.object({
provisioningKey: z.string().nonempty()
});
export type RegisterNewtBody = z.infer<typeof bodySchema>;
export type RegisterNewtResponse = {
newtId: string;
secret: string;
};
export async function registerNewt(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
try {
const parsedBody = bodySchema.safeParse(req.body);
if (!parsedBody.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
fromError(parsedBody.error).toString()
)
);
}
const { provisioningKey } = parsedBody.data;
// Keys are in the format "siteProvisioningKeyId.secret"
const dotIndex = provisioningKey.indexOf(".");
if (dotIndex === -1) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
"Invalid provisioning key format"
)
);
}
const provisioningKeyId = provisioningKey.substring(0, dotIndex);
const provisioningKeySecret = provisioningKey.substring(dotIndex + 1);
// Look up the provisioning key by ID, joining to get the orgId
const [keyRecord] = await db
.select({
siteProvisioningKeyId:
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyHash:
siteProvisioningKeys.siteProvisioningKeyHash,
orgId: siteProvisioningKeyOrg.orgId,
maxBatchSize: siteProvisioningKeys.maxBatchSize,
numUsed: siteProvisioningKeys.numUsed,
validUntil: siteProvisioningKeys.validUntil
})
.from(siteProvisioningKeys)
.innerJoin(
siteProvisioningKeyOrg,
eq(
siteProvisioningKeys.siteProvisioningKeyId,
siteProvisioningKeyOrg.siteProvisioningKeyId
)
)
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
provisioningKeyId
)
)
.limit(1);
if (!keyRecord) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid provisioning key"
)
);
}
// Verify the secret portion against the stored hash
const validSecret = await verifyPassword(
provisioningKeySecret,
keyRecord.siteProvisioningKeyHash
);
if (!validSecret) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Invalid provisioning key"
)
);
}
if (keyRecord.maxBatchSize && keyRecord.numUsed >= keyRecord.maxBatchSize) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Provisioning key has reached its maximum usage"
)
);
}
if (keyRecord.validUntil && new Date(keyRecord.validUntil) < new Date()) {
return next(
createHttpError(
HttpCode.UNAUTHORIZED,
"Provisioning key has expired"
)
);
}
const { orgId } = keyRecord;
// Verify the org exists
const [org] = await db.select().from(orgs).where(eq(orgs.orgId, orgId));
if (!org) {
return next(
createHttpError(HttpCode.NOT_FOUND, "Organization not found")
);
}
// SaaS billing check
if (build == "saas") {
const usage = await usageService.getUsage(orgId, FeatureId.SITES);
if (!usage) {
return next(
createHttpError(
HttpCode.NOT_FOUND,
"No usage data found for this organization"
)
);
}
const rejectSites = await usageService.checkLimitSet(
orgId,
FeatureId.SITES,
{
...usage,
instantaneousValue: (usage.instantaneousValue || 0) + 1
}
);
if (rejectSites) {
return next(
createHttpError(
HttpCode.FORBIDDEN,
"Site limit exceeded. Please upgrade your plan."
)
);
}
}
const niceId = await getUniqueSiteName(orgId);
const newtId = generateId(15);
const newtSecret = generateIdFromEntropySize(25);
const secretHash = await hashPassword(newtSecret);
let newSiteId: number | undefined;
await db.transaction(async (trx) => {
// Create the site (type "newt", name = niceId)
const [newSite] = await trx
.insert(sites)
.values({
orgId,
name: niceId,
niceId,
type: "newt",
dockerSocketEnabled: true
})
.returning();
newSiteId = newSite.siteId;
// Grant admin role access to the new site
const [adminRole] = await trx
.select()
.from(roles)
.where(and(eq(roles.isAdmin, true), eq(roles.orgId, orgId)))
.limit(1);
if (!adminRole) {
throw new Error(`Admin role not found for org ${orgId}`);
}
await trx.insert(roleSites).values({
roleId: adminRole.roleId,
siteId: newSite.siteId
});
// Create the newt for this site
await trx.insert(newts).values({
newtId,
secretHash,
siteId: newSite.siteId,
dateCreated: moment().toISOString()
});
// Consume the provisioning key — cascade removes siteProvisioningKeyOrg
await trx
.update(siteProvisioningKeys)
.set({
lastUsed: moment().toISOString(),
numUsed: sql`${siteProvisioningKeys.numUsed} + 1`
})
.where(
eq(
siteProvisioningKeys.siteProvisioningKeyId,
provisioningKeyId
)
);
await usageService.add(orgId, FeatureId.SITES, 1, trx);
});
logger.info(
`Provisioned new site (ID: ${newSiteId}) and newt (ID: ${newtId}) for org ${orgId} via provisioning key ${provisioningKeyId}`
);
return response<RegisterNewtResponse>(res, {
data: {
newtId,
secret: newtSecret
},
success: true,
error: false,
message: "Newt registered successfully",
status: HttpCode.CREATED
});
} catch (error) {
logger.error(error);
return next(
createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred")
);
}
}

View File

@@ -46,7 +46,7 @@ export async function createNewt(
const { newtId, secret } = parsedBody.data;
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
if (req.user && !req.userOrgRoleId) {
return next(
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
);

View File

@@ -1,7 +1,7 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db, idp, idpOidcConfig } from "@server/db";
import { roles, userOrgRoles, userOrgs, users } from "@server/db";
import { roles, userOrgs, users } from "@server/db";
import { and, eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
@@ -14,7 +14,7 @@ import { checkOrgAccessPolicy } from "#dynamic/lib/checkOrgAccessPolicy";
import { CheckOrgAccessPolicyResult } from "@server/lib/checkOrgAccessPolicy";
async function queryUser(orgId: string, userId: string) {
const [userRow] = await db
const [user] = await db
.select({
orgId: userOrgs.orgId,
userId: users.userId,
@@ -22,7 +22,10 @@ async function queryUser(orgId: string, userId: string) {
username: users.username,
name: users.name,
type: users.type,
roleId: userOrgs.roleId,
roleName: roles.name,
isOwner: userOrgs.isOwner,
isAdmin: roles.isAdmin,
twoFactorEnabled: users.twoFactorEnabled,
autoProvisioned: userOrgs.autoProvisioned,
idpId: users.idpId,
@@ -32,40 +35,13 @@ async function queryUser(orgId: string, userId: string) {
idpAutoProvision: idp.autoProvision
})
.from(userOrgs)
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
.leftJoin(users, eq(userOrgs.userId, users.userId))
.leftJoin(idp, eq(users.idpId, idp.idpId))
.leftJoin(idpOidcConfig, eq(idp.idpId, idpOidcConfig.idpId))
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.limit(1);
if (!userRow) return undefined;
const roleRows = await db
.select({
roleId: userOrgRoles.roleId,
roleName: roles.name,
isAdmin: roles.isAdmin
})
.from(userOrgRoles)
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, orgId)
)
);
const isAdmin = roleRows.some((r) => r.isAdmin);
return {
...userRow,
isAdmin,
roleIds: roleRows.map((r) => r.roleId),
roles: roleRows.map((r) => ({
roleId: r.roleId,
name: r.roleName ?? ""
}))
};
return user;
}
export type CheckOrgUserAccessResponse = CheckOrgAccessPolicyResult;

View File

@@ -9,7 +9,6 @@ import {
orgs,
roleActions,
roles,
userOrgRoles,
userOrgs,
users,
actions
@@ -313,13 +312,9 @@ export async function createOrg(
await trx.insert(userOrgs).values({
userId: req.user!.userId,
orgId: newOrg[0].orgId,
roleId: roleId,
isOwner: true
});
await trx.insert(userOrgRoles).values({
userId: req.user!.userId,
orgId: newOrg[0].orgId,
roleId
});
ownerUserId = req.user!.userId;
} else {
// if org created by root api key, set the server admin as the owner
@@ -337,13 +332,9 @@ export async function createOrg(
await trx.insert(userOrgs).values({
userId: serverAdmin.userId,
orgId: newOrg[0].orgId,
roleId: roleId,
isOwner: true
});
await trx.insert(userOrgRoles).values({
userId: serverAdmin.userId,
orgId: newOrg[0].orgId,
roleId
});
ownerUserId = serverAdmin.userId;
}

View File

@@ -117,26 +117,20 @@ export async function getOrgOverview(
.from(userOrgs)
.where(eq(userOrgs.orgId, orgId));
const roleIds = req.userOrgRoleIds ?? [];
const roleRows =
roleIds.length > 0
? await db
.select({ name: roles.name, isAdmin: roles.isAdmin })
.from(roles)
.where(inArray(roles.roleId, roleIds))
: [];
const userRoleName = roleRows.map((r) => r.name ?? "").join(", ") ?? "";
const isAdmin = roleRows.some((r) => r.isAdmin === true);
const [role] = await db
.select()
.from(roles)
.where(eq(roles.roleId, req.userOrg.roleId));
return response<GetOrgOverviewResponse>(res, {
data: {
orgName: org[0].name,
orgId: org[0].orgId,
userRoleName,
userRoleName: role.name,
numSites,
numUsers,
numResources,
isAdmin,
isAdmin: role.isAdmin || false,
isOwner: req.userOrg?.isOwner || false
},
success: true,

View File

@@ -1,7 +1,7 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db, roles } from "@server/db";
import { Org, orgs, userOrgRoles, userOrgs } from "@server/db";
import { Org, orgs, userOrgs } from "@server/db";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
@@ -82,7 +82,10 @@ export async function listUserOrgs(
const { userId } = parsedParams.data;
const userOrganizations = await db
.select({ orgId: userOrgs.orgId })
.select({
orgId: userOrgs.orgId,
roleId: userOrgs.roleId
})
.from(userOrgs)
.where(eq(userOrgs.userId, userId));
@@ -113,27 +116,10 @@ export async function listUserOrgs(
userOrgs,
and(eq(userOrgs.orgId, orgs.orgId), eq(userOrgs.userId, userId))
)
.leftJoin(roles, eq(userOrgs.roleId, roles.roleId))
.limit(limit)
.offset(offset);
const roleRows = await db
.select({
orgId: userOrgRoles.orgId,
isAdmin: roles.isAdmin
})
.from(userOrgRoles)
.leftJoin(roles, eq(userOrgRoles.roleId, roles.roleId))
.where(
and(
eq(userOrgRoles.userId, userId),
inArray(userOrgRoles.orgId, userOrgIds)
)
);
const orgHasAdmin = new Set(
roleRows.filter((r) => r.isAdmin).map((r) => r.orgId)
);
const totalCountResult = await db
.select({ count: sql<number>`cast(count(*) as integer)` })
.from(orgs)
@@ -147,8 +133,8 @@ export async function listUserOrgs(
if (val.userOrgs && val.userOrgs.isOwner) {
res.isOwner = val.userOrgs.isOwner;
}
if (val.orgs && orgHasAdmin.has(val.orgs.orgId)) {
res.isAdmin = true;
if (val.roles && val.roles.isAdmin) {
res.isAdmin = val.roles.isAdmin;
}
if (val.userOrgs?.isOwner && val.orgs?.isBillingOrg) {
res.isPrimaryOrg = val.orgs.isBillingOrg;

View File

@@ -112,7 +112,7 @@ export async function createResource(
const { orgId } = parsedParams.data;
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
if (req.user && !req.userOrgRoleId) {
return next(
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
);
@@ -292,7 +292,7 @@ async function createHttpResource(
resourceId: newResource[0].resourceId
});
if (req.user && !req.userOrgRoleIds?.includes(adminRole[0].roleId)) {
if (req.user && req.userOrgRoleId != adminRole[0].roleId) {
// make sure the user can access the resource
await trx.insert(userResources).values({
userId: req.user?.userId!,
@@ -385,7 +385,7 @@ async function createRawResource(
resourceId: newResource[0].resourceId
});
if (req.user && !req.userOrgRoleIds?.includes(adminRole[0].roleId)) {
if (req.user && req.userOrgRoleId != adminRole[0].roleId) {
// make sure the user can access the resource
await trx.insert(userResources).values({
userId: req.user?.userId!,

View File

@@ -5,7 +5,6 @@ import {
resources,
userResources,
roleResources,
userOrgRoles,
userOrgs,
resourcePassword,
resourcePincode,
@@ -33,29 +32,22 @@ export async function getUserResources(
);
}
// Check user is in organization and get their role IDs
const [userOrg] = await db
.select()
// First get the user's role in the organization
const userOrgResult = await db
.select({
roleId: userOrgs.roleId
})
.from(userOrgs)
.where(and(eq(userOrgs.userId, userId), eq(userOrgs.orgId, orgId)))
.limit(1);
if (!userOrg) {
if (userOrgResult.length === 0) {
return next(
createHttpError(HttpCode.FORBIDDEN, "User not in organization")
);
}
const userRoleIds = await db
.select({ roleId: userOrgRoles.roleId })
.from(userOrgRoles)
.where(
and(
eq(userOrgRoles.userId, userId),
eq(userOrgRoles.orgId, orgId)
)
)
.then((rows) => rows.map((r) => r.roleId));
const userRoleId = userOrgResult[0].roleId;
// Get resources accessible through direct assignment or role assignment
const directResourcesQuery = db
@@ -63,28 +55,20 @@ export async function getUserResources(
.from(userResources)
.where(eq(userResources.userId, userId));
const roleResourcesQuery =
userRoleIds.length > 0
? db
.select({ resourceId: roleResources.resourceId })
.from(roleResources)
.where(inArray(roleResources.roleId, userRoleIds))
: Promise.resolve([]);
const roleResourcesQuery = db
.select({ resourceId: roleResources.resourceId })
.from(roleResources)
.where(eq(roleResources.roleId, userRoleId));
const directSiteResourcesQuery = db
.select({ siteResourceId: userSiteResources.siteResourceId })
.from(userSiteResources)
.where(eq(userSiteResources.userId, userId));
const roleSiteResourcesQuery =
userRoleIds.length > 0
? db
.select({
siteResourceId: roleSiteResources.siteResourceId
})
.from(roleSiteResources)
.where(inArray(roleSiteResources.roleId, userRoleIds))
: Promise.resolve([]);
const roleSiteResourcesQuery = db
.select({ siteResourceId: roleSiteResources.siteResourceId })
.from(roleSiteResources)
.where(eq(roleSiteResources.roleId, userRoleId));
const [directResources, roleResourceResults, directSiteResourceResults, roleSiteResourceResults] = await Promise.all([
directResourcesQuery,

View File

@@ -305,7 +305,7 @@ export async function listResources(
.where(
or(
eq(userResources.userId, req.user!.userId),
inArray(roleResources.roleId, req.userOrgRoleIds!)
eq(roleResources.roleId, req.userOrgRoleId!)
)
);
} else {

View File

@@ -1,8 +1,8 @@
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { db } from "@server/db";
import { roles, userOrgRoles } from "@server/db";
import { and, eq, exists, aliasedTable } from "drizzle-orm";
import { roles, userOrgs } from "@server/db";
import { eq } from "drizzle-orm";
import response from "@server/lib/response";
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
@@ -114,32 +114,13 @@ export async function deleteRole(
}
await db.transaction(async (trx) => {
const uorNewRole = aliasedTable(userOrgRoles, "user_org_roles_new");
// Users who already have newRoleId: drop the old assignment only (unique on userId+orgId+roleId).
await trx.delete(userOrgRoles).where(
and(
eq(userOrgRoles.roleId, roleId),
exists(
trx
.select()
.from(uorNewRole)
.where(
and(
eq(uorNewRole.userId, userOrgRoles.userId),
eq(uorNewRole.orgId, userOrgRoles.orgId),
eq(uorNewRole.roleId, newRoleId)
)
)
)
)
);
// move all users from the userOrgs table with roleId to newRoleId
await trx
.update(userOrgRoles)
.update(userOrgs)
.set({ roleId: newRoleId })
.where(eq(userOrgRoles.roleId, roleId));
.where(eq(userOrgs.roleId, roleId));
// delete the old role
await trx.delete(roles).where(eq(roles.roleId, roleId));
});

View File

@@ -111,7 +111,7 @@ export async function createSite(
const { orgId } = parsedParams.data;
if (req.user && (!req.userOrgRoleIds || req.userOrgRoleIds.length === 0)) {
if (req.user && !req.userOrgRoleId) {
return next(
createHttpError(HttpCode.FORBIDDEN, "User does not have a role")
);
@@ -399,7 +399,7 @@ export async function createSite(
siteId: newSite.siteId
});
if (req.user && !req.userOrgRoleIds?.includes(adminRole[0].roleId)) {
if (req.user && req.userOrgRoleId != adminRole[0].roleId) {
// make sure the user can access the site
trx.insert(userSites).values({
userId: req.user?.userId!,

Some files were not shown because too many files have changed in this diff Show More