Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(bigquery): WIP add samples for access policies #3975

Draft
wants to merge 23 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
5925b0f
feat(bigquery): initial project setup
hivanalejandro Feb 13, 2025
e24c2e8
feat(bigquery): basic structure
hivanalejandro Feb 13, 2025
84ec0f6
feat(bigquery): Add table and view access policy viewer
hivanalejandro Feb 13, 2025
21f786e
feat(bigquery): Add viewDatasetAccessPolicy tests
hivanalejandro Feb 13, 2025
5d408c7
feat(bigquery): Add viewTableOrViewAccessPolicy tests
hivanalejandro Feb 14, 2025
62e343a
fix(bigquery): Fix linting errors
hivanalejandro Feb 14, 2025
c87d659
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Feb 14, 2025
58ee72a
feat(bigquery): Add revokeTableOrViewAccess feawture and tests
hivanalejandro Feb 17, 2025
62ebc2c
feat(bigquery): Update app.js file to add revokeTableOrViewAccess & f…
hivanalejandro Feb 17, 2025
9d0ce88
fix(bigquery):Fix headers for revokeTableOrViewAccess.js & revokeTabl…
hivanalejandro Feb 17, 2025
627536a
feat(bigquery): Add bigquery_revoke_access_to_table_or_view tag
hivanalejandro Feb 17, 2025
70cfb83
fix(bigquery): Update if/else to if/else if
hivanalejandro Feb 18, 2025
ff35988
feat(bigquery): Add grantAccessToDataset sample and tests
hivanalejandro Feb 20, 2025
b8ad0f4
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Feb 20, 2025
7b38e5a
fix(bigquery): Update lint error
hivanalejandro Feb 20, 2025
5cfa8dc
feat(bigquery): Add grantAccessToTableOrView sample
hivanalejandro Feb 20, 2025
ccf30d6
feat(bigquery): Add grantAccessToTableOrView test
hivanalejandro Feb 20, 2025
eb32aa8
feat(bigquery): Update app.js file with new samples
hivanalejandro Feb 20, 2025
0a5f5dd
feat(bigquery): Add revokeDatasetAccess sample
hivanalejandro Feb 20, 2025
6c40940
feat(bigquery): Add revokeDatasetAccess tests
hivanalejandro Feb 20, 2025
b600729
feat(bigquery): Update app.js file with new sample
hivanalejandro Feb 20, 2025
c7a1821
Merge branch 'main' into hivanalejandro/bigquery/create-sample/view-d…
hivanalejandro Feb 20, 2025
db956a7
chore(bigquery): Update project structure
hivanalejandro Feb 20, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions bigquery/cloud-client/grantAccessToDataset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const {BigQuery} = require('@google-cloud/bigquery');

/**
* Grants access to a BigQuery dataset for a specified entity
*
* @param {object} options The configuration object
* @param {string} options.datasetId ID of the dataset to grant access to (e.g. "my_project_id.my_dataset")
* @param {string} options.entityId ID of the user or group to grant access to (e.g. "[email protected]")
* @param {string} options.role One of the basic roles for datasets (e.g. "READER")
* @returns {Promise<Array>} Array of access entries
*/
// [START bigquery_grant_access_to_dataset]
async function grantAccessToDataset(options) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think here the part where the developer can uncomment and modify their datasetId, entityId and role, is missing.

Although it's implicit in line 33, I can't find a // TODO(developer): giving them instructions on what to do next.

// Create a BigQuery client
const bigquery = new BigQuery();

const {datasetId, entityId, role} = options;

try {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this try block is too broad, and it's only catching an error that may happen in line 50.

You could move the try block to line 49.

// Get a reference to the dataset
const dataset = bigquery.dataset(datasetId);
const [metadata] = await dataset.getMetadata();

// The access entries list is immutable. Create a copy for modifications
const entries = [...(metadata.access || [])];

// Add the new access entry
entries.push({
role: role,
groupByEmail: entityId, // For group access. Use userByEmail for user access
});

// Update the dataset's access entries
const [updatedMetadata] = await dataset.setMetadata({
...metadata,
access: entries,
});

console.log(
`Role '${role}' granted for entity '${entityId}' in dataset '${datasetId}'.`
);

return updatedMetadata.access;
} catch (error) {
if (error.code === 412) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd suggest avoiding Magic numbers like 412, and using a const instead

ERROR_PRECONDITION_FAILED = 412

if (error.code === ERROR_PRECONDITION_FAILED)

Usually these constants are available in the client-library, although I can't find it for Node.JS.
Also it seems that this message is specific for Python:
https://cloud.google.com/bigquery/docs/error-messages#connecterrors

Could you replicate that error in your runs?
Otherwise, you could try to replicate the error to manually see what's the caught error for this specific case.
What I did was reading metadata (as in line 50), adding a 15 seconds pause, modifying the dataset from the Web page, and trying to save the metadata as you do in line 50.

// 412 Precondition Failed - Dataset was modified between get and update
console.error(
`Dataset '${datasetId}' was modified remotely before this update. ` +
'Fetch the latest version and retry.'
);
}
throw error;
}
}
// [END bigquery_grant_access_to_dataset]

module.exports = {
grantAccessToDataset,
};
81 changes: 81 additions & 0 deletions bigquery/cloud-client/grantAccessToTableOrView.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const {BigQuery} = require('@google-cloud/bigquery');

/**
* Grants access to a BigQuery table or view for a specified principal.
*
* @param {string} projectId - Google Cloud Platform project ID
* @param {string} datasetId - Dataset where the table or view is
* @param {string} resourceName - Table or view name to get the access policy
* @param {string} principalId - The principal requesting access to the table or view
* @param {string} role - Role to assign to the member
* @returns {Promise<object[]>} The updated policy bindings
*/
async function grantAccessToTableOrView({
projectId,
datasetId,
resourceName,
principalId,
role,
}) {
// [START bigquery_grant_access_to_table_or_view]
// Uncomment and update these variables:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

// const projectId = 'my_project_id';
// const datasetId = 'my_dataset';
// const resourceName = 'my_table';
// const principalId = 'user:[email protected]';
// const role = 'roles/bigquery.dataViewer';

// Create a BigQuery client
const bigquery = new BigQuery();

// Get the dataset and table references
const dataset = bigquery.dataset(datasetId);
const table = dataset.table(resourceName);

try {
// Get the IAM access policy for the table or view
const [policy] = await table.iam.getPolicy();

// Create a new binding for the principal and role
const binding = {
role: role,
members: [principalId],
};

// Add the new binding to the policy
policy.bindings.push(binding);

// Set the updated IAM access policy
const [updatedPolicy] = await table.iam.setPolicy(policy);

console.log(
`Role '${role}' granted for principal '${principalId}' on resource '${projectId}.${datasetId}.${resourceName}'.`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see the projectId is only being used for this console.log, so perhaps it is not necessary?

);

return updatedPolicy.bindings;
} catch (error) {
console.error('Error granting access:', error);
throw error;
}
// [END bigquery_grant_access_to_table_or_view]
}

module.exports = {
grantAccessToTableOrView,
};
26 changes: 26 additions & 0 deletions bigquery/cloud-client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"name": "bigquery-cloud-client",
"description": "Big Query Cloud Client Node.js for Google App",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "20.x"
},
"scripts": {
"deploy": "gcloud app deploy",
"start": "node app.js",
"unit-test": "c8 mocha -p -j 2 test/ --timeout=10000 --exit",
"test": "npm run unit-test"
},
"dependencies": {
"@google-cloud/bigquery": "7.9.2"
},
"devDependencies": {
"c8": "^10.0.0",
"chai": "^4.5.0",
"mocha": "^10.0.0",
"sinon": "^18.0.0"
}
}
64 changes: 64 additions & 0 deletions bigquery/cloud-client/revokeDatasetAccess.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

const {BigQuery} = require('@google-cloud/bigquery');

// [START bigquery_revoke_dataset_access]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this region tag could be placed after the // TODO(developer) part .

/**
* Revokes access to a BigQuery dataset for a specified entity.
*
* @param {Object} params The parameters for revoking dataset access
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In another sample grantAccessToDataset.js Line 22, you've used Object but with lowercase as in object.
Although JSDoc seems not to be case sensitive (as in JSDoc Issue 1046, I'd recommend to follow a convention across the repo.

* @param {string} params.datasetId The ID of the dataset to revoke access from
* @param {string} params.entityId The ID of the user or group to revoke access from
* @returns {Promise<Array>} A promise that resolves to the updated access entries
*/
async function revokeDatasetAccess({datasetId, entityId}) {
// Instantiate a client
const bigquery = new BigQuery();

try {
// Get a reference to the dataset
const [dataset] = await bigquery.dataset(datasetId).get();

// Filter out the access entry for the specified entity
dataset.metadata.access = dataset.metadata.access.filter(
entry => entry.userByEmail !== entityId && entry.groupByEmail !== entityId
);

// Update the dataset with the new access entries
const [updatedDataset] = await dataset.setMetadata(dataset.metadata);

console.log(
`Revoked dataset access for '${entityId}' to dataset '${dataset.id}'.`
);

return updatedDataset.metadata.access;
} catch (error) {
if (error.code === 412) {
// Handle precondition failed error (dataset modified externally)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same comment than in grantAccessToDataset.js. Avoid the magic number, check if you can replicate the error to get the right error code and check if the client-library offers a Human Friendly enumeration (or equivalent) for this error.

console.error(
`Dataset '${datasetId}' was modified remotely before this update. ` +
'Fetch the latest version and retry.'
);
}
throw error;
}
}
// [END bigquery_revoke_dataset_access]

module.exports = {
revokeDatasetAccess,
};
105 changes: 105 additions & 0 deletions bigquery/cloud-client/revokeTableOrViewAccess.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

const {BigQuery} = require('@google-cloud/bigquery');

// [START bigquery_revoke_access_to_table_or_view]
/**
* Revokes access to a BigQuery table or view
* @param {Object} params - The parameters object
* @param {string} params.projectId - The ID of the Google Cloud project
* @param {string} params.datasetId - The ID of the dataset containing the table/view
* @param {string} params.resourceId - The ID of the table or view
* @param {string} [params.memberToRevoke] - Optional. Specific member to revoke access from (e.g., 'group:[email protected]')
* @param {string} [params.roleToRevoke='roles/bigquery.dataViewer'] - Optional. Specific role to revoke
* @returns {Promise<void>}
*/
async function revokeTableOrViewAccess({
projectId,
datasetId,
resourceId,
memberToRevoke,
roleToRevoke = 'roles/bigquery.dataViewer',
}) {
// Validate required parameters
if (!projectId || !datasetId || !resourceId) {
throw new Error(
'projectId, datasetId and resourceID are required parameters'
);
}
try {
// Create BigQuery client
const bigquery = new BigQuery({
projectId: projectId,
});

// Get reference to the table or view
const dataset = bigquery.dataset(datasetId);
const table = dataset.table(resourceId);

// Get current IAM policy
const [policy] = await table.iam.getPolicy();
console.log(
'Current IAM Policy:',
JSON.stringify(policy.bindings, null, 2)
);

// Filter bindings based on parameters
let newBindings = policy.bindings;

if (memberToRevoke && roleToRevoke) {
// Remove specific member from specific role
newBindings = policy.bindings
.map(binding => ({
...binding,
members:
binding.role === roleToRevoke
? binding.members.filter(member => member !== memberToRevoke)
: binding.members,
}))
.filter(binding => binding.members.length > 0);
} else if (!memberToRevoke && roleToRevoke) {
// Remove all bindings for the specified role
newBindings = policy.bindings.filter(
binding => binding.role !== roleToRevoke
);
} else {
// Keep the current binding as is
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"As is" sounds weird to me, "As it is", sounds more natural, although it seems to be grammatically correct.

I don't have a strong opinion here.

newBindings = policy.bindings;
}

// Create new policy with updated bindings
const newPolicy = {
bindings: newBindings,
};

// Set the new IAM policy
await table.iam.setPolicy(newPolicy);
console.log(`Access revoked successfully for ${resourceId}`);

// Verify the changes
const [updatedPolicy] = await table.iam.getPolicy();
console.log(
'Updated IAM Policy:',
JSON.stringify(updatedPolicy.bindings, null, 2)
);
} catch (error) {
console.error('Error revoking access:', error);
throw error;
}
}

// [END bigquery_revoke_access_to_table_or_view]

module.exports = {revokeTableOrViewAccess};
Loading
Loading