feat(twenty-server): introduce ENCRYPTION_KEY env var with versioned envelope (#20528)

## Summary

- Adds `ENCRYPTION_KEY` (primary) and `FALLBACK_ENCRYPTION_KEY`
(decrypt-only fallback for rotation) env vars to twenty-server, with
backward-compatible fallback to `APP_SECRET` when `ENCRYPTION_KEY` is
unset.
- Introduces a versioned ciphertext envelope `enc:v2:<keyId>:<base64>`
using AES-256-GCM with HKDF-SHA256 derived per-context keys. The 8-hex
`keyId` fingerprint lets every row identify which physical key encrypted
it, so rotation routes directly to primary or fallback without trial
decryption; GCM's auth tag gives true integrity (legacy CTR has none).
- Migrates `ConnectedAccountTokenEncryptionService` to the new envelope
and plumbs `workspaceId` through every caller, so per-workspace HKDF
context binds each row to its tenant.

The remaining encryption sites (`jwt-key-manager`, `config-storage`,
`postgres-credentials`, `application-variable`, TOTP) stay on the legacy
unprefixed CTR path and will be migrated in follow-up PRs. The
operator-facing rotation runbook is out of scope here.

### Format details

`enc:v{N}:{keyId}:{base64}` — `N=2` is the only version produced by new
writes (`v1` exists for backward-compatible decryption of existing
connected-account rows). `keyId =
sha256(rawKey).slice(0,4).toString('hex')`. The CHECK constraint on
`core.connectedAccount.{accessToken,refreshToken}` is relaxed from `LIKE
'enc:v1:%'` to `LIKE 'enc:v_:%'` so both versions pass.

### Key resolution

| `ENCRYPTION_KEY` | `FALLBACK_ENCRYPTION_KEY` | `APP_SECRET` | Encrypt
with | Decrypt try order |
|---|---|---|---|---|
| set | set | (any) | `ENCRYPTION_KEY` | match `keyId` → primary →
fallback |
| set | unset | (any) | `ENCRYPTION_KEY` | match `keyId` → primary |
| unset | set | set | `APP_SECRET` | match `keyId` → `APP_SECRET` →
fallback |
| unset | unset | set | `APP_SECRET` | match `keyId` → `APP_SECRET` |
| unset | unset | unset | startup error | n/a |

## Test plan

- [x] `npx nx typecheck twenty-server` — clean
- [x] `npx jest
'secret-encryption|connected-account-token-encryption|connected-account-refresh-tokens|encrypt-connected-account-tokens|connection-provider-oauth-flow'`
— 87 tests pass
- [x] New `secret-encryption.service.versioned.spec.ts` covers: key
resolution table (no-key error, APP_SECRET fallback, ENCRYPTION_KEY
precedence), v2 round-trip with/without workspaceId, GCM tamper
rejection, workspaceId-mismatch rejection, keyId-based primary→fallback
routing, missing-key error names the fingerprint, v1 legacy decryption,
no-prefix legacy decryption, malformed envelope rejection.
- [x] Updated `connected-account-token-encryption.service.spec.ts`
covers workspaceId binding and HKDF context isolation.
- [x] Updated slow instance command spec verifies workspaceId is
threaded through encryption and the relaxed `enc:v_:%` LIKE pattern
matches both v1 and v2.
- [ ] Manual E2E: connect a Gmail account on a freshly deployed instance
with `APP_SECRET` only → confirm `core.connectedAccount.accessToken` is
`enc:v2:<keyId>:<base64>`.
- [ ] Manual E2E: rotate — set `ENCRYPTION_KEY=<new>` and
`FALLBACK_ENCRYPTION_KEY=<old APP_SECRET>`, restart, confirm
pre-rotation rows still decrypt and new rows carry the new `keyId`.
- [ ] Manual E2E: missing key — set `ENCRYPTION_KEY=<new>` without the
fallback, confirm decrypt error names the old `keyId` so the operator
can identify the missing key.
This commit is contained in:
Charles Bochet
2026-05-13 18:15:54 +02:00
committed by GitHub
parent aec2e01662
commit e0b4c9918b
60 changed files with 1687 additions and 394 deletions
@@ -13,6 +13,7 @@ import { Test, type TestingModule } from '@nestjs/testing';
import { getRepositoryToken } from '@nestjs/typeorm';
import { ConnectedAccountProvider } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
import { ConnectionProviderOAuthFlowService } from 'src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service';
@@ -21,11 +22,11 @@ import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/auth-contex
import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
import { SecureHttpClientService } from 'src/engine/core-modules/secure-http-client/secure-http-client.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX } from 'src/engine/core-modules/secret-encryption/constants/secret-encryption.constant';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
import {
CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX,
ConnectedAccountTokenEncryptionService,
} from 'src/engine/metadata-modules/connected-account/services/connected-account-token-encryption.service';
import { ConnectedAccountTokenEncryptionService } from 'src/engine/metadata-modules/connected-account/services/connected-account-token-encryption.service';
const FAKE_CIPHER_PREFIX = `${SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX}keyid:`;
describe('ConnectionProviderOAuthFlowService', () => {
let service: ConnectionProviderOAuthFlowService;
@@ -125,12 +126,12 @@ describe('ConnectionProviderOAuthFlowService', () => {
}: {
accessToken: string;
refreshToken: string | null;
workspaceId: string;
}) => ({
encryptedAccessToken: `${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}CIPHER(${accessToken})`,
encryptedRefreshToken:
refreshToken === null
? null
: `${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}CIPHER(${refreshToken})`,
encryptedAccessToken: `${FAKE_CIPHER_PREFIX}CIPHER(${accessToken})`,
encryptedRefreshToken: isDefined(refreshToken)
? `${FAKE_CIPHER_PREFIX}CIPHER(${refreshToken})`
: null,
}),
),
},
@@ -344,8 +345,8 @@ describe('ConnectionProviderOAuthFlowService', () => {
expect(connectedAccountRepository.create).toHaveBeenCalledWith(
expect.objectContaining({
provider: ConnectedAccountProvider.APP,
accessToken: `${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}CIPHER(new_access)`,
refreshToken: `${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}CIPHER(new_refresh)`,
accessToken: `${FAKE_CIPHER_PREFIX}CIPHER(new_access)`,
refreshToken: `${FAKE_CIPHER_PREFIX}CIPHER(new_refresh)`,
connectionProviderId: 'provider-1',
applicationId: 'app-1',
workspaceId: 'workspace-1',
@@ -372,8 +373,8 @@ describe('ConnectionProviderOAuthFlowService', () => {
expect(connectedAccountRepository.update).toHaveBeenCalledWith(
{ id: 'existing-account-id', workspaceId: 'workspace-1' },
expect.objectContaining({
accessToken: `${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}CIPHER(new_access)`,
refreshToken: `${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}CIPHER(new_refresh)`,
accessToken: `${FAKE_CIPHER_PREFIX}CIPHER(new_access)`,
refreshToken: `${FAKE_CIPHER_PREFIX}CIPHER(new_refresh)`,
authFailedAt: null,
visibility: 'user',
}),
@@ -248,6 +248,7 @@ export class ConnectionProviderOAuthFlowService {
this.connectedAccountTokenEncryptionService.encryptTokenPair({
accessToken: tokenResponse.accessToken,
refreshToken: tokenResponse.refreshToken,
workspaceId,
});
const sharedFields = {
@@ -44,9 +44,10 @@ export class AppOAuthRevokeService {
try {
const decryptedAccessToken =
this.connectedAccountTokenEncryptionService.decrypt(
connectedAccount.accessToken,
);
this.connectedAccountTokenEncryptionService.decrypt({
ciphertext: connectedAccount.accessToken,
workspaceId: connectedAccount.workspaceId,
});
const response = await this.secureHttpClientService.createSsrfSafeFetch()(
revokeEndpoint,
@@ -91,6 +91,7 @@ export class CreateConnectedAccountService {
this.connectedAccountTokenEncryptionService.encryptTokenPair({
accessToken,
refreshToken,
workspaceId,
});
await input.transactionManager
@@ -38,6 +38,7 @@ export class UpdateConnectedAccountOnReconnectService {
this.connectedAccountTokenEncryptionService.encryptTokenPair({
accessToken,
refreshToken,
workspaceId,
});
const authContext = buildSystemAuthContext(workspaceId);
@@ -0,0 +1,10 @@
export const SECRET_ENCRYPTION_ENVELOPE_PREFIX = 'enc:';
export const SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX = 'enc:v2:';
export const SECRET_ENCRYPTION_KEY_ID_REGEX = /^[0-9a-f]{8}$/;
export const SECRET_ENCRYPTION_GCM_IV_LENGTH = 12;
export const SECRET_ENCRYPTION_GCM_TAG_LENGTH = 16;
export const SECRET_ENCRYPTION_DERIVED_KEY_LENGTH = 32;
export const SECRET_ENCRYPTION_HKDF_INFO_PREFIX = 'twenty:enc:v2:';
export const SECRET_ENCRYPTION_INSTANCE_CONTEXT = 'instance';
@@ -0,0 +1,46 @@
import { type MessageDescriptor } from '@lingui/core';
import { msg } from '@lingui/core/macro';
import { assertUnreachable } from 'twenty-shared/utils';
import { CustomException } from 'src/utils/custom-exception';
export enum SecretEncryptionExceptionCode {
NO_ENCRYPTION_KEY_CONFIGURED = 'NO_ENCRYPTION_KEY_CONFIGURED',
UNKNOWN_KEY_ID = 'UNKNOWN_KEY_ID',
MALFORMED_ENVELOPE = 'MALFORMED_ENVELOPE',
UNKNOWN_ENVELOPE_VERSION = 'UNKNOWN_ENVELOPE_VERSION',
INVALID_KEY_ID_FORMAT = 'INVALID_KEY_ID_FORMAT',
CIPHERTEXT_TOO_SHORT = 'CIPHERTEXT_TOO_SHORT',
ALREADY_ENCRYPTED = 'ALREADY_ENCRYPTED',
}
const getSecretEncryptionExceptionUserFriendlyMessage = (
code: SecretEncryptionExceptionCode,
) => {
switch (code) {
case SecretEncryptionExceptionCode.NO_ENCRYPTION_KEY_CONFIGURED:
case SecretEncryptionExceptionCode.UNKNOWN_KEY_ID:
case SecretEncryptionExceptionCode.MALFORMED_ENVELOPE:
case SecretEncryptionExceptionCode.UNKNOWN_ENVELOPE_VERSION:
case SecretEncryptionExceptionCode.INVALID_KEY_ID_FORMAT:
case SecretEncryptionExceptionCode.CIPHERTEXT_TOO_SHORT:
case SecretEncryptionExceptionCode.ALREADY_ENCRYPTED:
return msg`An internal error occurred while handling encrypted data.`;
default:
assertUnreachable(code);
}
};
export class SecretEncryptionException extends CustomException<SecretEncryptionExceptionCode> {
constructor(
message: string,
code: SecretEncryptionExceptionCode,
{ userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
) {
super(message, code, {
userFriendlyMessage:
userFriendlyMessage ??
getSecretEncryptionExceptionUserFriendlyMessage(code),
});
}
}
@@ -1,41 +1,57 @@
import { Injectable } from '@nestjs/common';
import { Injectable, Logger } from '@nestjs/common';
import { isDefined } from 'twenty-shared/utils';
import {
decryptText,
encryptText,
} from 'src/engine/core-modules/auth/auth.util';
import { EnvironmentConfigDriver } from 'src/engine/core-modules/twenty-config/drivers/environment-config.driver';
import { computeEncryptionKeyId } from './utils/compute-encryption-key-id.util';
import { decryptAesCtrOrThrow } from './utils/decrypt-aes-ctr-or-throw.util';
import { decryptAesGcmV2OrThrow } from './utils/decrypt-aes-gcm-v2-or-throw.util';
import { encryptAesCtr } from './utils/encrypt-aes-ctr.util';
import { encryptAesGcmV2 } from './utils/encrypt-aes-gcm-v2.util';
import { formatSecretEncryptionEnvelopeV2 } from './utils/format-secret-encryption-envelope-v2.util';
import { parseSecretEncryptionEnvelopeOrThrow } from './utils/parse-secret-encryption-envelope-or-throw.util';
import { pickEncryptionKeyByKeyIdOrThrow } from './utils/pick-encryption-key-by-key-id-or-throw.util';
import { resolveEncryptionKeysOrThrow } from './utils/resolve-encryption-keys-or-throw.util';
type VersionedOptions = {
workspaceId?: string;
};
@Injectable()
export class SecretEncryptionService {
private readonly logger = new Logger(SecretEncryptionService.name);
private hasLoggedLegacyDecryption = false;
constructor(
private readonly environmentConfigDriver: EnvironmentConfigDriver,
) {}
private getAppSecret(): string {
return this.environmentConfigDriver.get('APP_SECRET');
}
public encrypt(value: string): string {
if (!isDefined(value)) {
return value;
}
const appSecret = this.getAppSecret();
const { primary } = resolveEncryptionKeysOrThrow({
environmentConfigDriver: this.environmentConfigDriver,
});
return encryptText(value, appSecret);
return encryptAesCtr({ plaintext: value, rawKey: primary });
}
// Legacy CTR has no integrity tag, so a wrong key produces an arbitrary
// byte sequence rather than throwing. Rotation of these rows requires
// migrating the consumer to the versioned envelope first.
public decrypt(value: string): string {
if (!isDefined(value)) {
return value;
}
const appSecret = this.getAppSecret();
const { primary } = resolveEncryptionKeysOrThrow({
environmentConfigDriver: this.environmentConfigDriver,
});
return decryptText(value, appSecret);
return decryptAesCtrOrThrow({ ciphertext: value, rawKey: primary });
}
public decryptAndMask({
@@ -50,7 +66,6 @@ export class SecretEncryptionService {
}
const decryptedValue = this.decrypt(value);
const visibleCharsCount = Math.min(
5,
Math.floor(decryptedValue.length / 10),
@@ -58,4 +73,61 @@ export class SecretEncryptionService {
return `${decryptedValue.slice(0, visibleCharsCount)}${mask}`;
}
public encryptVersioned(value: string, opts: VersionedOptions = {}): string {
if (!isDefined(value)) {
return value;
}
const { primary } = resolveEncryptionKeysOrThrow({
environmentConfigDriver: this.environmentConfigDriver,
});
const payloadBase64 = encryptAesGcmV2({
plaintext: value,
rawKey: primary,
workspaceId: opts.workspaceId,
});
const keyId = computeEncryptionKeyId({ rawKey: primary });
return formatSecretEncryptionEnvelopeV2({ keyId, payloadBase64 });
}
public decryptVersioned(value: string, opts: VersionedOptions = {}): string {
if (!isDefined(value)) {
return value;
}
const parsed = parseSecretEncryptionEnvelopeOrThrow({ value });
if (parsed.version === 2) {
const keys = resolveEncryptionKeysOrThrow({
environmentConfigDriver: this.environmentConfigDriver,
});
const rawKey = pickEncryptionKeyByKeyIdOrThrow({
keyId: parsed.keyId,
keys,
});
return decryptAesGcmV2OrThrow({
payloadBase64: parsed.payload,
rawKey,
workspaceId: opts.workspaceId,
});
}
this.warnLegacyDecryptionOnce();
return this.decrypt(value);
}
private warnLegacyDecryptionOnce(): void {
if (this.hasLoggedLegacyDecryption) {
return;
}
this.hasLoggedLegacyDecryption = true;
this.logger.warn(
'Decrypted a legacy unprefixed ciphertext. These rows should be re-encrypted into the enc:v2 envelope in a follow-up migration.',
);
}
}
@@ -0,0 +1,4 @@
export type ResolvedEncryptionKeys = {
primary: string;
fallback: string | null;
};
@@ -0,0 +1,3 @@
export type ParsedSecretEncryptionEnvelope =
| { version: 2; keyId: string; payload: string }
| { version: null };
@@ -0,0 +1,79 @@
import {
SecretEncryptionException,
SecretEncryptionExceptionCode,
} from 'src/engine/core-modules/secret-encryption/exceptions/secret-encryption.exception';
import { decryptAesGcmV2OrThrow } from 'src/engine/core-modules/secret-encryption/utils/decrypt-aes-gcm-v2-or-throw.util';
import { encryptAesGcmV2 } from 'src/engine/core-modules/secret-encryption/utils/encrypt-aes-gcm-v2.util';
describe('decryptAesGcmV2OrThrow', () => {
const KEY = 'gcm-test-key-zzzz1234567890abcdefghijkl';
it('throws when decrypting with a different workspaceId (HKDF context binding)', () => {
const ciphertext = encryptAesGcmV2({
plaintext: 'plaintext',
rawKey: KEY,
workspaceId: 'ws-1',
});
expect(() =>
decryptAesGcmV2OrThrow({
payloadBase64: ciphertext,
rawKey: KEY,
workspaceId: 'ws-2',
}),
).toThrow();
});
it('throws when decrypting with a different key', () => {
const ciphertext = encryptAesGcmV2({
plaintext: 'plaintext',
rawKey: KEY,
workspaceId: 'ws-1',
});
expect(() =>
decryptAesGcmV2OrThrow({
payloadBase64: ciphertext,
rawKey: 'wrong-key',
workspaceId: 'ws-1',
}),
).toThrow();
});
it('throws when the ciphertext payload has been tampered with (GCM auth tag)', () => {
const ciphertext = encryptAesGcmV2({
plaintext: 'plaintext',
rawKey: KEY,
workspaceId: 'ws-1',
});
// Base64 alphabet collisions and padding can make a 1-char flip a no-op.
// Decode, flip one byte in the middle, re-encode.
const buffer = Buffer.from(ciphertext, 'base64');
const middle = Math.floor(buffer.length / 2);
buffer[middle] = buffer[middle] ^ 0xff;
const tampered = buffer.toString('base64');
expect(() =>
decryptAesGcmV2OrThrow({
payloadBase64: tampered,
rawKey: KEY,
workspaceId: 'ws-1',
}),
).toThrow();
});
it('throws CIPHERTEXT_TOO_SHORT on a payload that cannot contain IV + tag', () => {
expect(() =>
decryptAesGcmV2OrThrow({
payloadBase64: 'AAAA',
rawKey: KEY,
workspaceId: 'ws-1',
}),
).toThrow(
expect.objectContaining({
code: SecretEncryptionExceptionCode.CIPHERTEXT_TOO_SHORT,
}) as SecretEncryptionException,
);
});
});
@@ -0,0 +1,77 @@
import { decryptAesGcmV2OrThrow } from 'src/engine/core-modules/secret-encryption/utils/decrypt-aes-gcm-v2-or-throw.util';
import { encryptAesGcmV2 } from 'src/engine/core-modules/secret-encryption/utils/encrypt-aes-gcm-v2.util';
describe('encryptAesGcmV2', () => {
const KEY = 'gcm-test-key-zzzz1234567890abcdefghijkl';
it('produces a base64 payload that round-trips with workspaceId context', () => {
const ciphertext = encryptAesGcmV2({
plaintext: 'plaintext',
rawKey: KEY,
workspaceId: 'ws-1',
});
expect(
decryptAesGcmV2OrThrow({
payloadBase64: ciphertext,
rawKey: KEY,
workspaceId: 'ws-1',
}),
).toBe('plaintext');
});
it('round-trips with no workspaceId (instance context)', () => {
const ciphertext = encryptAesGcmV2({ plaintext: 'plaintext', rawKey: KEY });
expect(
decryptAesGcmV2OrThrow({ payloadBase64: ciphertext, rawKey: KEY }),
).toBe('plaintext');
});
it('produces a different ciphertext for the same plaintext under a different workspaceId', () => {
const a = encryptAesGcmV2({
plaintext: 'plaintext',
rawKey: KEY,
workspaceId: 'ws-1',
});
const b = encryptAesGcmV2({
plaintext: 'plaintext',
rawKey: KEY,
workspaceId: 'ws-2',
});
expect(a).not.toBe(b);
});
it('produces a different ciphertext on every call (random IV)', () => {
const a = encryptAesGcmV2({
plaintext: 'plaintext',
rawKey: KEY,
workspaceId: 'ws-1',
});
const b = encryptAesGcmV2({
plaintext: 'plaintext',
rawKey: KEY,
workspaceId: 'ws-1',
});
expect(a).not.toBe(b);
});
it('handles unicode and long plaintexts', () => {
const plaintext = 'secret-with-émojis-🔐-and-中文-' + 'a'.repeat(2000);
const ciphertext = encryptAesGcmV2({
plaintext,
rawKey: KEY,
workspaceId: 'ws-1',
});
expect(
decryptAesGcmV2OrThrow({
payloadBase64: ciphertext,
rawKey: KEY,
workspaceId: 'ws-1',
}),
).toBe(plaintext);
});
});
@@ -0,0 +1,28 @@
import { SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX } from 'src/engine/core-modules/secret-encryption/constants/secret-encryption.constant';
import { formatSecretEncryptionEnvelopeV2 } from 'src/engine/core-modules/secret-encryption/utils/format-secret-encryption-envelope-v2.util';
import { parseSecretEncryptionEnvelopeOrThrow } from 'src/engine/core-modules/secret-encryption/utils/parse-secret-encryption-envelope-or-throw.util';
describe('formatSecretEncryptionEnvelopeV2', () => {
it('concatenates the v2 prefix, keyId, and payload', () => {
expect(
formatSecretEncryptionEnvelopeV2({
keyId: 'abcd1234',
payloadBase64: 'payload',
}),
).toBe(`${SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX}abcd1234:payload`);
});
it('round-trips with parseSecretEncryptionEnvelopeOrThrow', () => {
const envelope = formatSecretEncryptionEnvelopeV2({
keyId: 'deadbeef',
payloadBase64: 'cipherpayload',
});
const parsed = parseSecretEncryptionEnvelopeOrThrow({ value: envelope });
expect(parsed).toEqual({
version: 2,
keyId: 'deadbeef',
payload: 'cipherpayload',
});
});
});
@@ -0,0 +1,93 @@
import { SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX } from 'src/engine/core-modules/secret-encryption/constants/secret-encryption.constant';
import {
SecretEncryptionException,
SecretEncryptionExceptionCode,
} from 'src/engine/core-modules/secret-encryption/exceptions/secret-encryption.exception';
import { parseSecretEncryptionEnvelopeOrThrow } from 'src/engine/core-modules/secret-encryption/utils/parse-secret-encryption-envelope-or-throw.util';
describe('parseSecretEncryptionEnvelopeOrThrow', () => {
it('returns version: null for an unprefixed value', () => {
expect(
parseSecretEncryptionEnvelopeOrThrow({ value: 'opaque-base64-string' }),
).toEqual({ version: null });
});
it('returns version: null for the empty string', () => {
expect(parseSecretEncryptionEnvelopeOrThrow({ value: '' })).toEqual({
version: null,
});
});
it('parses a v2 envelope, splitting keyId and payload', () => {
expect(
parseSecretEncryptionEnvelopeOrThrow({
value: `${SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX}deadbeef:cipherpayload`,
}),
).toEqual({ version: 2, keyId: 'deadbeef', payload: 'cipherpayload' });
});
it('throws MALFORMED_ENVELOPE on a v2 envelope missing the keyId separator', () => {
expect(() =>
parseSecretEncryptionEnvelopeOrThrow({
value: `${SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX}no-separator`,
}),
).toThrow(
expect.objectContaining({
code: SecretEncryptionExceptionCode.MALFORMED_ENVELOPE,
}) as SecretEncryptionException,
);
});
it('throws MALFORMED_ENVELOPE on a v2 envelope with an empty keyId', () => {
expect(() =>
parseSecretEncryptionEnvelopeOrThrow({
value: `${SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX}:payload`,
}),
).toThrow(
expect.objectContaining({
code: SecretEncryptionExceptionCode.MALFORMED_ENVELOPE,
}) as SecretEncryptionException,
);
});
it('throws INVALID_KEY_ID_FORMAT when keyId is not 8 hex characters', () => {
expect(() =>
parseSecretEncryptionEnvelopeOrThrow({
value: `${SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX}NOTHEX!!:payload`,
}),
).toThrow(
expect.objectContaining({
code: SecretEncryptionExceptionCode.INVALID_KEY_ID_FORMAT,
}) as SecretEncryptionException,
);
});
it('throws INVALID_KEY_ID_FORMAT when keyId is shorter than 8 chars', () => {
expect(() =>
parseSecretEncryptionEnvelopeOrThrow({
value: `${SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX}abc:payload`,
}),
).toThrow(
expect.objectContaining({
code: SecretEncryptionExceptionCode.INVALID_KEY_ID_FORMAT,
}) as SecretEncryptionException,
);
});
it('throws UNKNOWN_ENVELOPE_VERSION on an unknown envelope version (including the dropped v1)', () => {
expect(() =>
parseSecretEncryptionEnvelopeOrThrow({ value: 'enc:v1:legacy' }),
).toThrow(
expect.objectContaining({
code: SecretEncryptionExceptionCode.UNKNOWN_ENVELOPE_VERSION,
}) as SecretEncryptionException,
);
expect(() =>
parseSecretEncryptionEnvelopeOrThrow({ value: 'enc:v99:whatever' }),
).toThrow(
expect.objectContaining({
code: SecretEncryptionExceptionCode.UNKNOWN_ENVELOPE_VERSION,
}) as SecretEncryptionException,
);
});
});
@@ -0,0 +1,66 @@
import {
SecretEncryptionException,
SecretEncryptionExceptionCode,
} from 'src/engine/core-modules/secret-encryption/exceptions/secret-encryption.exception';
import { computeEncryptionKeyId } from 'src/engine/core-modules/secret-encryption/utils/compute-encryption-key-id.util';
import { pickEncryptionKeyByKeyIdOrThrow } from 'src/engine/core-modules/secret-encryption/utils/pick-encryption-key-by-key-id-or-throw.util';
describe('pickEncryptionKeyByKeyIdOrThrow', () => {
const PRIMARY = 'primary-key-1234567890abcdefghij';
const FALLBACK = 'fallback-key-zyxwvutsrqponmlkjihgf';
it('returns the primary key when its fingerprint matches', () => {
const keyId = computeEncryptionKeyId({ rawKey: PRIMARY });
expect(
pickEncryptionKeyByKeyIdOrThrow({
keyId,
keys: { primary: PRIMARY, fallback: null },
}),
).toBe(PRIMARY);
});
it('returns the fallback key when its fingerprint matches', () => {
const keyId = computeEncryptionKeyId({ rawKey: FALLBACK });
expect(
pickEncryptionKeyByKeyIdOrThrow({
keyId,
keys: { primary: PRIMARY, fallback: FALLBACK },
}),
).toBe(FALLBACK);
});
it('prefers primary when both fingerprints would match', () => {
const keyId = computeEncryptionKeyId({ rawKey: PRIMARY });
expect(
pickEncryptionKeyByKeyIdOrThrow({
keyId,
keys: { primary: PRIMARY, fallback: PRIMARY },
}),
).toBe(PRIMARY);
});
it('throws UNKNOWN_KEY_ID when no configured key matches', () => {
expect(() =>
pickEncryptionKeyByKeyIdOrThrow({
keyId: 'deadbeef',
keys: { primary: PRIMARY, fallback: null },
}),
).toThrow(
expect.objectContaining({
code: SecretEncryptionExceptionCode.UNKNOWN_KEY_ID,
}) as SecretEncryptionException,
);
});
it('error message names the missing keyId for operator diagnostics', () => {
expect(() =>
pickEncryptionKeyByKeyIdOrThrow({
keyId: 'deadbeef',
keys: { primary: PRIMARY, fallback: null },
}),
).toThrow(/keyId 'deadbeef'/);
});
});
@@ -0,0 +1,83 @@
import {
SecretEncryptionException,
SecretEncryptionExceptionCode,
} from 'src/engine/core-modules/secret-encryption/exceptions/secret-encryption.exception';
import { resolveEncryptionKeysOrThrow } from 'src/engine/core-modules/secret-encryption/utils/resolve-encryption-keys-or-throw.util';
import { type EnvironmentConfigDriver } from 'src/engine/core-modules/twenty-config/drivers/environment-config.driver';
type EnvMap = Partial<{
ENCRYPTION_KEY: string;
FALLBACK_ENCRYPTION_KEY: string;
APP_SECRET: string;
}>;
const buildDriver = (env: EnvMap): Pick<EnvironmentConfigDriver, 'get'> => ({
get: jest.fn((key: keyof EnvMap) => env[key]) as never,
});
describe('resolveEncryptionKeysOrThrow', () => {
it('throws NO_ENCRYPTION_KEY_CONFIGURED when no key is set', () => {
expect(() =>
resolveEncryptionKeysOrThrow({
environmentConfigDriver: buildDriver({}),
}),
).toThrow(
expect.objectContaining({
code: SecretEncryptionExceptionCode.NO_ENCRYPTION_KEY_CONFIGURED,
}) as SecretEncryptionException,
);
});
it('uses APP_SECRET as primary when ENCRYPTION_KEY is unset', () => {
const keys = resolveEncryptionKeysOrThrow({
environmentConfigDriver: buildDriver({ APP_SECRET: 'app' }),
});
expect(keys.primary).toBe('app');
expect(keys.fallback).toBeNull();
});
it('prefers ENCRYPTION_KEY over APP_SECRET when both are set', () => {
const keys = resolveEncryptionKeysOrThrow({
environmentConfigDriver: buildDriver({
ENCRYPTION_KEY: 'new',
APP_SECRET: 'old',
}),
});
expect(keys.primary).toBe('new');
});
it('exposes FALLBACK_ENCRYPTION_KEY when set', () => {
const keys = resolveEncryptionKeysOrThrow({
environmentConfigDriver: buildDriver({
ENCRYPTION_KEY: 'new',
FALLBACK_ENCRYPTION_KEY: 'old',
}),
});
expect(keys.primary).toBe('new');
expect(keys.fallback).toBe('old');
});
it('returns null fallback when FALLBACK_ENCRYPTION_KEY is unset', () => {
const keys = resolveEncryptionKeysOrThrow({
environmentConfigDriver: buildDriver({ ENCRYPTION_KEY: 'new' }),
});
expect(keys.fallback).toBeNull();
});
it('treats empty-string env vars as unset', () => {
const keys = resolveEncryptionKeysOrThrow({
environmentConfigDriver: buildDriver({
ENCRYPTION_KEY: '',
APP_SECRET: 'app',
FALLBACK_ENCRYPTION_KEY: '',
}),
});
expect(keys.primary).toBe('app');
expect(keys.fallback).toBeNull();
});
});
@@ -0,0 +1,7 @@
import { createHash } from 'crypto';
export const computeEncryptionKeyId = ({
rawKey,
}: {
rawKey: string;
}): string => createHash('sha256').update(rawKey).digest('hex').slice(0, 8);
@@ -0,0 +1,23 @@
import { createDecipheriv, createHash } from 'crypto';
const deriveCtrKey = (rawKey: string): string =>
createHash('sha512').update(rawKey).digest('hex').substring(0, 32);
// AES-CTR has no integrity tag, so a wrong key produces an arbitrary byte
// sequence instead of throwing. `OrThrow` reflects only the malformed-input
// failures from Node crypto (e.g. invalid base64).
export const decryptAesCtrOrThrow = ({
ciphertext,
rawKey,
}: {
ciphertext: string;
rawKey: string;
}): string => {
const buffer = Buffer.from(ciphertext, 'base64');
const iv = buffer.subarray(0, 16);
const payload = buffer.subarray(16);
const keyHash = deriveCtrKey(rawKey);
const decipher = createDecipheriv('aes-256-ctr', keyHash, iv);
return Buffer.concat([decipher.update(payload), decipher.final()]).toString();
};
@@ -0,0 +1,52 @@
import { createDecipheriv } from 'crypto';
import {
SECRET_ENCRYPTION_GCM_IV_LENGTH,
SECRET_ENCRYPTION_GCM_TAG_LENGTH,
} from 'src/engine/core-modules/secret-encryption/constants/secret-encryption.constant';
import {
SecretEncryptionException,
SecretEncryptionExceptionCode,
} from 'src/engine/core-modules/secret-encryption/exceptions/secret-encryption.exception';
import { deriveGcmKey } from 'src/engine/core-modules/secret-encryption/utils/derive-gcm-key.util';
export const decryptAesGcmV2OrThrow = ({
payloadBase64,
rawKey,
workspaceId,
}: {
payloadBase64: string;
rawKey: string;
workspaceId?: string;
}): string => {
const buffer = Buffer.from(payloadBase64, 'base64');
if (
buffer.length <
SECRET_ENCRYPTION_GCM_IV_LENGTH + SECRET_ENCRYPTION_GCM_TAG_LENGTH
) {
throw new SecretEncryptionException(
'v2 ciphertext payload is too short to contain an IV and an auth tag.',
SecretEncryptionExceptionCode.CIPHERTEXT_TOO_SHORT,
);
}
const iv = buffer.subarray(0, SECRET_ENCRYPTION_GCM_IV_LENGTH);
const authTag = buffer.subarray(
buffer.length - SECRET_ENCRYPTION_GCM_TAG_LENGTH,
);
const ciphertext = buffer.subarray(
SECRET_ENCRYPTION_GCM_IV_LENGTH,
buffer.length - SECRET_ENCRYPTION_GCM_TAG_LENGTH,
);
const key = deriveGcmKey({ rawKey, workspaceId });
const decipher = createDecipheriv('aes-256-gcm', key, iv);
decipher.setAuthTag(authTag);
return Buffer.concat([
decipher.update(ciphertext),
decipher.final(),
]).toString('utf8');
};
@@ -0,0 +1,30 @@
import { hkdfSync } from 'crypto';
import {
SECRET_ENCRYPTION_DERIVED_KEY_LENGTH,
SECRET_ENCRYPTION_HKDF_INFO_PREFIX,
SECRET_ENCRYPTION_INSTANCE_CONTEXT,
} from 'src/engine/core-modules/secret-encryption/constants/secret-encryption.constant';
const ZERO_SALT = Buffer.alloc(32);
export const deriveGcmKey = ({
rawKey,
workspaceId,
}: {
rawKey: string;
workspaceId?: string;
}): Buffer =>
Buffer.from(
hkdfSync(
'sha256',
Buffer.from(rawKey),
ZERO_SALT,
Buffer.from(
`${SECRET_ENCRYPTION_HKDF_INFO_PREFIX}${
workspaceId ?? SECRET_ENCRYPTION_INSTANCE_CONTEXT
}`,
),
SECRET_ENCRYPTION_DERIVED_KEY_LENGTH,
),
);
@@ -0,0 +1,20 @@
import { createCipheriv, createHash, randomBytes } from 'crypto';
const deriveCtrKey = (rawKey: string): string =>
createHash('sha512').update(rawKey).digest('hex').substring(0, 32);
export const encryptAesCtr = ({
plaintext,
rawKey,
}: {
plaintext: string;
rawKey: string;
}): string => {
const keyHash = deriveCtrKey(rawKey);
const iv = randomBytes(16);
const cipher = createCipheriv('aes-256-ctr', keyHash, iv);
return Buffer.concat([iv, cipher.update(plaintext), cipher.final()]).toString(
'base64',
);
};
@@ -0,0 +1,26 @@
import { createCipheriv, randomBytes } from 'crypto';
import { SECRET_ENCRYPTION_GCM_IV_LENGTH } from 'src/engine/core-modules/secret-encryption/constants/secret-encryption.constant';
import { deriveGcmKey } from 'src/engine/core-modules/secret-encryption/utils/derive-gcm-key.util';
export const encryptAesGcmV2 = ({
plaintext,
rawKey,
workspaceId,
}: {
plaintext: string;
rawKey: string;
workspaceId?: string;
}): string => {
const key = deriveGcmKey({ rawKey, workspaceId });
const iv = randomBytes(SECRET_ENCRYPTION_GCM_IV_LENGTH);
const cipher = createCipheriv('aes-256-gcm', key, iv);
const ciphertext = Buffer.concat([
cipher.update(plaintext, 'utf8'),
cipher.final(),
]);
const authTag = cipher.getAuthTag();
return Buffer.concat([iv, ciphertext, authTag]).toString('base64');
};
@@ -0,0 +1,10 @@
import { SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX } from 'src/engine/core-modules/secret-encryption/constants/secret-encryption.constant';
export const formatSecretEncryptionEnvelopeV2 = ({
keyId,
payloadBase64,
}: {
keyId: string;
payloadBase64: string;
}): string =>
`${SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX}${keyId}:${payloadBase64}`;
@@ -0,0 +1,49 @@
import {
SECRET_ENCRYPTION_ENVELOPE_PREFIX,
SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX,
SECRET_ENCRYPTION_KEY_ID_REGEX,
} from 'src/engine/core-modules/secret-encryption/constants/secret-encryption.constant';
import {
SecretEncryptionException,
SecretEncryptionExceptionCode,
} from 'src/engine/core-modules/secret-encryption/exceptions/secret-encryption.exception';
import { type ParsedSecretEncryptionEnvelope } from 'src/engine/core-modules/secret-encryption/types/secret-encryption-envelope.type';
export const parseSecretEncryptionEnvelopeOrThrow = ({
value,
}: {
value: string;
}): ParsedSecretEncryptionEnvelope => {
if (!value.startsWith(SECRET_ENCRYPTION_ENVELOPE_PREFIX)) {
return { version: null };
}
if (value.startsWith(SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX)) {
const rest = value.slice(SECRET_ENCRYPTION_ENVELOPE_V2_PREFIX.length);
const separatorIndex = rest.indexOf(':');
if (separatorIndex <= 0) {
throw new SecretEncryptionException(
'Malformed enc:v2 envelope: missing keyId separator. Expected enc:v2:<keyId>:<payload>.',
SecretEncryptionExceptionCode.MALFORMED_ENVELOPE,
);
}
const keyId = rest.slice(0, separatorIndex);
const payload = rest.slice(separatorIndex + 1);
if (!SECRET_ENCRYPTION_KEY_ID_REGEX.test(keyId)) {
throw new SecretEncryptionException(
`Malformed enc:v2 envelope: keyId '${keyId}' is not 8 hex characters.`,
SecretEncryptionExceptionCode.INVALID_KEY_ID_FORMAT,
);
}
return { version: 2, keyId, payload };
}
throw new SecretEncryptionException(
`Unknown ciphertext envelope version. Value starts with '${value.slice(0, 16)}'.`,
SecretEncryptionExceptionCode.UNKNOWN_ENVELOPE_VERSION,
);
};
@@ -0,0 +1,32 @@
import { isDefined } from 'twenty-shared/utils';
import {
SecretEncryptionException,
SecretEncryptionExceptionCode,
} from 'src/engine/core-modules/secret-encryption/exceptions/secret-encryption.exception';
import { type ResolvedEncryptionKeys } from 'src/engine/core-modules/secret-encryption/types/resolved-encryption-keys.type';
import { computeEncryptionKeyId } from 'src/engine/core-modules/secret-encryption/utils/compute-encryption-key-id.util';
export const pickEncryptionKeyByKeyIdOrThrow = ({
keyId,
keys,
}: {
keyId: string;
keys: ResolvedEncryptionKeys;
}): string => {
if (computeEncryptionKeyId({ rawKey: keys.primary }) === keyId) {
return keys.primary;
}
if (
isDefined(keys.fallback) &&
computeEncryptionKeyId({ rawKey: keys.fallback }) === keyId
) {
return keys.fallback;
}
throw new SecretEncryptionException(
`No encryption key matches keyId '${keyId}'. Configure FALLBACK_ENCRYPTION_KEY with the key that encrypted this row.`,
SecretEncryptionExceptionCode.UNKNOWN_KEY_ID,
);
};
@@ -0,0 +1,35 @@
import { isNonEmptyString } from '@sniptt/guards';
import {
SecretEncryptionException,
SecretEncryptionExceptionCode,
} from 'src/engine/core-modules/secret-encryption/exceptions/secret-encryption.exception';
import { type ResolvedEncryptionKeys } from 'src/engine/core-modules/secret-encryption/types/resolved-encryption-keys.type';
import { type EnvironmentConfigDriver } from 'src/engine/core-modules/twenty-config/drivers/environment-config.driver';
export const resolveEncryptionKeysOrThrow = ({
environmentConfigDriver,
}: {
environmentConfigDriver: Pick<EnvironmentConfigDriver, 'get'>;
}): ResolvedEncryptionKeys => {
const encryptionKey = environmentConfigDriver.get('ENCRYPTION_KEY');
const fallbackEncryptionKey = environmentConfigDriver.get(
'FALLBACK_ENCRYPTION_KEY',
);
const appSecret = environmentConfigDriver.get('APP_SECRET');
const primary = isNonEmptyString(encryptionKey) ? encryptionKey : appSecret;
if (!isNonEmptyString(primary)) {
throw new SecretEncryptionException(
'No encryption key configured: set ENCRYPTION_KEY (or APP_SECRET for legacy deployments).',
SecretEncryptionExceptionCode.NO_ENCRYPTION_KEY_CONFIGURED,
);
}
const fallback = isNonEmptyString(fallbackEncryptionKey)
? fallbackEncryptionKey
: null;
return { primary, fallback };
};
@@ -1151,6 +1151,28 @@ export class ConfigVariables {
})
APP_SECRET: string;
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.SERVER_CONFIG,
isSensitive: true,
description:
'Primary key for at-rest encryption of secrets. Falls back to APP_SECRET when unset.',
isEnvOnly: true,
type: ConfigVariableType.STRING,
})
@IsOptional()
ENCRYPTION_KEY: string;
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.SERVER_CONFIG,
isSensitive: true,
description:
'Decrypt-only fallback key. During rotation, set this to the previous ENCRYPTION_KEY so rows encrypted with the old key remain readable.',
isEnvOnly: true,
type: ConfigVariableType.STRING,
})
@IsOptional()
FALLBACK_ENCRYPTION_KEY: string;
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.RATE_LIMITING,
description: 'Maximum number of records affected by mutations',
@@ -28,11 +28,11 @@ export type ConnectedAccountVisibility = 'user' | 'workspace';
@Index('IDX_CONNECTED_ACCOUNT_APPLICATION_ID', ['applicationId'])
@Check(
'CHK_connectedAccount_accessToken_encrypted',
`"accessToken" IS NULL OR "accessToken" LIKE 'enc:v1:%'`,
`"accessToken" IS NULL OR "accessToken" LIKE 'enc:v2:%'`,
)
@Check(
'CHK_connectedAccount_refreshToken_encrypted',
`"refreshToken" IS NULL OR "refreshToken" LIKE 'enc:v1:%'`,
`"refreshToken" IS NULL OR "refreshToken" LIKE 'enc:v2:%'`,
)
export class ConnectedAccountEntity extends WorkspaceRelatedEntity {
@PrimaryGeneratedColumn('uuid')
@@ -1,5 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`ConnectedAccountTokenEncryptionService encrypt should throw when given an already-prefixed value 1`] = `"ConnectedAccountTokenEncryptionService.encrypt received an already-prefixed value. This indicates a double-encryption bug — the caller is encrypting ciphertext."`;
exports[`ConnectedAccountTokenEncryptionService encryptTokenPair should throw when accessToken is already encrypted 1`] = `"ConnectedAccountTokenEncryptionService.encrypt received an already-prefixed value. This indicates a double-encryption bug — the caller is encrypting ciphertext."`;
@@ -1,151 +0,0 @@
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
import { type EnvironmentConfigDriver } from 'src/engine/core-modules/twenty-config/drivers/environment-config.driver';
import {
CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX,
ConnectedAccountTokenEncryptionService,
} from 'src/engine/metadata-modules/connected-account/services/connected-account-token-encryption.service';
describe('ConnectedAccountTokenEncryptionService', () => {
const buildEncryptionService = (): ConnectedAccountTokenEncryptionService => {
const environmentConfigDriver = {
get: jest.fn().mockReturnValue('mock-app-secret-for-testing-12345678'),
} as unknown as EnvironmentConfigDriver;
return new ConnectedAccountTokenEncryptionService(
new SecretEncryptionService(environmentConfigDriver),
);
};
describe('encrypt', () => {
it('should produce a value that starts with the enc:v1: prefix and hides the plaintext', () => {
const service = buildEncryptionService();
const plaintext = 'plaintext-token';
const ciphertext = service.encrypt(plaintext);
expect(
ciphertext.startsWith(CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX),
).toBe(true);
expect(ciphertext).not.toContain(plaintext);
});
it('should throw when given an already-prefixed value', () => {
const service = buildEncryptionService();
expect(() =>
service.encrypt(
`${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}already-encrypted`,
),
).toThrowErrorMatchingSnapshot();
});
});
describe('encryptNullable', () => {
it('should pass null through unchanged', () => {
const service = buildEncryptionService();
expect(service.encryptNullable(null)).toBeNull();
});
it('should encrypt non-null values like encrypt()', () => {
const service = buildEncryptionService();
const ciphertext = service.encryptNullable('plaintext');
expect(ciphertext).not.toBeNull();
expect(
ciphertext!.startsWith(CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX),
).toBe(true);
});
});
describe('decrypt', () => {
it('should roundtrip cleanly with encrypt()', () => {
const service = buildEncryptionService();
const plaintext = 'roundtrip-token-value';
expect(service.decrypt(service.encrypt(plaintext))).toBe(plaintext);
});
// v2.4.0 deployment-window tolerance. Should be patch to throw after v2.4.1
it.failing(
'should throw when given a value without the enc:v1: prefix',
() => {
const service = buildEncryptionService();
expect(() =>
service.decrypt('raw-plaintext-without-prefix'),
).toThrowErrorMatchingSnapshot();
},
);
});
describe('decryptNullable', () => {
it('should pass null through unchanged', () => {
const service = buildEncryptionService();
expect(service.decryptNullable(null)).toBeNull();
});
it('should decrypt non-null values like decrypt()', () => {
const service = buildEncryptionService();
const plaintext = 'rt-value';
const ciphertext = service.encrypt(plaintext);
expect(service.decryptNullable(ciphertext)).toBe(plaintext);
});
});
describe('encryptTokenPair', () => {
it('should encrypt both tokens and return them keyed as encrypted*', () => {
const service = buildEncryptionService();
const { encryptedAccessToken, encryptedRefreshToken } =
service.encryptTokenPair({
accessToken: 'at-plaintext',
refreshToken: 'rt-plaintext',
});
expect(
encryptedAccessToken.startsWith(
CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX,
),
).toBe(true);
expect(
encryptedRefreshToken!.startsWith(
CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX,
),
).toBe(true);
expect(service.decrypt(encryptedAccessToken)).toBe('at-plaintext');
expect(service.decrypt(encryptedRefreshToken!)).toBe('rt-plaintext');
});
it('should pass a null refreshToken through unencrypted', () => {
const service = buildEncryptionService();
const { encryptedAccessToken, encryptedRefreshToken } =
service.encryptTokenPair({
accessToken: 'at-plaintext',
refreshToken: null,
});
expect(
encryptedAccessToken.startsWith(
CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX,
),
).toBe(true);
expect(encryptedRefreshToken).toBeNull();
});
it('should throw when accessToken is already encrypted', () => {
const service = buildEncryptionService();
expect(() =>
service.encryptTokenPair({
accessToken: `${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}already-encrypted`,
refreshToken: 'rt-plaintext',
}),
).toThrowErrorMatchingSnapshot();
});
});
});
@@ -1,8 +1,13 @@
import { Injectable, Logger } from '@nestjs/common';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
import { isDefined } from 'twenty-shared/utils';
export const CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX = 'enc:v1:';
import {
SecretEncryptionException,
SecretEncryptionExceptionCode,
} from 'src/engine/core-modules/secret-encryption/exceptions/secret-encryption.exception';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
import { parseSecretEncryptionEnvelopeOrThrow } from 'src/engine/core-modules/secret-encryption/utils/parse-secret-encryption-envelope-or-throw.util';
@Injectable()
export class ConnectedAccountTokenEncryptionService {
@@ -14,69 +19,109 @@ export class ConnectedAccountTokenEncryptionService {
private readonly secretEncryptionService: SecretEncryptionService,
) {}
encrypt(plaintext: string): string {
if (plaintext.startsWith(CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX)) {
throw new Error(
'ConnectedAccountTokenEncryptionService.encrypt received an already-prefixed value. ' +
'This indicates a double-encryption bug — the caller is encrypting ciphertext.',
encrypt({
plaintext,
workspaceId,
}: {
plaintext: string;
workspaceId: string;
}): string {
if (this.looksLikeCiphertext(plaintext)) {
throw new SecretEncryptionException(
'ConnectedAccountTokenEncryptionService.encrypt received an already-encrypted envelope. This indicates a double-encryption bug — the caller is encrypting ciphertext.',
SecretEncryptionExceptionCode.ALREADY_ENCRYPTED,
);
}
return `${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}${this.secretEncryptionService.encrypt(plaintext)}`;
return this.secretEncryptionService.encryptVersioned(plaintext, {
workspaceId,
});
}
encryptNullable(plaintext: string | null): string | null {
if (plaintext === null) {
encryptNullable({
plaintext,
workspaceId,
}: {
plaintext: string | null;
workspaceId: string;
}): string | null {
if (!isDefined(plaintext)) {
return null;
}
return this.encrypt(plaintext);
return this.encrypt({ plaintext, workspaceId });
}
decrypt(ciphertext: string): string {
if (!ciphertext.startsWith(CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX)) {
// v2.4.0 deployment-window tolerance. Should be patch to throw after v2.4.1
// throw new Error(
// 'ConnectedAccountTokenEncryptionService.decrypt received a value without the ' +
// `'${CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX}' prefix. ` +
// 'This indicates the column was written without going through encrypt(), ' +
// 'or the value was read from a source other than core.connectedAccount.',
// );
// v2.4.0 rollout-window tolerance: rows written before the encryption
// backfill ran may still be plaintext. Returning them as-is lets the slow
// command finish; once it has run everywhere this branch can throw.
decrypt({
ciphertext,
workspaceId,
}: {
ciphertext: string;
workspaceId: string;
}): string {
const parsed = parseSecretEncryptionEnvelopeOrThrow({ value: ciphertext });
if (!isDefined(parsed.version)) {
this.logger.warn(
'Decrypted a legacy plaintext token. Expected during the 2.4.0 ' +
'rollout window until the slow instance command finishes backfilling.',
'Decrypted a legacy plaintext token. Expected during the rollout window until the slow instance command finishes backfilling.',
);
return ciphertext;
}
return this.secretEncryptionService.decrypt(
ciphertext.slice(CONNECTED_ACCOUNT_TOKEN_ENCRYPTION_PREFIX.length),
);
return this.secretEncryptionService.decryptVersioned(ciphertext, {
workspaceId,
});
}
decryptNullable(ciphertext: string | null): string | null {
if (ciphertext === null) {
decryptNullable({
ciphertext,
workspaceId,
}: {
ciphertext: string | null;
workspaceId: string;
}): string | null {
if (!isDefined(ciphertext)) {
return null;
}
return this.decrypt(ciphertext);
return this.decrypt({ ciphertext, workspaceId });
}
encryptTokenPair({
accessToken,
refreshToken,
workspaceId,
}: {
accessToken: string;
refreshToken: string | null;
workspaceId: string;
}): {
encryptedAccessToken: string;
encryptedRefreshToken: string | null;
} {
return {
encryptedAccessToken: this.encrypt(accessToken),
encryptedRefreshToken: this.encryptNullable(refreshToken),
encryptedAccessToken: this.encrypt({
plaintext: accessToken,
workspaceId,
}),
encryptedRefreshToken: this.encryptNullable({
plaintext: refreshToken,
workspaceId,
}),
};
}
private looksLikeCiphertext(value: string): boolean {
try {
const parsed = parseSecretEncryptionEnvelopeOrThrow({ value });
return parsed.version === 2;
} catch {
return false;
}
}
}