Skip to content

Commit

Permalink
worked on reading private env variables
Browse files Browse the repository at this point in the history
  • Loading branch information
IshanBhatBhardwaj committed Sep 16, 2024
1 parent f781abf commit 9d13da2
Show file tree
Hide file tree
Showing 7 changed files with 57 additions and 33 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/run-unit-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
NEXT_PUBLIC_SUPABASE_URL: http://127.0.0.1:54321
NEXT_PUBLIC_SUPABASE_ANON_KEY: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0
SUPABASE_SERVICE_ROLE_KEY: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU
CRYPTO_KEY_1: DvViBWSQfwFGSetPOVbIWZrMXYJh4wTVSE/+1QI/VTI=
CRYPTO_KEY: DvViBWSQfwFGSetPOVbIWZrMXYJh4wTVSE/+1QI/VTI=
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
Expand Down
10 changes: 6 additions & 4 deletions scripts/create-cryptoKey.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ const path = require('path');

(async () => {
try {
//count how many cryptoKey we have
const cryptoKeyName = process.argv.slice(2);

const envFilePath = path.join(__dirname, '../.env');
const envFileContent = await fs.readFile(envFilePath, 'utf-8');
const cryptoKeyCount = (envFileContent.match(/CRYPTO_KEY_/g) || []).length;
let newKeyName = `CRYPTO_KEY`;

const newKeyName = `CRYPTO_KEY_${cryptoKeyCount + 1}`;
if (cryptoKeyName.length >= 1) {
newKeyName += `_${cryptoKeyName[0]}`;
}

const cryptoKey = await crypto.subtle.generateKey(
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ describe('VoterRegistrationRepository class', () => {
if (!dbUser) throw new Error('no user found');

const decryptInformation = async (encryptedObject: typeof registerBody) => {
const cryptoKey = await PRIVATE_ENVIRONMENT_VARIABLES.CRYPTO_KEY_1;
const cryptoKey = PRIVATE_ENVIRONMENT_VARIABLES.CRYPTO_KEY["CRYPTO_KEY"];

const decryptedObject = { ...encryptedObject };
for (const [key, value] of Object.entries(decryptedObject)) {
Expand Down
15 changes: 14 additions & 1 deletion src/constants/private-environment-variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,17 @@ import { readPrivateEnvironmentVariables } from '@/utils/environment/read-privat
* there is a need to change the value of environment variables throughout a
* test suite, etc.
*/
export const PRIVATE_ENVIRONMENT_VARIABLES = readPrivateEnvironmentVariables();

let PRIVATE_ENVIRONMENT_VARIABLES: {
TURNSTILE_SECRET_KEY: string;
SUPABASE_SERVICE_ROLE_KEY: string;
CRYPTO_KEY: {
[key: string]: CryptoKey
}
};

(async () => {
PRIVATE_ENVIRONMENT_VARIABLES = await readPrivateEnvironmentVariables();
})();

export { PRIVATE_ENVIRONMENT_VARIABLES };
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ import type { SupabaseClient } from '@supabase/supabase-js';
* To bypass RLS in repository-type classes, use {@link createSupabaseServiceRoleClient}.
*/
export const createSupabaseSSRClient = bind(
function createSupabaseServerClient() {
function createSupabaseServerClient() {
const cookieStore = cookies();
const { NEXT_PUBLIC_SUPABASE_URL: url } = PUBLIC_ENVIRONMENT_VARIABLES;

const { SUPABASE_SERVICE_ROLE_KEY: serviceRoleKey } =
const { SUPABASE_SERVICE_ROLE_KEY: serviceRoleKey } =
PRIVATE_ENVIRONMENT_VARIABLES;

return createServerClient(url, serviceRoleKey, {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export const VoterRegistrationRepository = inject(
const encryptRegisterBody = async (
obj: typeof RegisterBody,
): Promise<typeof RegisterBody> => {
const cryptoKey = await PRIVATE_ENVIRONMENT_VARIABLES.CRYPTO_KEY_1;
const cryptoKey = PRIVATE_ENVIRONMENT_VARIABLES.CRYPTO_KEY["CRYPTO_KEY"];

const encryptedObject = { ...obj };
for (const [key, value] of Object.entries(encryptedObject)) {
Expand Down
53 changes: 31 additions & 22 deletions src/utils/environment/read-private-environment-variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,30 @@ import { z } from 'zod';
* Reads and validates private environment variables. Can only be invoked from
* server-side code.
*/
export function readPrivateEnvironmentVariables() {
export async function readPrivateEnvironmentVariables() {
const cryptoKeys = Object.keys(process.env).filter(key =>
key.startsWith('CRYPTO_KEY'),
);

const cryptoKeyPromises = cryptoKeys.map(async (key) => {
const rawKey = new Uint8Array(
atob(process.env[key]!)
.split('')
.map(char => char.charCodeAt(0)),
);

const cryptoKey = await crypto.subtle.importKey(
'raw',
rawKey,
{ name: 'AES-GCM' },
true,
['encrypt', 'decrypt'],
);

return { [key]: cryptoKey };
});

const resolvedCryptoKeys = await Promise.all(cryptoKeyPromises);
return {
TURNSTILE_SECRET_KEY: z
.string({
Expand All @@ -20,26 +43,12 @@ export function readPrivateEnvironmentVariables() {
'Could not load environment variable SUPABASE_SERVICE_ROLE_KEY',
})
.parse(process.env.SUPABASE_SERVICE_ROLE_KEY),
CRYPTO_KEY_1: z
.string({
required_error: 'Could not load environment variable CRYPTO_KEY',
})
.transform(async (key: string): Promise<CryptoKey> => {
const rawKey = new Uint8Array(
atob(key)
.split('')
.map(char => char.charCodeAt(0)),
);

const cryptoKey = await crypto.subtle.importKey(
'raw',
rawKey,
{ name: 'AES-GCM' },
true,
['encrypt', 'decrypt'],
);
return cryptoKey;
})
.parseAsync(process.env.CRYPTO_KEY_1),
CRYPTO_KEY: Object.assign({}, ...resolvedCryptoKeys),
};
}






0 comments on commit 9d13da2

Please sign in to comment.