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 4 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
43 changes: 43 additions & 0 deletions bigquery/cloud-client/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// 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";

Check failure on line 15 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Replace `"use·strict"` with `'use·strict'`

Check warning on line 15 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

const { viewDatasetAccessPolicy } = require("./src/viewDatasetAccessPolicy")

Check failure on line 17 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Replace `·viewDatasetAccessPolicy·}·=·require("./src/viewDatasetAccessPolicy")` with `viewDatasetAccessPolicy}·=·require('./src/viewDatasetAccessPolicy');`

Check warning on line 17 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote
const { viewTableOrViewAccessPolicy } = require("./src/viewTableOrViewAccessPolicy")

Check failure on line 18 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Replace `·viewTableOrViewAccessPolicy·}·=·require("./src/viewTableOrViewAccessPolicy")` with `⏎··viewTableOrViewAccessPolicy,⏎}·=·require('./src/viewTableOrViewAccessPolicy');`

Check warning on line 18 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

async function main() {
try {

Check failure on line 21 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Delete `··`
// Example usage of dataset access policy viewer

Check failure on line 22 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Replace `········` with `····`
await viewDatasetAccessPolicy();

Check failure on line 23 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Replace `········` with `····`

// Example usage of table/view access policy viewer

Check failure on line 25 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Delete `····`
const projectId = process.env.GOOGLE_CLOUD_PROJECT;

Check failure on line 26 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Replace `········` with `····`
await viewTableOrViewAccessPolicy({

Check failure on line 27 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Delete `····`
projectId,

Check failure on line 28 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Replace `············` with `······`
datasetId: "my_new_dataset",

Check warning on line 29 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote
resourceName: "my_table",

Check warning on line 30 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote
});
} catch (error) {
console.error("Error:", error);

Check warning on line 33 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote
processors.exitCode = 1;
}
}

Check failure on line 36 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / Node.js lint

'processors' is not defined

Check failure on line 36 in bigquery/cloud-client/app.js

View workflow job for this annotation

GitHub Actions / Node.js lint

'processors' is not defined

// Run the samples if this file is run directly
if (require.main === module) {
main();
}

module.export = { viewDatasetAccessPolicy, viewTableOrViewAccessPolicy }
27 changes: 27 additions & 0 deletions bigquery/cloud-client/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
"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",
"proxysquire": "^2.1.0",
"sinon": "^18.0.0"
}
}
58 changes: 58 additions & 0 deletions bigquery/cloud-client/src/viewDatasetAccessPolicy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// 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";

Check warning on line 15 in bigquery/cloud-client/src/viewDatasetAccessPolicy.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

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

Check warning on line 17 in bigquery/cloud-client/src/viewDatasetAccessPolicy.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

// [START bigquery_view_dataset_access_policy]
/**
* View access policies for a BigQuery dataset
*
* @param {object} [overrideValues] Optional parameters to override defaults
Copy link
Contributor

Choose a reason for hiding this comment

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

David Cavazos advised in this Python PR Review against Overriding parameters as it may be confusing. Having these things commented out as TODOs and passing them as arguments to the function.

For an example see:

function main(
projectId,
zone,
instanceName,
machineType = 'n1-standard-1',
sourceImage = 'projects/debian-cloud/global/images/family/debian-11',
networkName = 'global/networks/default'
) {
// [START compute_instances_create]
/**
* TODO(developer): Uncomment and replace these variables before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// const zone = 'europe-central2-b'
// const instanceName = 'YOUR_INSTANCE_NAME'
// const machineType = 'n1-standard-1';
// const sourceImage = 'projects/debian-cloud/global/images/family/debian-11';
// const networkName = 'global/networks/default';

* @param {string} [overrideValues.datasetId] Dataset ID to view access policies
*/

async function viewDatasetAccessPolicy(overrideValues = {}) {
// Instantiate BigQuery client
const bigquery = new BigQuery();

// Dataset from which to get the access policy
const datasetId = overrideValues.datasetId || "my_new_dataset";

Check warning on line 32 in bigquery/cloud-client/src/viewDatasetAccessPolicy.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote

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

// Shows the Access policy as a list of access entries
console.log("Access entries:", metadata.access);

Check warning on line 40 in bigquery/cloud-client/src/viewDatasetAccessPolicy.js

View workflow job for this annotation

GitHub Actions / lint

Strings must use singlequote
Copy link
Contributor

Choose a reason for hiding this comment

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

Based on the conversation with iennae and this Python PR Review it's better to only show one way, not the 'pretty output', and also how to access each parameter.

I have refactored it here, I think it's cleaner:
https://github.com/GoogleCloudPlatform/python-docs-samples/blob/72c9bbc6fea691022105d14b4f152ea4e029c2c7/bigquery/cloud-client/view_dataset_access_policy.py#L38-L43


// Get properties for an AccessEntry
if (metadata.access && metadata.access.length > 0) {
console.log(`Details for Access entry 0 in dataset '${datasetId}':`);
console.log(`Role: '${metadata.access[0].role || "N/A"}'`);
console.log(`SpecialGroup: '${metadata.access[0].specialGroup || "N/A"}'`);
console.log(`UserByEmail: '${metadata.access[0].userByEmail || "N/A"}'`);
}
} catch (error) {
console.lerror(`Error viewing dataset access policy: ${error.message}`);
}
}

// [END bigquery_view_dataset_access_policy]

module.exports = {
viewDatasetAccessPolicy,
};
71 changes: 71 additions & 0 deletions bigquery/cloud-client/src/viewTableOrViewAccessPolicy.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// 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");

// [START bigquery_view_table_or_view_access_policy]
/**
* View access policies for a BigQuery table or view
*
* @param {object} [overrideValues] Optional parameters to override defaults
Copy link
Contributor

Choose a reason for hiding this comment

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

"Overriding parameters as it may be confusing. Having these things commented out as TODOs and passing them as arguments to the function."

See my previous comment in bigquery/cloud-client/src/viewDatasetAccessPolicy.js

* @param {string} [overrideValues.projectId] Google Cloud project ID
* @param {string} [overrideValues.datasetId] Dataset ID where the table or view is located
* @param {string} [overrideValues.resourceName] Table or view name to get the access policy
* @throws {Error} If required parameters are missing or if there's an API error
*/

async function viewTableOrViewAccessPolicy(overrideValues = {}) {
// Initialize default values
const projectId = overrideValues.projectId || processors.env.GOOGLE_CLOUD_PROJECT;
const datasetId = overrideValues.datasetId || "my_new_dataset";

Check failure on line 33 in bigquery/cloud-client/src/viewTableOrViewAccessPolicy.js

View workflow job for this annotation

GitHub Actions / Node.js lint

'processors' is not defined

Check failure on line 33 in bigquery/cloud-client/src/viewTableOrViewAccessPolicy.js

View workflow job for this annotation

GitHub Actions / Node.js lint

'processors' is not defined
const resourceName = overrideValues.resourceName || "my_table";

if (!projectId) {
throw new Error("Project ID is required. Set it in overrideValues or GOOGLE_CLOUD_PROJECT environment variable.")
}

try {
// // Instantiate BigQuery client
const bigquery = new BigQuery();

// Get the IAM access policy from the table or view
const [policy] = await bigquery
.dataset(datasetId)
.table(resourceName)
.getIamPolicy();

// Show policy details
console.log(`Access Policy details for table or view '${resourceName}':`);
console.log(`Bindings: ${JSON.stringify(policy.bindings, null, 2)}`);
console.log(`etag: ${policy.etag}`);
console.log(`version: ${policy.version}`);

return policy;
} catch (error) {
console.error(`Error viewing table/view access policy: ${error.message}`);
throw error;
}
}
// [END bigquery_view_table_or_view_access_policy]

// If this file is run directly, execute the function with default values
if (require.main === module) {
viewTableOrViewAccessPolicy().catch(console.error);
}

module.exports = {
viewTableOrViewAccessPolicy,
};
99 changes: 99 additions & 0 deletions bigquery/cloud-client/test/viewDatasetAccessPolicy.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// 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 { assert } = require("chai");
const sinon = require("sinon");
const { BigQuery } = require("@google-cloud/bigquery")
const { viewDatasetAccessPolicy } = require("../src/viewDatasetAccessPolicy")

describe("viewDatasetAccessPolicy", () => {
let bigQueryStub;
let consoleLogSpy;

const sampleAccessEntry = {
role: "READER",
specialGroup: "projectReaders",
userByEmail: "[email protected]",
};

beforeEach(() => {
// Stub BigQuery client
bigQueryStub = {
dataset: sinon.stub().returns({
getMetadata: sinon.stub().resolves([
{
access: [sampleAccessEntry],
},
]),
}),
};

// Stub BigQuery constructor
sinon.stub(BigQuery.prototype, "dataset").callsFake(bigQueryStub.dataset);

// Spy on console.log
consoleLogSpy = sinon.spy(console, "log");
Copy link
Contributor

Choose a reason for hiding this comment

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

Based on this Python PR Review
Please don't check stdout/stderr directly. This was a very early approach but it's very error prone and results in (Python) flaky tests. If there's something you want to check from the sample, return it from the sample function and check the value here directly.

You may use this pattern instead?

const outputCreate = execSync(
`node create-instance-templates/createTemplate ${projectId} ${templateName}`
);
assert.match(outputCreate, /Instance template created./);

});

afterEach(() => {
sinon.restore();
});

it("should display access policy details for a dataset", async () => {
const datasetId = "test_dataset";

await viewDatasetAccessPolicy({ datasetId });

// Verify BigQuery client was called correctly
assert.ok(consoleLogSpy.calledWith("Access entries:", [sampleAccessEntry]));
Copy link
Contributor

Choose a reason for hiding this comment

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

See my previous comment about checking stdout/stederr

assert.ok(consoleLogSpy.calledWith(`Details for Access entry 0 in dataset '${datasetId}':`));
assert.ok(consoleLogSpy.calledWith("Role: READER"));
assert.ok(consoleLogSpy.calledWith("SpecialGroup: projectReaders"));
assert.ok(consoleLogSpy.calledWith("UserByEmail: [email protected]"));
});

it("should handle datasets with no access entries", async () => {
// Override stub to return empty access array
bigQueryStub.dataset.returns({
getMetadata: sinon.stub().resolves([
{
access: [],
},
]),
});

await viewDatasetAccessPolicy({ datasetId: "empty_dataset" });

// Verify only the access entries message was logged
assert.ok(consoleLogSpy.calledWith("Access entries:", []));
});

it("should handle errors gracefully", async () => {
const errorMessage = "Dataset not found";

// Override stub to throw error
bigQueryStub.dataset.returns({
getMetadata: sinon.stub().rejects(new Error(errorMessage)),
});

try {
await viewDatasetAccessPolicy({ datasetId: "non_existent_dataset" });
assert.fail("Should have thrown an error");
} catch (error) {
assert.include(error.message, errorMessage);
}
});
})
Empty file.
Loading