Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp
5.5 KB
Raw Blame
// SPDX-License-Identifier: AGPL-3.0-or-later

import {type AdminAuditAttribution, runWithAdminAuditAttribution} from '@app/api/admin/AdminAuditAttribution';
import {isOperatorRequest, readOperatorHostUser} from '@app/api/admin/operator/OperatorRequests';
import {createApplicationID, createUserID} from '@app/api/BrandedTypes';
import {assertMutableUserId} from '@app/api/constants/Core';
import {Logger} from '@app/api/Logger';
import type {User} from '@app/api/models/User';
import type {HonoEnv} from '@app/api/types/HonoEnv';
import {AdminACLs} from '@fluxer/constants/src/AdminACLs';
import {ADMIN_OAUTH2_APPLICATION_ID} from '@fluxer/constants/src/Core';
import {AccessDeniedError} from '@fluxer/errors/src/domains/core/AccessDeniedError';
import {MissingACLError} from '@fluxer/errors/src/domains/core/MissingACLError';
import {MissingPermissionsError} from '@fluxer/errors/src/domains/core/MissingPermissionsError';
import {UnauthorizedError} from '@fluxer/errors/src/domains/core/UnauthorizedError';
import {SnowflakeType} from '@fluxer/schema/src/primitives/SchemaPrimitives';
import type {Context} from 'hono';
import {createMiddleware} from 'hono/factory';

const ADMIN_OAUTH2_APPLICATION_ID_BRANDED = createApplicationID(ADMIN_OAUTH2_APPLICATION_ID);
type AdminAuthTokenType = 'bearer' | 'session' | 'admin_api_key' | 'operator';
const ADMIN_TARGET_USER_PARAMS = ['user_id', 'target_user_id'] as const;

function ensureBearerIsBuiltInAdminApplication(ctx: Context<HonoEnv>): void {
	if (ctx.get('oauthBearerApplicationId') !== ADMIN_OAUTH2_APPLICATION_ID_BRANDED) {
		throw new AccessDeniedError();
	}
}

function getAdminTokenType(ctx: Context<HonoEnv>): AdminAuthTokenType {
	const tokenType = ctx.get('authTokenType');
	if (tokenType === 'bearer' || tokenType === 'session' || tokenType === 'admin_api_key') {
		return tokenType;
	}
	if (tokenType === 'operator' && isOperatorRequest(ctx.req.raw)) {
		return tokenType;
	}
	throw new UnauthorizedError();
}

function ensureAdminCanAuthenticate(adminUser: User, tokenType: AdminAuthTokenType): void {
	if (tokenType === 'operator') {
		return;
	}
	if (!adminUser.acls.has(AdminACLs.AUTHENTICATE) && !adminUser.acls.has(AdminACLs.WILDCARD)) {
		throw new MissingPermissionsError();
	}
}

export function hasAdminACL(granted: ReadonlySet<string>, acl: string): boolean {
	return granted.has(acl) || granted.has(AdminACLs.WILDCARD);
}

export function requireGrantedAdminACLs(granted: ReadonlySet<string>, required: Iterable<string>): void {
	if (granted.has(AdminACLs.WILDCARD)) return;
	for (const acl of required) {
		if (!granted.has(acl)) throw new MissingACLError(acl);
	}
}

function hasAnyAdminACL(acls: Set<string>, requiredACLs: ReadonlyArray<string>): boolean {
	return acls.has(AdminACLs.WILDCARD) || requiredACLs.some((acl) => acls.has(acl));
}

function intersectAdminApiKeyACLs(keyAcls: ReadonlySet<string>, ownerAcls: ReadonlySet<string>): Set<string> {
	if (ownerAcls.has(AdminACLs.WILDCARD)) {
		return new Set(keyAcls);
	}
	if (keyAcls.has(AdminACLs.WILDCARD)) {
		return new Set(ownerAcls);
	}
	return new Set(Array.from(keyAcls).filter((acl) => ownerAcls.has(acl)));
}

function getRequestAdminACLs(ctx: Context<HonoEnv>, adminUser: User, tokenType: AdminAuthTokenType): Set<string> {
	if (tokenType === 'operator') {
		return new Set([AdminACLs.WILDCARD]);
	}
	if (tokenType === 'admin_api_key') {
		return intersectAdminApiKeyACLs(ctx.get('adminApiKeyAcls') ?? new Set(), adminUser.acls);
	}
	return adminUser.acls;
}

function getAdminAuditAttribution(ctx: Context<HonoEnv>, tokenType: AdminAuthTokenType): AdminAuditAttribution | null {
	if (tokenType === 'operator') {
		const hostUser = readOperatorHostUser(ctx.req.raw);
		return hostUser === null ? {via: 'rexctl'} : {via: 'rexctl', host_user: hostUser};
	}
	if (tokenType === 'admin_api_key') {
		const keyId = ctx.get('adminApiKeyId');
		return keyId === null || keyId === undefined ? null : {via: `api_key:${keyId}`};
	}
	return null;
}

function ensureAdminTargetIsMutable(ctx: Context<HonoEnv>): void {
	if (ctx.req.method === 'GET') {
		return;
	}
	for (const paramName of ADMIN_TARGET_USER_PARAMS) {
		const rawUserId = ctx.req.param(paramName);
		if (rawUserId === undefined) {
			continue;
		}
		const parsedUserId = SnowflakeType.safeParse(rawUserId);
		if (!parsedUserId.success) {
			continue;
		}
		assertMutableUserId(createUserID(parsedUserId.data));
	}
}

function requireAdminAccess(requiredACLs: ReadonlyArray<string>) {
	return createMiddleware<HonoEnv>(async (ctx, next) => {
		const adminUser = ctx.get('user');
		if (!adminUser) throw new UnauthorizedError();
		const tokenType = getAdminTokenType(ctx);
		if (tokenType === 'bearer') {
			ensureBearerIsBuiltInAdminApplication(ctx);
		}
		const requestAcls = getRequestAdminACLs(ctx, adminUser, tokenType);
		Logger.debug(
			{
				adminUserId: adminUser.id.toString(),
				acls: Array.from(requestAcls),
				requiredACLs,
				tokenType,
			},
			'Checking admin ACL requirements',
		);
		ensureAdminCanAuthenticate(adminUser, tokenType);
		if (!hasAnyAdminACL(requestAcls, requiredACLs)) {
			throw new MissingACLError(requiredACLs[0] ?? AdminACLs.AUTHENTICATE);
		}
		ensureAdminTargetIsMutable(ctx);
		ctx.set('adminUserId', adminUser.id);
		ctx.set('adminUserAcls', requestAcls);
		await runWithAdminAuditAttribution(getAdminAuditAttribution(ctx, tokenType), next);
	});
}

export function requireAdminACL(requiredACL: string) {
	return requireAdminAccess([requiredACL]);
}

export function requireAnyAdminACL(requiredACLs: Array<string>) {
	return requireAdminAccess(requiredACLs);
}