async function performBucketUpdate()

in api/v1/src/lib/appliers/storageApplier.js [79:149]


async function performBucketUpdate(projectId, bucketName, accounts) {
    console.log(`Begin IAM update for bucket: ${bucketName}`);
    const storageUtil = new StorageUtil(projectId);
    const exists = await storageUtil.bucketExists(bucketName);
    if (!exists) {
        console.warn(`Skipping IAM update for non-existant bucket: ${bucketName}`);
        return false;
    }
    const viewerRole = await runtimeConfig.storageObjectViewerRole(projectId);
    let isDirty = false;
    const bucketPolicy = await storageUtil.getBucketIamPolicy(bucketName);
    let readBinding = {};
    let bindingExists = false;
    if (bucketPolicy.bindings) {
        const viewerRoleBinding = underscore.findWhere(bucketPolicy.bindings, { role: viewerRole });
        if (viewerRoleBinding) {
            readBinding = viewerRoleBinding;
            bindingExists = true;
            let i = readBinding.members.length;
            while (i--) {
                let member = readBinding.members[i];
                let arr = member.split(':');
                let type = arr[0];
                let email = arr[1];
                if (cfg.managedIamAccessTypes.includes(type)) {
                    const shouldHaveAccess = underscore.findWhere(accounts, { email: email, emailType: type });
                    if (!shouldHaveAccess) {
                        console.log(`Deleting user: ${type}:${email} from bucket: ${bucketName}`);
                        readBinding.members.splice(i, 1);
                        isDirty = true;
                    }
                }
            }
        }
    } else {
        bucketPolicy.bindings = [];
    }

    if (!bindingExists) {
        readBinding.role = viewerRole;
        readBinding.members = [];
        bucketPolicy.bindings.push(readBinding);
    }

    accounts.forEach(account => {
        if (account.email && account.emailType) {
            const identifier = `${account.emailType}:${account.email}`;
            const accessRecordExists = readBinding.members.includes(identifier);
            if (!accessRecordExists) {
                readBinding.members.push(identifier);
                isDirty = true;
                console.log(`Adding access record to bucket: ${bucketName}: ${JSON.stringify(account)}`);
            }
        }
    });

    if (isDirty === true) {
        try {
            await storageUtil.setBucketIamPolicy(bucketName, bucketPolicy);
            console.info(`Policy set successfully for bucket '${bucketName}'`);
        } catch (err) {
            console.error(`Failed to set policy for bucket '${bucketName}' with error '${err}' and payload: ${JSON.stringify(bucketPolicy)}`);
            throw err;
        }
    } else {
        console.info(`Metadata is already up to date for bucket: '${bucketName}'`);
    }

    console.log(`End IAM update for bucket: ${bucketName}`);
    return isDirty;
}