/
testPermissions.ts
74 lines (61 loc) · 2.21 KB
/
testPermissions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import fs from 'fs';
import path from 'path';
import {getProjectId} from '../../functions/helpers/is-in-cloud-task';
import {getResourceManagerClient} from '../helpers/get-resource-manager-client';
export const logPermissionOutput = (output: TestResult) => {
return [output.decision ? '✅' : '❌', output.permissionName].join(' ');
};
type TestResult = {
decision: true | false;
permissionName: string;
};
type TestPermissionsInput = {
onTest: (result: TestResult) => void;
};
type TestPermissionsOutput = {
results: TestResult[];
};
/**
* @description Test the permissions on the service account match the permissions required.
* @see [Remotion-Documentation](http://remotion.dev/docs/cloudrun/testpermissions)
* @see [Cloudrun-Documentation](https://cloud.google.com/resource-manager/reference/rest/v3/projects/testIamPermissions)
* @param {(result: TestResult) => void} params.onTest Function to run on each test result
* @returns {Promise<TestPermissionsOutput>} Returns array of TestResult objects
*/
export const testPermissions = async (
params?: TestPermissionsInput,
): Promise<TestPermissionsOutput> => {
const resourceManagerClient = getResourceManagerClient();
const saPermissions = JSON.parse(
fs.readFileSync(
path.join(__dirname, '../../shared/sa-permissions.json'),
'utf-8',
),
);
const permissionList: string[] = saPermissions.list.map(
(permission: {name: string; reason: string}) => permission.name,
);
const response = await resourceManagerClient.testIamPermissions({
resource: `projects/${getProjectId()}`,
permissions: permissionList,
});
const returnedPermissions = response[0].permissions;
if (!returnedPermissions) {
throw new Error(
'No permissions returned from the testIamPermissions call.',
);
}
const results: TestResult[] = [];
saPermissions.list.forEach((permission: {name: string; reason: string}) => {
if (returnedPermissions.includes(permission.name)) {
const thisResult = {decision: true, permissionName: permission.name};
results.push(thisResult);
params?.onTest(thisResult);
} else {
const thisResult = {decision: false, permissionName: permission.name};
results.push(thisResult);
params?.onTest(thisResult);
}
});
return {results};
};