A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(api): hash generated app secrets with sha-256 (#3902)
Hampus7e315d1754b3
diff --git a/fluxer_api/src/api/admin/repositories/AdminApiKeyRepository.ts b/fluxer_api/src/api/admin/repositories/AdminApiKeyRepository.tsindex 8342fc9c9..9f760d3d2 100644--- a/fluxer_api/src/api/admin/repositories/AdminApiKeyRepository.ts+++ b/fluxer_api/src/api/admin/repositories/AdminApiKeyRepository.ts@@ -12,7 +12,7 @@ import {Db} from '@app/api/database/CassandraTypes';import type {AdminApiKeyByCreatorRow, AdminApiKeyRow} from '@app/api/database/types/AdminAuthTypes';import {AdminApiKey} from '@app/api/models/AdminApiKey';import {AdminApiKeys, AdminApiKeysByCreator} from '@app/api/Tables';-import {hashPassword} from '@app/api/utils/PasswordUtils';+import {hashStoredSecret} from '@app/api/utils/StoredSecret';export interface CreateAdminApiKeyData {name: string;@@ -32,7 +32,7 @@ function computeTtlSeconds(expiresAt: Date): number {export class AdminApiKeyRepository {async create(data: CreateAdminApiKeyData, createdBy: UserID, keyId: bigint, rawKey: string): Promise<AdminApiKey> {- const keyHash = await hashPassword(rawKey);+ const keyHash = hashStoredSecret(rawKey);const createdAt = new Date();const row: AdminApiKeyRow = {key_id: keyId,diff --git a/fluxer_api/src/api/admin/services/AdminApiKeyService.ts b/fluxer_api/src/api/admin/services/AdminApiKeyService.tsindex e7c7038df..5203c6c89 100644--- a/fluxer_api/src/api/admin/services/AdminApiKeyService.ts+++ b/fluxer_api/src/api/admin/services/AdminApiKeyService.ts@@ -6,7 +6,7 @@ import type {UserID} from '@app/api/BrandedTypes';import type {ISnowflakeService} from '@app/api/infrastructure/ISnowflakeService';import {requireGrantedAdminACLs} from '@app/api/middleware/AdminMiddleware';import type {AdminApiKey} from '@app/api/models/AdminApiKey';-import {verifyPassword} from '@app/api/utils/PasswordUtils';+import type {StoredSecretVerifier} from '@app/api/utils/StoredSecret';import {AdminApiKeyNotFoundError} from '@fluxer/errors/src/domains/admin/AdminApiKeyNotFoundError';import type {CreateAdminApiKeyRequest, UpdateAdminApiKeyRequest} from '@fluxer/schema/src/domains/admin/AdminSchemas';import {ms} from 'itty-time';@@ -50,6 +50,7 @@ export class AdminApiKeyService {constructor(private readonly adminApiKeyRepository: AdminApiKeyRepository,private readonly snowflakeService: ISnowflakeService,+ private readonly storedSecrets: StoredSecretVerifier,) {}private generateRawKey(keyId: bigint): string {@@ -149,7 +150,7 @@ export class AdminApiKeyService {) {return 'cached';}- const valid = await verifyPassword({password: rawKey, passwordHash: apiKey.keyHash});+ const valid = await this.storedSecrets.matches(`admin_api_key:${apiKey.keyId}`, rawKey, apiKey.keyHash);if (!valid) {return 'invalid';}diff --git a/fluxer_api/src/api/middleware/ServiceMiddleware.ts b/fluxer_api/src/api/middleware/ServiceMiddleware.tsindex ad08dde82..0b3ce6e92 100644--- a/fluxer_api/src/api/middleware/ServiceMiddleware.ts+++ b/fluxer_api/src/api/middleware/ServiceMiddleware.ts@@ -105,6 +105,7 @@ import {getReportRepository,getStorageService,getStoreBillingRepository,+ getStoredSecretVerifier,getStreamPreviewService,getSweegoWebhookService,getThemeService,@@ -716,6 +717,7 @@ class RequestServices implements RequestScopedServices {this.cachedOAuth2Service ??= new OAuth2Service(this.context, {applicationRepository: getApplicationRepository(),oauth2TokenRepository: getOAuth2TokenRepository(),+ storedSecrets: getStoredSecretVerifier(),});return this.cachedOAuth2Service;}diff --git a/fluxer_api/src/api/middleware/ServiceSingletons.ts b/fluxer_api/src/api/middleware/ServiceSingletons.tsindex 21a929835..84a1d23a0 100644--- a/fluxer_api/src/api/middleware/ServiceSingletons.ts+++ b/fluxer_api/src/api/middleware/ServiceSingletons.ts@@ -99,6 +99,7 @@ import {VisionarySlotRepository} from '@app/api/user/repositories/VisionarySlotRimport {UserActivityBuffer} from '@app/api/user/services/UserActivityBuffer';import {UserContactChangeLogService} from '@app/api/user/services/UserContactChangeLogService';import {awaitAll} from '@app/api/utils/ConcurrencyUtils';+import {StoredSecretVerifier} from '@app/api/utils/StoredSecret';import {UserPermissionUtils} from '@app/api/utils/UserPermissionUtils';import {VoiceP2pConnectionReportRepository} from '@app/api/voice/VoiceP2pConnectionReportRepository';import {VoiceRepository} from '@app/api/voice/VoiceRepository';@@ -177,6 +178,7 @@ export const getNatsConfigPublisher = singleton(export const getVisionarySlotRepository = singleton(() => new VisionarySlotRepository());export const getCacheService: () => ICacheService = singleton(() => new KVCacheProvider({client: getKVClient()}));+export const getStoredSecretVerifier = singleton(() => new StoredSecretVerifier(getCacheService()));export const getCustomBadgeCatalog = singleton(() =>new CustomBadgeCatalog({@@ -374,7 +376,9 @@ export const getReadStateService = singleton(() => new ReadStateService(getReadSexport const getDiscriminatorService = singleton(() => new DiscriminatorService(getUserRepository(), getCacheService(), getLimitConfigService()),);-export const getBotAuthService = singleton(() => new BotAuthService(getApplicationRepository(), getUserRepository()));+export const getBotAuthService = singleton(+ () => new BotAuthService(getApplicationRepository(), getUserRepository(), getStoredSecretVerifier()),+);export const getBotMfaMirrorService = singleton(() => new BotMfaMirrorService(getApplicationRepository(), getUserRepository(), getGatewayService()),);@@ -405,7 +409,7 @@ export const getEntityAssetService = singleton(new EntityAssetService(getStorageService(), getMediaService(), getAssetDeletionQueue(), getLimitConfigService()),);export const getAdminApiKeyService = singleton(- () => new AdminApiKeyService(getAdminApiKeyRepository(), getSnowflakeService()),+ () => new AdminApiKeyService(getAdminApiKeyRepository(), getSnowflakeService(), getStoredSecretVerifier()),);export const getAdminArchiveService = singleton(() =>diff --git a/fluxer_api/src/api/oauth/ApplicationService.ts b/fluxer_api/src/api/oauth/ApplicationService.tsindex 07641ea5c..74e0d0ec1 100644--- a/fluxer_api/src/api/oauth/ApplicationService.ts+++ b/fluxer_api/src/api/oauth/ApplicationService.ts@@ -19,8 +19,8 @@ import {assertTierAllows, NO_TIER_CONTEXT} from '@app/api/user/AccountTier';import {enforceFluxerTagChangeRateLimit} from '@app/api/user/FluxerTagChangeRateLimit';import {dispatchUserUpdate, hasPartialUserFieldsChanged} from '@app/api/user/UserMappers';import {runAllInOrder} from '@app/api/utils/ConcurrencyUtils';-import {hashPassword} from '@app/api/utils/PasswordUtils';import {randomBase64Url} from '@app/api/utils/SecretHash';+import {hashStoredSecret} from '@app/api/utils/StoredSecret';import {generateRandomUsername} from '@app/api/utils/UsernameGenerator';import {deriveUsernameFromDisplayName} from '@app/api/utils/UsernameSuggestionUtils';import {TierGatedActions} from '@fluxer/constants/src/AccountTierConstants';@@ -162,10 +162,10 @@ export class ApplicationService {token: botToken,hash: botTokenHash,preview: botTokenPreview,- } = await this.deps.botAuthService.generateBotToken(applicationId);+ } = this.deps.botAuthService.generateBotToken(applicationId);const botTokenCreatedAt = new Date();const clientSecret = randomBase64Url(32);- const clientSecretHash = await hashPassword(clientSecret);+ const clientSecretHash = hashStoredSecret(clientSecret);const clientSecretCreatedAt = new Date();const applicationRow: ApplicationRow = {application_id: applicationId,@@ -324,7 +324,7 @@ export class ApplicationService {if (application.botUserId === null) {throw new BotUserNotFoundError();}- const {token, hash, preview} = await this.deps.botAuthService.generateBotToken(applicationId);+ const {token, hash, preview} = this.deps.botAuthService.generateBotToken(applicationId);const botTokenCreatedAt = new Date();const currentRow = application.toRow();const updatedRow: ApplicationRow = {@@ -352,7 +352,7 @@ export class ApplicationService {}> {const application = await this.verifyOwnership(userId, applicationId);const clientSecret = randomBase64Url(32);- const clientSecretHash = await hashPassword(clientSecret);+ const clientSecretHash = hashStoredSecret(clientSecret);const clientSecretCreatedAt = new Date();const currentRow = application.toRow();const updatedRow: ApplicationRow = {diff --git a/fluxer_api/src/api/oauth/BotAuthService.ts b/fluxer_api/src/api/oauth/BotAuthService.tsindex a880cd555..c96b62591 100644--- a/fluxer_api/src/api/oauth/BotAuthService.ts+++ b/fluxer_api/src/api/oauth/BotAuthService.ts@@ -5,8 +5,8 @@ import type {ApplicationID, UserID} from '@app/api/BrandedTypes';import type {ApplicationRepository} from '@app/api/oauth/repositories/ApplicationRepository';import type {UserRepository} from '@app/api/user/repositories/UserRepository';import {canOwnerRunBots} from '@app/api/user/UserHelpers';-import {hashPassword, verifyPassword} from '@app/api/utils/PasswordUtils';import {randomBase64Url} from '@app/api/utils/SecretHash';+import {hashStoredSecret, type StoredSecretVerifier} from '@app/api/utils/StoredSecret';const VERIFIED_TOKEN_CACHE_LIMIT = 10_000;const VERIFIED_TOKEN_CACHE_TTL_MS = 10 * 60 * 1000;@@ -23,6 +23,7 @@ export class BotAuthService {constructor(private readonly applicationRepository: ApplicationRepository,private readonly users: Pick<UserRepository, 'findUnique'>,+ private readonly storedSecrets: StoredSecretVerifier,) {}private parseBotToken(token: string): {@@ -56,14 +57,19 @@ export class BotAuthService {return null;}const [isValid, owner] = await Promise.all([- this.verifyBotSecret(token, secret, application.botTokenHash),+ this.verifyBotSecret(applicationId, token, secret, application.botTokenHash),this.users.findUnique(application.ownerUserId),]);if (!isValid || (owner && !canOwnerRunBots(owner))) return null;return application.botUserId;}- private async verifyBotSecret(token: string, secret: string, botTokenHash: string): Promise<boolean> {+ private async verifyBotSecret(+ applicationId: ApplicationID,+ token: string,+ secret: string,+ botTokenHash: string,+ ): Promise<boolean> {const key = createHmac('sha256', this.verifiedTokenKey).update(token).update('\0')@@ -76,7 +82,7 @@ export class BotAuthService {this.verifiedTokens.set(key, cached);return cached.valid;}- const valid = await verifyPassword({password: secret, passwordHash: botTokenHash}).catch(() => false);+ const valid = await this.storedSecrets.matches(`bot_token:${applicationId}`, secret, botTokenHash);this.verifiedTokens.delete(key);this.verifiedTokens.set(key, {valid, expiresAt: now + VERIFIED_TOKEN_CACHE_TTL_MS});while (this.verifiedTokens.size > VERIFIED_TOKEN_CACHE_LIMIT) {@@ -87,13 +93,13 @@ export class BotAuthService {return valid;}- async generateBotToken(applicationId: ApplicationID): Promise<{+ generateBotToken(applicationId: ApplicationID): {token: string;hash: string;preview: string;- }> {+ } {const secret = randomBase64Url(32);- const hash = await hashPassword(secret);+ const hash = hashStoredSecret(secret);const preview = secret.slice(0, 8);const token = `${applicationId.toString()}.${secret}`;return {token, hash, preview};diff --git a/fluxer_api/src/api/oauth/OAuth2RequestService.ts b/fluxer_api/src/api/oauth/OAuth2RequestService.tsindex 6819fa6fd..fe6c0d9ce 100644--- a/fluxer_api/src/api/oauth/OAuth2RequestService.ts+++ b/fluxer_api/src/api/oauth/OAuth2RequestService.ts@@ -27,7 +27,6 @@ import type {OAuth2TokenRepository} from '@app/api/oauth/repositories/OAuth2Tokeimport {parseClientCredentials} from '@app/api/oauth/utils/ParseClientCredentials';import {isSignInRefused} from '@app/api/user/UserHelpers';import {mapUserToOAuthResponse, mapUserToPartialResponse} from '@app/api/user/UserMappers';-import {verifyPassword} from '@app/api/utils/PasswordUtils';import {canAuthorizeBotInvite, normalizeBotInvitePermissions} from '@fluxer/constants/src/BotPermissionUtils';import {ALL_PERMISSIONS} from '@fluxer/constants/src/ChannelConstants';import {JoinSourceTypes} from '@fluxer/constants/src/GuildConstants';@@ -181,11 +180,8 @@ export class OAuth2RequestService {if (!application) {throw new InvalidClientError();}- if (application.clientSecretHash) {- const valid = await verifyPassword({password: secret, passwordHash: application.clientSecretHash});- if (!valid) {- throw new InvalidClientError();- }+ if (!(await this.oauth2Service.clientSecretMatches(application, secret))) {+ throw new InvalidClientError();}return this.oauth2Service.introspect(params.form.token, applicationId);}diff --git a/fluxer_api/src/api/oauth/OAuth2Service.ts b/fluxer_api/src/api/oauth/OAuth2Service.tsindex 45afe6b19..e82382551 100644--- a/fluxer_api/src/api/oauth/OAuth2Service.ts+++ b/fluxer_api/src/api/oauth/OAuth2Service.ts@@ -17,8 +17,8 @@ import type {ApplicationRepository} from '@app/api/oauth/repositories/Applicatioimport type {OAuth2TokenRepository} from '@app/api/oauth/repositories/OAuth2TokenRepository';import {isSignInRefused} from '@app/api/user/UserHelpers';import {mapUserToOAuthResponse} from '@app/api/user/UserMappers';-import {verifyPassword} from '@app/api/utils/PasswordUtils';import {randomBase64Url} from '@app/api/utils/SecretHash';+import type {StoredSecretVerifier} from '@app/api/utils/StoredSecret';import {InvalidRequestError} from '@fluxer/errors/src/domains/core/InvalidRequestError';import {InvalidTokenError} from '@fluxer/errors/src/domains/core/InvalidTokenError';import {BotIsPrivateError} from '@fluxer/errors/src/domains/oauth/BotIsPrivateError';@@ -35,11 +35,13 @@ const ADMIN_SSO_TOKEN_SCOPES = ['identify', 'email'];interface OAuth2ServiceDeps {applicationRepository: ApplicationRepository;oauth2TokenRepository: OAuth2TokenRepository;+ storedSecrets: StoredSecretVerifier;}export class OAuth2Service {private applications: ApplicationRepository;private tokens: OAuth2TokenRepository;+ private storedSecrets: StoredSecretVerifier;constructor(private readonly apiContext: ApiContext,@@ -47,6 +49,16 @@ export class OAuth2Service {) {this.applications = deps.applicationRepository;this.tokens = deps.oauth2TokenRepository;+ this.storedSecrets = deps.storedSecrets;+ }++ async clientSecretMatches(application: Application, clientSecret: string): Promise<boolean> {+ if (!application.clientSecretHash) return true;+ return this.storedSecrets.matches(+ `client_secret:${application.applicationId}`,+ clientSecret,+ application.clientSecretHash,+ );}private async findActiveUser(userId: UserID) {@@ -225,15 +237,12 @@ export class OAuth2Service {);throw new MissingClientSecretError();}- if (application.clientSecretHash) {- const ok = await verifyPassword({password: clientSecret, passwordHash: application.clientSecretHash});- if (!ok) {- Logger.debug(- {application_id: application.applicationId.toString()},- 'OAuth2 client authentication: client_secret verification failed',- );- throw new InvalidClientSecretError();- }+ if (!(await this.clientSecretMatches(application, clientSecret))) {+ Logger.debug(+ {application_id: application.applicationId.toString()},+ 'OAuth2 client authentication: client_secret verification failed',+ );+ throw new InvalidClientSecretError();}return application;}@@ -444,11 +453,8 @@ export class OAuth2Service {if (!application) {throw new InvalidClientError();}- if (application.clientSecretHash) {- const valid = await verifyPassword({password: auth.clientSecret, passwordHash: application.clientSecretHash});- if (!valid) {- throw new InvalidClientSecretError();- }+ if (!(await this.clientSecretMatches(application, auth.clientSecret))) {+ throw new InvalidClientSecretError();}if (tokenTypeHint === 'refresh_token') {const refresh = await this.tokens.getRefreshToken(tokenStr);diff --git a/fluxer_api/src/api/oauth/repositories/ApplicationRepository.ts b/fluxer_api/src/api/oauth/repositories/ApplicationRepository.tsindex efa89def1..25c9aa181 100644--- a/fluxer_api/src/api/oauth/repositories/ApplicationRepository.ts+++ b/fluxer_api/src/api/oauth/repositories/ApplicationRepository.ts@@ -10,7 +10,7 @@ import {APPLICATION_COLUMNS} from '@app/api/database/types/OAuth2Types';import {getInstanceProductName} from '@app/api/instance/ProductName';import {Application} from '@app/api/models/Application';import {Applications, ApplicationsByOwner} from '@app/api/Tables';-import {hashPassword} from '@app/api/utils/PasswordUtils';+import {hashStoredSecret} from '@app/api/utils/StoredSecret';import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';import {ADMIN_OAUTH2_APPLICATION_ID} from '@fluxer/constants/src/Core';import {ForbiddenError} from '@fluxer/errors/src/domains/core/ForbiddenError';@@ -32,13 +32,13 @@ export function resetAdminSecretHashForTesting(): void {cachedAdminSecretHash = null;}-async function getAdminSecretHash(): Promise<string | null> {+function getAdminSecretHash(): string | null {const secret = Config.admin.oauthClientSecret;if (!secret) {return null;}if (cachedAdminSecretHash === null) {- cachedAdminSecretHash = await hashPassword(secret);+ cachedAdminSecretHash = hashStoredSecret(secret);}return cachedAdminSecretHash;}@@ -69,7 +69,7 @@ function buildAdminApplication(secretHash: string | null): Application {export class ApplicationRepository {async getApplication(applicationId: ApplicationID): Promise<Application | null> {if (applicationId === createApplicationID(ADMIN_OAUTH2_APPLICATION_ID)) {- const secretHash = await getAdminSecretHash();+ const secretHash = getAdminSecretHash();if (secretHash === null) {return null;}diff --git a/fluxer_api/src/api/utils/StoredSecret.ts b/fluxer_api/src/api/utils/StoredSecret.tsnew file mode 100644index 000000000..77d7f7961--- /dev/null+++ b/fluxer_api/src/api/utils/StoredSecret.ts@@ -0,0 +1,66 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {verifyPassword} from '@app/api/utils/PasswordUtils';+import {constantTimeEquals, secretMatchesHash, sha256Hex} from '@app/api/utils/SecretHash';+import type {ICacheService} from '@pkgs/cache/src/ICacheService';++const LEGACY_HASH_PREFIX = '$argon2';+const LEGACY_PROOF_TTL_SECONDS = 90 * 24 * 60 * 60;+const LEGACY_CONCURRENT_VERIFICATIONS = 2;+const LEGACY_QUEUED_VERIFICATIONS = 32;++export function hashStoredSecret(secret: string): string {+ return sha256Hex(secret);+}++export class StoredSecretVerifier {+ private activeLegacyVerifications = 0;+ private readonly legacyWaiters: Array<() => void> = [];++ constructor(private readonly cache: Pick<ICacheService, 'get' | 'set'>) {}++ async matches(scope: string, secret: string, storedHash: string): Promise<boolean> {+ if (!storedHash.startsWith(LEGACY_HASH_PREFIX)) {+ return secretMatchesHash(secret, storedHash);+ }+ const proofKey = `stored_secret_proof:${scope}:${sha256Hex(storedHash)}`;+ const proof = sha256Hex(`${secret}\0${storedHash}`);+ const knownProof = await this.cache.get<string>(proofKey).catch(() => null);+ if (knownProof) {+ return constantTimeEquals(knownProof, proof);+ }+ const release = await this.acquireLegacySlot();+ if (!release) {+ return false;+ }+ let valid: boolean;+ try {+ valid = await verifyPassword({password: secret, passwordHash: storedHash}).catch(() => false);+ } finally {+ release();+ }+ if (valid) {+ await this.cache.set(proofKey, proof, LEGACY_PROOF_TTL_SECONDS).catch(() => undefined);+ }+ return valid;+ }++ private async acquireLegacySlot(): Promise<(() => void) | null> {+ if (this.activeLegacyVerifications >= LEGACY_CONCURRENT_VERIFICATIONS) {+ if (this.legacyWaiters.length >= LEGACY_QUEUED_VERIFICATIONS) {+ return null;+ }+ await new Promise<void>((resolve) => this.legacyWaiters.push(resolve));+ } else {+ this.activeLegacyVerifications += 1;+ }+ return () => {+ const next = this.legacyWaiters.shift();+ if (next) {+ next();+ return;+ }+ this.activeLegacyVerifications -= 1;+ };+ }+}diff --git a/fluxer_api/src/api/utils/tests/StoredSecret.test.ts b/fluxer_api/src/api/utils/tests/StoredSecret.test.tsnew file mode 100644index 000000000..b0d98826e--- /dev/null+++ b/fluxer_api/src/api/utils/tests/StoredSecret.test.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import {hashPassword} from '@app/api/utils/PasswordUtils';+import {hashStoredSecret, StoredSecretVerifier} from '@app/api/utils/StoredSecret';+import argon2 from 'argon2';+import {describe, expect, it, vi} from 'vitest';++function memoryCache() {+ const values = new Map<string, unknown>();+ return {+ get: async <T>(key: string) => (values.get(key) as T | undefined) ?? null,+ set: async <T>(key: string, value: T) => {+ values.set(key, value);+ },+ };+}++describe('StoredSecretVerifier', () => {+ it('checks new hashes without argon2', async () => {+ const verify = vi.spyOn(argon2, 'verify');+ const verifier = new StoredSecretVerifier(memoryCache());+ const hash = hashStoredSecret('right');+ expect(await verifier.matches('bot_token:1', 'right', hash)).toBe(true);+ expect(await verifier.matches('bot_token:1', 'wrong', hash)).toBe(false);+ expect(verify).not.toHaveBeenCalled();+ verify.mockRestore();+ });++ it('rejects wrong secrets for a proven legacy hash without argon2', async () => {+ const verifier = new StoredSecretVerifier(memoryCache());+ const hash = await hashPassword('right');+ expect(await verifier.matches('bot_token:1', 'right', hash)).toBe(true);+ const verify = vi.spyOn(argon2, 'verify');+ expect(await verifier.matches('bot_token:1', 'wrong', hash)).toBe(false);+ expect(await verifier.matches('bot_token:1', 'right', hash)).toBe(true);+ expect(verify).not.toHaveBeenCalled();+ verify.mockRestore();+ });++ it('does not reuse a proof for a different legacy hash', async () => {+ const verifier = new StoredSecretVerifier(memoryCache());+ expect(await verifier.matches('bot_token:1', 'old', await hashPassword('old'))).toBe(true);+ expect(await verifier.matches('bot_token:1', 'new', await hashPassword('new'))).toBe(true);+ });+});