Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

8.1 KB
Raw Blame
/*
 * Copyright 2025 Daytona Platforms Inc.
 * Modified by BoxLite AI, 2025-2026
 * SPDX-License-Identifier: AGPL-3.0
 */

import { ConflictException, Injectable, Logger, NotFoundException } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { EntityManager, Repository, ArrayOverlap, FindOptionsWhere } from 'typeorm'
import { ApiKey } from './api-key.entity'
import { OrganizationResourcePermission } from '../organization/enums/organization-resource-permission.enum'
import { RedisLockProvider } from '../box/common/redis-lock.provider'
import { OnAsyncEvent } from '../common/decorators/on-async-event.decorator'
import { OrganizationEvents } from '../organization/constants/organization-events.constant'
import { OrganizationResourcePermissionsUnassignedEvent } from '../organization/events/organization-resource-permissions-unassigned.event'
import { OrganizationUserRemovedEvent } from '../organization/events/organization-user-removed.event'
import { TransactionalEvent } from '../common/events/transactional.event'
import { InjectRedis } from '@nestjs-modules/ioredis'
import Redis from 'ioredis'
import {
  apiKeyValidationCacheKey,
  extractKeyDisplayPrefix,
  generateApiKeyHash,
  generateApiKeyValue,
} from '../common/utils/api-key'
import { TypedConfigService } from '../config/typed-config.service'
import { randomUUID } from 'crypto'
import { Context } from '../common/context/context'
import { mutationFailureType, recordOutcomes } from '../common/utils/business-event.util'

@Injectable()
export class ApiKeyService {
  private readonly logger = new Logger(ApiKeyService.name)

  constructor(
    @InjectRepository(ApiKey)
    private apiKeyRepository: Repository<ApiKey>,
    private readonly redisLockProvider: RedisLockProvider,
    @InjectRedis() private readonly redis: Redis,
    private readonly configService: TypedConfigService,
  ) {}

  private getApiKeyPrefix(value: string): string {
    return extractKeyDisplayPrefix(value)
  }

  private getApiKeySuffix(value: string): string {
    return value.slice(-3)
  }

  async createApiKey(
    organizationId: string,
    userId: string,
    name: string,
    permissions: OrganizationResourcePermission[],
    ctx: Context,
    expiresAt?: Date,
    apiKeyValue?: string,
  ): Promise<{ apiKey: ApiKey; value: string }> {
    return recordOutcomes(
      { name: 'api_key.create', organizationId, correlationId: randomUUID(), ctx },
      () => this.persistApiKey(organizationId, userId, name, permissions, expiresAt, apiKeyValue),
      mutationFailureType,
    )
  }

  private async persistApiKey(
    organizationId: string,
    userId: string,
    name: string,
    permissions: OrganizationResourcePermission[],
    expiresAt?: Date,
    apiKeyValue?: string,
  ): Promise<{ apiKey: ApiKey; value: string }> {
    const existingKey = await this.apiKeyRepository.findOne({ where: { organizationId, userId, name } })
    if (existingKey) {
      throw new ConflictException('API key with this name already exists')
    }

    // User dashboard keys: env-split class from the deployment mode; the
    // brand prefix is operator-overridable via API_KEY_PREFIX (default `blk`).
    const value =
      apiKeyValue ||
      generateApiKeyValue(
        this.configService.getOrThrow('apiKey.prefix'),
        this.configService.get('production') ? 'live' : 'test',
      )

    const apiKey = await this.apiKeyRepository.save({
      organizationId,
      userId,
      name,
      keyHash: generateApiKeyHash(value),
      keyPrefix: this.getApiKeyPrefix(value),
      keySuffix: this.getApiKeySuffix(value),
      permissions,
      createdAt: new Date(),
      expiresAt,
    })

    return { apiKey, value }
  }

  async ensureApiKeyValue(
    organizationId: string,
    userId: string,
    name: string,
    permissions: OrganizationResourcePermission[],
    value: string,
    ctx: Context,
    expiresAt?: Date,
  ): Promise<{ apiKey: ApiKey; value: string }> {
    const keyHash = generateApiKeyHash(value)
    const existingKey = await this.apiKeyRepository.findOne({ where: { organizationId, userId, name } })

    if (existingKey) {
      if (existingKey.keyHash === keyHash) {
        return { apiKey: existingKey, value }
      }

      await this.deleteWithEntityManager(this.apiKeyRepository.manager, existingKey)
    }

    return this.createApiKey(organizationId, userId, name, permissions, ctx, expiresAt, value)
  }

  async getApiKeys(organizationId: string, userId?: string): Promise<ApiKey[]> {
    const apiKeys = await this.apiKeyRepository.find({
      where: { organizationId, userId },
      order: {
        lastUsedAt: {
          direction: 'DESC',
          nulls: 'LAST',
        },
        createdAt: 'DESC',
      },
    })

    return apiKeys
  }

  async getApiKeyByName(organizationId: string, userId: string, name: string): Promise<ApiKey> {
    const apiKey = await this.apiKeyRepository.findOne({
      where: {
        organizationId,
        userId,
        name,
      },
    })

    if (!apiKey) {
      throw new NotFoundException('API key not found')
    }

    return apiKey
  }

  async getApiKeyByValue(value: string): Promise<ApiKey> {
    return this.getApiKeyByHash(generateApiKeyHash(value))
  }

  async getApiKeyByHash(keyHash: string): Promise<ApiKey> {
    const apiKey = await this.apiKeyRepository.findOne({
      where: {
        keyHash,
      },
    })

    if (!apiKey) {
      throw new NotFoundException('API key not found')
    }

    return apiKey
  }

  async deleteApiKey(organizationId: string, userId: string, name: string): Promise<void> {
    const apiKey = await this.apiKeyRepository.findOne({ where: { organizationId, userId, name } })

    if (!apiKey) {
      throw new NotFoundException('API key not found')
    }

    await this.deleteWithEntityManager(this.apiKeyRepository.manager, apiKey)
  }

  async updateLastUsedAt(organizationId: string, userId: string, name: string, lastUsedAt: Date): Promise<void> {
    const cooldownKey = `api-key-last-used-update-${organizationId}-${userId}-${name}`

    const aquired = await this.redisLockProvider.lock(cooldownKey, 10)

    // redis for cooldown period - 10 seconds
    // prevents database flooding when multiple requests are made at the same time
    if (!aquired) {
      return
    }

    await this.apiKeyRepository.update(
      {
        organizationId,
        userId,
        name,
      },
      { lastUsedAt },
    )
  }

  private async deleteWithEntityManager(entityManager: EntityManager, apiKey: ApiKey): Promise<void> {
    await entityManager.remove(apiKey)
    // Invalidate cache when API key is deleted
    await this.invalidateApiKeyCache(apiKey.keyHash)
  }

  private async invalidateApiKeyCache(keyHash: string): Promise<void> {
    try {
      const cacheKey = apiKeyValidationCacheKey(keyHash)
      await this.redis.del(cacheKey)
      this.logger.debug(`Invalidated cache for API key: ${cacheKey}`)
    } catch (error) {
      this.logger.error('Error invalidating API key cache:', error)
    }
  }

  @OnAsyncEvent({
    event: OrganizationEvents.PERMISSIONS_UNASSIGNED,
  })
  async handleOrganizationResourcePermissionsUnassignedEvent(
    payload: OrganizationResourcePermissionsUnassignedEvent,
  ): Promise<void> {
    await this.revokeWithinTransaction(payload, {
      organizationId: payload.organizationId,
      userId: payload.userId,
      permissions: ArrayOverlap(payload.unassignedPermissions),
    })
  }

  @OnAsyncEvent({
    event: OrganizationEvents.USER_REMOVED,
  })
  async handleOrganizationUserRemovedEvent(payload: OrganizationUserRemovedEvent): Promise<void> {
    await this.revokeWithinTransaction(payload, {
      organizationId: payload.organizationId,
      userId: payload.userId,
    })
  }

  // Deletes the keys in the event's transaction, and clears their cached validation
  // only once it commits.
  private async revokeWithinTransaction(event: TransactionalEvent, where: FindOptionsWhere<ApiKey>): Promise<void> {
    const apiKeysToRevoke = await event.entityManager.find(ApiKey, { where })

    await event.entityManager.remove(apiKeysToRevoke)
    event.afterCommit(async () => {
      await Promise.all(apiKeysToRevoke.map((apiKey) => this.invalidateApiKeyCache(apiKey.keyHash)))
    })
  }
}