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): add samples for control access 1/3 #4023

Open
wants to merge 3 commits into
base: main
Choose a base branch
from

Conversation

hivanalejandro
Copy link
Contributor

@hivanalejandro hivanalejandro commented Mar 8, 2025

Description

Add the following NodeJS samples:

Step of Internal: b/394478489

PR 1/3

Checklist

@hivanalejandro hivanalejandro requested review from a team as code owners March 8, 2025 13:15
Copy link

snippet-bot bot commented Mar 8, 2025

Here is the summary of changes.

You are about to add 2 region tags.

This comment is generated by snippet-bot.
If you find problems with this result, please file an issue at:
https://github.com/googleapis/repo-automation-bots/issues.
To update this comment, add snippet-bot:force-run label or use the checkbox below:

  • Refresh this comment

@product-auto-label product-auto-label bot added api: bigquery Issues related to the BigQuery API. samples Issues that are directly related to samples. labels Mar 8, 2025
Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Hello @hivanalejandro, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

Summary of Changes

This pull request introduces new NodeJS samples for granting access to BigQuery datasets, tables, or views using IAM. It includes two new files: grantAccessToDataset.js and grantAccessToTableOrView.js, along with corresponding tests and updates to the package.json and config.js files. The samples demonstrate how to grant roles to users or groups, enabling control over resource access within BigQuery.

Highlights

  • New Samples: Adds grantAccessToDataset.js and grantAccessToTableOrView.js to demonstrate granting access to BigQuery resources.
  • IAM Integration: Demonstrates the use of IAM policies to control access to BigQuery datasets, tables, and views.
  • Testing: Includes new tests to verify the functionality of the new samples.

Changelog

Click here to see the changelog
  • bigquery/cloud-client/grantAccessToDataset.js
    • Introduces a new function grantAccessToDataset to grant access to a BigQuery dataset for a specified entity.
    • Includes example code with placeholders for datasetId, entityId, and role.
    • Uses @google-cloud/bigquery library to interact with BigQuery.
    • Handles potential PRECONDITION_FAILED errors if the dataset is modified remotely.
  • bigquery/cloud-client/grantAccessToTableOrView.js
    • Introduces a new function grantAccessToTableOrView to grant access to a BigQuery table or view for a specified principal.
    • Includes example code with placeholders for projectId, datasetId, resourceName, principalId, and role.
    • Uses @google-cloud/bigquery library to interact with BigQuery.
    • Updates the IAM access policy for the table or view with the new binding.
  • bigquery/cloud-client/package.json
    • Adds bigquery-cloud-client package with description, version, license, author, and engine details.
    • Includes scripts for deploy, start, unit-test, and test.
    • Specifies @google-cloud/bigquery as a dependency.
    • Adds c8, chai, mocha, and sinon as devDependencies.
  • bigquery/cloud-client/test/config.js
    • Adds configuration file for tests, including setup and teardown functions.
    • Defines constants for prefix, entity ID, dataset ID, table name, and view name.
    • Includes helper functions to get shared resources like client, project ID, dataset, table, and view.
    • Implements setupBeforeAll and teardownAfterAll functions to manage test resources.
  • bigquery/cloud-client/test/grantAccessToDataset.test.js
    • Adds tests for the grantAccessToDataset function.
    • Uses chai for assertions.
    • Imports necessary modules and functions from ./config.js and ../grantAccessToDataset.js.
    • Tests if the entity is added to access entries correctly.
  • bigquery/cloud-client/test/grantAccessToTableOrView.test.js
    • Adds tests for the grantAccessToTableOrView function.
    • Uses assert for assertions.
    • Imports necessary modules and functions from ./config.js and ../grantAccessToTableOrView.js.
    • Tests if access is granted to a table correctly by verifying role and principal existence in the updated policy.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in issue comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.


Trivia time!

What is the underlying technology that powers BigQuery's query engine?

Click here for the answer
BigQuery's query engine is powered by Dremel, a scalable, interactive ad-hoc query system for analysis of read-only nested data.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces new NodeJS samples for granting access to BigQuery datasets, tables, or views. The code includes functions to grant access and corresponding tests. Overall, the code is well-structured and addresses the intended functionality. However, there are a few areas that could be improved for clarity and robustness.

Summary of Findings

  • TODO comments: The code contains TODO comments with placeholders for the developer to update. While this is acceptable, it's important to ensure these are addressed before merging to avoid confusion or incomplete examples.
  • Error Handling: The error handling in grantAccessToDataset could be improved by providing more context or guidance to the user on how to resolve the PRECONDITION_FAILED error.
  • Principal ID Format: In grantAccessToTableOrView, the principal ID is hardcoded with a group: prefix in the test. The code sample should reflect this format to avoid confusion.

Merge Readiness

The pull request is almost ready for merging. Addressing the TODO comments and clarifying the principal ID format would improve the overall quality of the samples. I am unable to directly approve this pull request, and recommend that others review and approve this code before merging. At a minimum, the TODO comments should be addressed before merging.

const entityId = getEntityId();

const ROLE = 'roles/bigquery.dataViewer';
const PRINCIPAL_ID = `group:${entityId}`;

Choose a reason for hiding this comment

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

medium

It's good that the principal ID includes the group: prefix. To avoid confusion, consider adding a comment in the code sample (grantAccessToTableOrView.js) to indicate that the principal ID should be formatted as group:[email protected] or user:[email protected].

Suggested change
const PRINCIPAL_ID = `group:${entityId}`;
const PRINCIPAL_ID = `group:${entityId}`; // Ensure the principal ID is formatted as group: or user:

Copy link
Contributor

@telpirion telpirion left a comment

Choose a reason for hiding this comment

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

I have multiple concerns about this sample. Given the number of comments, I will make a commit to this branch that demonstrates some of the changes I suggest.

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

return updatedDataset.access;
Copy link
Contributor

Choose a reason for hiding this comment

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

issue: process results from the method call in the sample.

See: https://googlecloudplatform.github.io/samples-style-guide/#result


// Define enum for HTTP codes.
const HTTP_STATUS = {
PRECONDITION_FAILED: 412,
Copy link
Contributor

Choose a reason for hiding this comment

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

question: can we use a library here instead of defining our own constant? Maybe something from the gRPC library for Node?

const [dataset] = await client.dataset(datasetId).get();

// The 'access entries' array is immutable. Create a copy for modifications.
const entries = Array.isArray(dataset.metadata.access)
Copy link
Contributor

Choose a reason for hiding this comment

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

issue: don't use ternary conditions in samples, as they are harder to read.

The condition that we're testing is "is dataset.metadata.access an array?" I think we can assume that it is an array, since it is returned by the API service.

.dataset(datasetId)
.setMetadata(metadata);

// Show a success message.
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: cut this comment, as it doesn't add any significant new information to what the code does.

// Find more details about the AccessEntry object in the BigQuery documentation:
// https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.dataset.AccessEntry
entries.push({
role: role,
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: you can shorten this operation to just

entries.push({
    role,
    [entityType]: entityId,
})


'use strict';

const {expect} = require('chai');
Copy link
Contributor

Choose a reason for hiding this comment

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

issue: explicitly import describe, it, before, and after from mocha.

Copy link
Contributor

Choose a reason for hiding this comment

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

Also, let's use just regular assert() rather than expect().

const VIEW_NAME = `${PREFIX}_view`;

// Shared client for all tests
let sharedClient = null;
Copy link
Contributor

Choose a reason for hiding this comment

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

issue: I have concerns about storing these variables globally. I think we should ensure that our set up function passes along resource names to each subsequent set up step in the object hierarchy.

const PREFIX = createRandomPrefix();
console.log(`Generated test prefix: ${PREFIX}`);

const ENTITY_ID = '[email protected]'; // Group account
Copy link
Contributor

Choose a reason for hiding this comment

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

question: Do we know that using this entity ID "works"? I think we should look at the IAM samples to see if there is a better pattern used there.

* @param {string} role Role to grant.
* @returns {Promise<Array>} Array of access entries.
*/
async function grantAccessToDataset(datasetId, entityId, role) {
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: we typically write the Node samples so that there is an inner function and an outer function, where the outer function exposes arguments that are passed through to the inner function.

);

// Assert: Check if entity was added to access entries.
const updatedEntityIds = accessEntries
Copy link
Contributor

Choose a reason for hiding this comment

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

issue: check stdout rather than iterating over the returned types. We can trust that the BigQuery service behaves appropriately. We don't have to check that resources are, in fact created -- we're more interested in ensuring that the sample didn't fail.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
api: bigquery Issues related to the BigQuery API. samples Issues that are directly related to samples.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants