diff --git a/messages/en-US.json b/messages/en-US.json index 05046e84f..ac4afcbd5 100644 --- a/messages/en-US.json +++ b/messages/en-US.json @@ -1205,7 +1205,7 @@ "accessRoleInferenceBudget": "AI Budget", "accessRoleInferenceBudgetDescription": "Configure how members of this role restrict AI usage based on spending or token limits", "accessRoleClientSettings": "Client Settings", - "accessRoleClientSettingsDescription": "Manage tunnel settings for the Pangolin clients of users in this role. Clients fetch these settings each time they connect. A user with several roles that manage settings gets the settings of the oldest of those roles; settings are not combined across roles.", + "accessRoleClientSettingsDescription": "Manage tunnel settings for the Pangolin clients of users in this role and for machine clients assigned to it. Clients fetch these settings each time they connect. A user or machine client with several roles that manage settings gets the settings of the oldest of those roles; settings are not combined across roles.", "clientSettingsEnabled": "Manage settings from the server", "clientSettingsEnabledDescription": "When off, this role does not change any client settings and clients keep their own.", "clientSettingsUnmanaged": "Set by client", diff --git a/server/lib/clientSettings.ts b/server/lib/clientSettings.ts index d140990c4..3346391dc 100644 --- a/server/lib/clientSettings.ts +++ b/server/lib/clientSettings.ts @@ -1,7 +1,8 @@ -// The client settings an org applies to a user's devices, resolved from the -// roleClientSettings table. Clients fetch these from -// GET /org/:orgId/my-client-settings each time they connect and when their -// settings are opened. An absent field is not managed by the server: the client +// The client settings an org applies to a client, resolved from the +// roleClientSettings table. User devices fetch these from +// GET /org/:orgId/my-client-settings and machine clients from +// POST /auth/olm/client-settings, each time they connect and when their settings +// are opened. An absent field is not managed by the server: the client // uses its own value for it. export type ClientSettings = { overrideDns?: boolean; @@ -24,3 +25,11 @@ export async function getClientSettingsForUser( ): Promise { return undefined; } + +export async function getClientSettingsForClient(client: { + clientId: number; + orgId: string; + userId: string | null; +}): Promise { + return undefined; +} diff --git a/server/private/lib/clientSettings.ts b/server/private/lib/clientSettings.ts index 9e4aeebd0..3e5832242 100644 --- a/server/private/lib/clientSettings.ts +++ b/server/private/lib/clientSettings.ts @@ -12,6 +12,7 @@ */ import { + clientOrgRoles, db, roleClientSettings, RoleClientSettings, @@ -58,6 +59,13 @@ function toClientSettings(row: RoleClientSettings): ClientSettings { return settings; } +function isClientSettingsLicensed(orgId: string): Promise { + return isLicensedOrSubscribed( + orgId, + tierMatrix[TierFeature.ClientSettings] + ); +} + // Resolves the settings a user gets in the org. Settings are never merged // across roles: a user with several enabled roles gets exactly one of them, // the one with the lowest roleId, so the result is deterministic. @@ -65,11 +73,7 @@ export async function getClientSettingsForUser( orgId: string, userId: string ): Promise { - const licensed = await isLicensedOrSubscribed( - orgId, - tierMatrix[TierFeature.ClientSettings] - ); - if (!licensed) { + if (!(await isClientSettingsLicensed(orgId))) { return undefined; } @@ -92,3 +96,40 @@ export async function getClientSettingsForUser( return row ? toClientSettings(row.settings) : undefined; } + +// Resolves the settings a client gets. A user device gets its user's settings; +// a machine client gets the settings of the roles assigned to it directly +// (clientOrgRoles), picked the same way as for users: the enabled role with +// the lowest roleId. +export async function getClientSettingsForClient(client: { + clientId: number; + orgId: string; + userId: string | null; +}): Promise { + if (client.userId) { + return getClientSettingsForUser(client.orgId, client.userId); + } + + if (!(await isClientSettingsLicensed(client.orgId))) { + return undefined; + } + + const [row] = await db + .select({ settings: roleClientSettings }) + .from(clientOrgRoles) + .innerJoin( + roleClientSettings, + eq(clientOrgRoles.roleId, roleClientSettings.roleId) + ) + .where( + and( + eq(clientOrgRoles.orgId, client.orgId), + eq(clientOrgRoles.clientId, client.clientId), + eq(roleClientSettings.enabled, true) + ) + ) + .orderBy(asc(clientOrgRoles.roleId)) + .limit(1); + + return row ? toClientSettings(row.settings) : undefined; +} diff --git a/server/routers/external.ts b/server/routers/external.ts index ee1bf5eca..45dbaa6da 100644 --- a/server/routers/external.ts +++ b/server/routers/external.ts @@ -2193,6 +2193,21 @@ authRouter.post( }), olm.getOlmToken ); +authRouter.post( + "/olm/client-settings", + rateLimit({ + windowMs: 15 * 60 * 1000, + max: 300, + keyGenerator: (req) => + `olmClientSettings:${req.body.olmId || ipKeyGenerator(req.ip || "")}`, + handler: (req, res, next) => { + const message = `You can only request Olm client settings ${300} times every ${15} minutes. Please try again later.`; + return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message)); + }, + store: createStore() + }), + olm.getOlmClientSettings +); authRouter.post( "/2fa/enable", diff --git a/server/routers/olm/getOlmClientSettings.ts b/server/routers/olm/getOlmClientSettings.ts new file mode 100644 index 000000000..a60d00f74 --- /dev/null +++ b/server/routers/olm/getOlmClientSettings.ts @@ -0,0 +1,147 @@ +import { NextFunction, Request, Response } from "express"; +import { and, eq } from "drizzle-orm"; +import createHttpError from "http-errors"; +import { z } from "zod"; +import { fromError } from "zod-validation-error"; +import { clients, db, olms, siteNetworks, siteResources } from "@server/db"; +import { verifyPassword } from "@server/auth/password"; +import response from "@server/lib/response"; +import config from "@server/lib/config"; +import logger from "@server/logger"; +import HttpCode from "@server/types/HttpCode"; +import type { ClientSettings } from "@server/lib/clientSettings"; +import { getClientSettingsForClient } from "#dynamic/lib/clientSettings"; + +export const olmClientSettingsBodySchema = z.strictObject({ + olmId: z.string().nonempty(), + secret: z.string().nonempty(), + orgId: z.string().optional() +}); + +export type OlmClientSettingsBody = z.infer; + +export type OlmClientSettingsResponse = { + settings: ClientSettings | null; + // The sites behind settings.exitNodeSiteResourceId. A machine client has + // no user session to look these up itself. Absent if no exit node is set, + // or if it is disabled, gone or has no sites. + exitNodeSiteIds?: number[]; +}; + +// Client settings for a client that authenticates with its olm ID and secret +// rather than a user session, i.e. a machine client. User devices use +// GET /org/:orgId/my-client-settings instead, though a user device's olm gets +// the same answer here. +export async function getOlmClientSettings( + req: Request, + res: Response, + next: NextFunction +): Promise { + const parsedBody = olmClientSettingsBodySchema.safeParse(req.body); + if (!parsedBody.success) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + fromError(parsedBody.error).toString() + ) + ); + } + + const { olmId, secret, orgId } = parsedBody.data; + + try { + const [olm] = await db + .select() + .from(olms) + .where(eq(olms.olmId, olmId)) + .limit(1); + + // Same response for an unknown olm and a wrong secret, so the + // endpoint can't be used to probe for olm IDs. + const validSecret = olm + ? await verifyPassword(secret, olm.secretHash) + : false; + if (!olm || !validSecret) { + if (config.getRawConfig().app.log_failed_attempts) { + logger.info( + `Olm client settings: olm id or secret is incorrect. Olm: ID ${olmId}. IP: ${req.ip}.` + ); + } + return next( + createHttpError( + HttpCode.UNAUTHORIZED, + "Olm ID or secret is incorrect" + ) + ); + } + + const clientFilter = orgId + ? and(eq(clients.orgId, orgId), eq(clients.olmId, olmId)) + : olm.clientId + ? eq(clients.clientId, olm.clientId) + : undefined; + if (!clientFilter) { + return next( + createHttpError( + HttpCode.BAD_REQUEST, + "Olm is not associated with a client, orgId is required" + ) + ); + } + + const [client] = await db + .select({ + clientId: clients.clientId, + orgId: clients.orgId, + userId: clients.userId + }) + .from(clients) + .where(clientFilter) + .limit(1); + if (!client) { + return next( + createHttpError(HttpCode.NOT_FOUND, "Client not found") + ); + } + + const settings = await getClientSettingsForClient(client); + + let exitNodeSiteIds: number[] | undefined; + if (settings?.exitNodeSiteResourceId) { + const rows = await db + .select({ siteId: siteNetworks.siteId }) + .from(siteResources) + .innerJoin( + siteNetworks, + eq(siteNetworks.networkId, siteResources.networkId) + ) + .where( + and( + eq( + siteResources.siteResourceId, + settings.exitNodeSiteResourceId + ), + eq(siteResources.orgId, client.orgId), + eq(siteResources.mode, "gateway"), + eq(siteResources.enabled, true) + ) + ); + if (rows.length > 0) { + exitNodeSiteIds = rows.map((r) => r.siteId); + } + } + + return response(res, { + data: { settings: settings ?? null, exitNodeSiteIds }, + success: true, + error: false, + message: "Client settings retrieved successfully", + status: HttpCode.OK + }); + } catch (error) { + logger.error(error); + return next( + createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "An error occurred") + ); + } +} diff --git a/server/routers/olm/index.ts b/server/routers/olm/index.ts index f02672b77..9e92fedbe 100644 --- a/server/routers/olm/index.ts +++ b/server/routers/olm/index.ts @@ -1,5 +1,6 @@ export * from "./handleOlmRegisterMessage"; export * from "./getOlmToken"; +export * from "./getOlmClientSettings"; export * from "./createUserOlm"; export * from "./handleOlmRelayMessage"; export * from "./handleOlmPingMessage";