The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.
/*
* Copyright 2025 Daytona Platforms Inc.
* Modified by BoxLite AI, 2025-2026
* SPDX-License-Identifier: AGPL-3.0
*/
import { CanActivate, ExecutionContext, Injectable, Logger } from '@nestjs/common'
import { OrganizationService } from '../services/organization.service'
import { OrganizationUserService } from '../services/organization-user.service'
import { AuthContext, OrganizationAuthContext } from '../../common/interfaces/auth-context.interface'
import { SystemRole } from '../../user/enums/system-role.enum'
import { InjectRedis } from '@nestjs-modules/ioredis'
import Redis from 'ioredis'
import { Organization } from '../entities/organization.entity'
@Injectable()
export class OrganizationAccessGuard implements CanActivate {
protected readonly logger = new Logger(OrganizationAccessGuard.name)
@InjectRedis() private readonly redis: Redis
constructor(
private readonly organizationService: OrganizationService,
private readonly organizationUserService: OrganizationUserService,
) {}
async canActivate(context: ExecutionContext, currentPermissions = false): Promise<boolean> {
const request = context.switchToHttp().getRequest()
// TODO: initialize authContext safely
const authContext: AuthContext = request.user
if (!authContext) {
this.logger.warn('User object is undefined. Authentication may not be set up correctly.')
return false
}
// note: semantic parameter names must be used (avoid :id)
const organizationIdParam = this.resolveOrganizationIdParam(
request.params.organizationId || request.params.orgId || request.params.prefix,
authContext,
)
if (
authContext.role !== 'runner' &&
authContext.role !== 'proxy' &&
authContext.role !== 'region-proxy' &&
!organizationIdParam &&
!authContext.organizationId
) {
this.logger.warn('Organization ID missing from the request context.')
return false
}
if (
organizationIdParam &&
authContext.apiKey &&
authContext.apiKey.organizationId !== organizationIdParam &&
(authContext.role !== SystemRole.ADMIN || currentPermissions)
) {
this.logger.warn(
`Organization ID mismatch in the request context. Expected: ${organizationIdParam}, Actual: ${authContext.apiKey.organizationId}`,
)
return false
}
const organizationId = organizationIdParam || authContext.organizationId
if (!organizationId) {
this.logger.warn('Organization ID missing from the request context.')
return false
}
const organization = currentPermissions
? await this.organizationService.findOne(organizationId)
: await this.getCachedOrganization(organizationId)
if (!organization) {
this.logger.warn(`Organization not found. Organization ID: ${organizationId}`)
return false
}
const organizationAuthContext: OrganizationAuthContext = {
...authContext,
organizationId,
organization,
}
request.user = organizationAuthContext
if (authContext.role === SystemRole.ADMIN && !(currentPermissions && authContext.apiKey)) {
return true
}
// Machine credentials (runner, proxy, health check, ...) carry no user, and TypeORM
// drops a where condition whose value is undefined: looking up their membership
// would return an arbitrary member of the organization.
if (!authContext.userId) {
this.logger.warn(`No user in the request context. Organization ID: ${organizationId}`)
return false
}
const organizationUser = await this.organizationUserService.findOneCached(organizationId, authContext.userId)
if (!organizationUser) {
this.logger.warn(
`Organization user not found. User ID: ${authContext.userId}, Organization ID: ${organizationId}`,
)
return false
}
organizationAuthContext.organizationUser = organizationUser
request.user = organizationAuthContext
return true
}
private resolveOrganizationIdParam(organizationIdParam: string | undefined, authContext: AuthContext) {
// REST SDKs released before path_prefix support hardcoded `/v1/default/...`.
// API keys are already org-scoped, so preserve that legacy route shape by
// resolving `default` to the authenticated org instead of rejecting it.
if (organizationIdParam === 'default') {
return authContext.organizationId
}
return organizationIdParam
}
private async getCachedOrganization(organizationId: string): Promise<Organization | null> {
try {
const cachedOrganization = await this.redis.get(`organization:${organizationId}`)
if (cachedOrganization) {
const organization = JSON.parse(cachedOrganization)
if (organization.suspendedUntil != null) {
organization.suspendedUntil = new Date(organization.suspendedUntil)
}
return organization
}
const organization = await this.organizationService.findOne(organizationId)
if (organization) {
await this.redis.set(`organization:${organizationId}`, JSON.stringify(organization), 'EX', 10)
return organization
}
return null
} catch (error) {
this.logger.error('Error getting cached organization:', error)
return null
}
}
}