diff --git a/.github/workflows/security-center-snippets.yaml b/.github/workflows/security-center-snippets.yaml new file mode 100644 index 0000000000..260adf0e1b --- /dev/null +++ b/.github/workflows/security-center-snippets.yaml @@ -0,0 +1,70 @@ +name: security-center-snippets +on: + push: + branches: + - main + paths: + - 'security-center/snippets/**' + pull_request: + paths: + - 'security-center/snippets/**' + pull_request_target: + types: [labeled] + paths: + - 'security-center/snippets/**' + schedule: + - cron: '0 0 * * 0' +env: + GCLOUD_ORGANIZATION: 1081635000895 +jobs: + test: + if: ${{ github.event.action != 'labeled' || github.event.label.name == 'actions:force-run' }} + runs-on: ubuntu-latest + timeout-minutes: 60 + permissions: + contents: 'write' + pull-requests: 'write' + id-token: 'write' + steps: + - uses: actions/checkout@v3.1.0 + with: + ref: ${{github.event.pull_request.head.sha}} + - uses: 'google-github-actions/auth@v1.0.0' + with: + workload_identity_provider: 'projects/1046198160504/locations/global/workloadIdentityPools/github-actions-pool/providers/github-actions-provider' + service_account: 'kokoro-system-test@long-door-651.iam.gserviceaccount.com' + create_credentials_file: 'true' + access_token_lifetime: 600s + - uses: actions/setup-node@v3.5.1 + with: + node-version: 16 + - run: npm install + working-directory: security-center/snippets + - run: npm test + working-directory: security-center/snippets + env: + MOCHA_REPORTER_SUITENAME: security_center_snippets + MOCHA_REPORTER_OUTPUT: security_center_snippets_sponge_log.xml + MOCHA_REPORTER: xunit + - if: ${{ github.event.action == 'labeled' && github.event.label.name == 'actions:force-run' }} + uses: actions/github-script@v6 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + try { + await github.rest.issues.removeLabel({ + name: 'actions:force-run', + owner: 'GoogleCloudPlatform', + repo: 'nodejs-docs-samples', + issue_number: context.payload.pull_request.number + }); + } catch (e) { + if (!e.message.includes('Label does not exist')) { + throw e; + } + } + - if: ${{ github.event_name == 'schedule'}} + run: | + curl https://github.com/googleapis/repo-automation-bots/releases/download/flakybot-1.1.0/flakybot -o flakybot -s -L + chmod +x ./flakybot + ./flakybot --repo GoogleCloudPlatform/nodejs-docs-samples --commit_hash ${{github.sha}} --build_url https://github.com/${{github.repository}}/actions/runs/${{github.run_id}} diff --git a/.github/workflows/workflows.json b/.github/workflows/workflows.json index 93d89889a6..d2aebb5c0b 100644 --- a/.github/workflows/workflows.json +++ b/.github/workflows/workflows.json @@ -57,8 +57,9 @@ "datacatalog/cloud-client", "datacatalog/quickstart", "datastore/functions", - "service-directory/snippets", "scheduler", + "security-center/snippets", + "service-directory/snippets", "secret-manager", "speech", "talent", diff --git a/security-center/snippets/package.json b/security-center/snippets/package.json new file mode 100644 index 0000000000..cb626bcbc6 --- /dev/null +++ b/security-center/snippets/package.json @@ -0,0 +1,24 @@ +{ + "name": "nodejs-security-center-samples", + "private": true, + "files": [ + "**/*.js", + "!system-test/" + ], + "engines": { + "node": ">=12.0.0" + }, + "scripts": { + "test": "mocha system-test/ --recursive --timeout 6000000" + }, + "license": "Apache-2.0", + "dependencies": { + "@google-cloud/pubsub": "^3.0.0", + "@google-cloud/security-center": "^6.3.1" + }, + "devDependencies": { + "chai": "^4.2.0", + "mocha": "^8.0.0", + "uuid": "^9.0.0" + } +} \ No newline at end of file diff --git a/security-center/snippets/system-test/v1/assetSecurityMarks.test.js b/security-center/snippets/system-test/v1/assetSecurityMarks.test.js new file mode 100644 index 0000000000..77c417535f --- /dev/null +++ b/security-center/snippets/system-test/v1/assetSecurityMarks.test.js @@ -0,0 +1,86 @@ +// Copyright 2019 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 {SecurityCenterClient} = require('@google-cloud/security-center'); +const {assert} = require('chai'); +const {describe, it, before} = require('mocha'); +const {execSync} = require('child_process'); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); + +const organizationId = process.env['GCLOUD_ORGANIZATION']; + +describe('client with security marks for assets', async () => { + let data; + before(async () => { + // Creates a new client. + const client = new SecurityCenterClient(); + + const [assetResults] = await client.listAssets({ + parent: client.organizationPath(organizationId), + }); + const randomAsset = + assetResults[Math.floor(Math.random() * assetResults.length)].asset; + console.log('random %j', randomAsset); + data = { + orgId: organizationId, + assetName: randomAsset.name, + }; + console.log('data %j', data); + }); + it('client can add security marks to asset.', () => { + const output = exec(`node v1/addSecurityMarks.js ${data.assetName}`); + assert.include(output, data.assetName); + assert.match(output, /key_a/); + assert.match(output, /value_a/); + assert.match(output, /key_b/); + assert.match(output, /value_b/); + assert.notMatch(output, /undefined/); + }); + + it('client can add and delete security marks', () => { + // Ensure marks are set. + exec(`node v1/addSecurityMarks.js ${data.assetName}`); + + const output = exec(`node v1/addDeleteSecurityMarks.js ${data.assetName}`); + assert.match(output, /key_a/); + assert.match(output, /new_value_a/); + assert.notMatch(output, /key_b/); + assert.notMatch(output, /undefined/); + }); + + it('client can delete security marks', () => { + // Ensure marks are set. + exec(`node v1/addSecurityMarks.js ${data.assetName}`); + + const output = exec(`node v1/deleteSecurityMarks.js ${data.assetName}`); + assert.notMatch(output, /key_a/); + assert.notMatch(output, /value_a/); + assert.notMatch(output, /key_b/); + assert.notMatch(output, /value_b/); + assert.include(output, data.assetName); + assert.include(output, data.assetName); + assert.notMatch(output, /undefined/); + }); + + it('client can list assets with security marks', () => { + // Ensure marks are set. + exec(`node v1/addSecurityMarks.js ${data.assetName}`); + + const output = exec(`node v1/listAssetsWithSecurityMarks.js ${data.orgId}`); + assert.include(output, data.assetName); + assert.notMatch(output, /undefined/); + }); +}); diff --git a/security-center/snippets/system-test/v1/findings.test.js b/security-center/snippets/system-test/v1/findings.test.js new file mode 100644 index 0000000000..d1f5173ad2 --- /dev/null +++ b/security-center/snippets/system-test/v1/findings.test.js @@ -0,0 +1,204 @@ +// Copyright 2019 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 {SecurityCenterClient} = require('@google-cloud/security-center'); +const {assert} = require('chai'); +const {describe, it, before} = require('mocha'); +const {execSync} = require('child_process'); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); + +const organizationId = process.env['GCLOUD_ORGANIZATION']; + +describe('Client with SourcesAndFindings', async () => { + let data; + before(async () => { + // Creates a new client. + const client = new SecurityCenterClient(); + const [source] = await client + .createSource({ + source: { + displayName: 'Customized Display Name', + description: 'A new custom source that does X', + }, + parent: client.organizationPath(organizationId), + }) + .catch(error => console.error(error)); + const eventTime = new Date(); + const createFindingTemplate = { + parent: source.name, + findingId: 'somefinding', + finding: { + state: 'ACTIVE', + // Resource the finding is associated with. This is an + // example any resource identifier can be used. + resourceName: + '//cloudresourcemanager.googleapis.com/organizations/11232', + // A free-form category. + category: 'MEDIUM_RISK_ONE', + // The time associated with discovering the issue. + eventTime: { + seconds: Math.floor(eventTime.getTime() / 1000), + nanos: (eventTime.getTime() % 1000) * 1e6, + }, + }, + }; + const [finding] = await client.createFinding(createFindingTemplate); + createFindingTemplate.findingId = 'untouchedFindingId'; + createFindingTemplate.finding.category = 'XSS'; + const [untouchedFinding] = await client + .createFinding(createFindingTemplate) + .catch(error => console.error(error)); + data = { + orgId: organizationId, + sourceName: source.name, + findingName: finding.name, + untouchedFindingName: untouchedFinding.name, + }; + console.log('my data %j', data); + }); + + it('client can create source', () => { + const output = exec(`node v1/createSource.js ${data.orgId}`); + assert.match(output, new RegExp(data.orgId)); + assert.match(output, /New Source/); + assert.notMatch(output, /undefined/); + }); + + it('client can get source', () => { + const output = exec(`node v1/getSource.js ${data.sourceName}`); + assert.match(output, new RegExp(data.sourceName)); + assert.match(output, /Source/); + assert.match(output, /"description":"A new custom source that does X"/); + assert.notMatch(output, /undefined/); + }); + + it('client can list all sources', () => { + const output = exec(`node v1/listAllSources.js ${data.orgId}`); + assert.match(output, new RegExp(data.sourceName)); + assert.match(output, /Sources/); + assert.notMatch(output, /undefined/); + }); + + it('client can update a source', () => { + const output = exec(`node v1/updateSource.js ${data.sourceName}`); + assert.match(output, new RegExp(data.sourceName)); + assert.match(output, /New Display Name/); + assert.match(output, /source that does X/); + assert.notMatch(output, /undefined/); + }); + + it('client can create a finding', () => { + const output = exec(`node v1/createFinding.js ${data.sourceName}`); + assert.match(output, new RegExp(data.sourceName)); + assert.match(output, /New finding created/); + assert.notMatch(output, /undefined/); + }); + + it('client can create a finding with source properties', () => { + const output = exec( + `node v1/createFindingSourceProperties.js ${data.sourceName}` + ); + assert.match(output, new RegExp(data.sourceName)); + assert.match(output, /New finding created/); + assert.match(output, /n_value/); + assert.notMatch(output, /undefined/); + }); + + it('client can update a findings source properties', () => { + const output = exec( + `node v1/updateFindingSourceProperties.js ${data.findingName}` + ); + assert.match(output, new RegExp(data.findingName)); + assert.match(output, /Updated Finding/); + assert.match(output, /new_string_example/); + assert.notMatch(output, /undefined/); + }); + + it('client can set finding state', () => { + const output = exec(`node v1/setFindingState.js ${data.findingName}`); + assert.match(output, new RegExp(data.findingName)); + assert.match(output, /INACTIVE/); + assert.notMatch(output, /undefined/); + }); + + it('client can test IAM privileges', () => { + const output = exec(`node v1/testIam.js ${data.sourceName}`); + assert.equal( + (output.match(/true/g) || []).length, + 2, + `${output} contains true twice` + ); + assert.notMatch(output, /undefined/); + }); + + it('client can list all findings', () => { + const output = exec(`node v1/listAllFindings.js ${data.orgId}`); + assert.match(output, new RegExp(data.findingName)); + assert.match(output, new RegExp(data.untouchedFindingName)); + assert.notMatch(output, /undefined/); + }); + + it('client can list only some findings', () => { + const output = exec(`node v1/listFilteredFindings.js ${data.sourceName}`); + assert.match(output, new RegExp(data.findingName)); + assert.notMatch(output, new RegExp(data.untouchedFindingName)); + assert.notMatch(output, /undefined/); + }); + + it('client can list findings at a time.', () => { + const output = exec(`node v1/listFindingsAtTime.js ${data.sourceName}`); + // Nothing was created for the source more then a few minutes ago, so + // days ago should return nothing. + assert.equal(output, ''); + }); + + it('client can add security marks to finding', () => { + const output = exec( + `node v1/addFindingSecurityMarks.js ${data.findingName}` + ); + assert.match(output, new RegExp(data.findingName)); + assert.match(output, /key_a/); + assert.match(output, /value_a/); + assert.match(output, /key_b/); + assert.match(output, /value_b/); + assert.notMatch(output, /undefined/); + }); + + it('client can list findings withe security marks', () => { + // Ensure marks are set. + exec(`node v1/addFindingSecurityMarks.js ${data.findingName}`); + const output = exec( + `node v1/listFindingsWithSecurityMarks.js ${data.sourceName}` + ); + assert.notMatch(output, new RegExp(data.findingName)); + assert.match(output, new RegExp(data.untouchedFindingName)); + assert.notMatch(output, /undefined/); + }); + + it('client can get a sources policy', () => { + const output = exec(`node v1/getSourceIam.js ${data.sourceName}`); + assert.match(output, /Current policy/); + assert.notMatch(output, /undefined/); + }); + + it('client set a sources policy', () => { + const user = 'csccclienttest@gmail.com'; + const output = exec(`node v1/setSourceIam.js ${data.sourceName} ${user}`); + assert.match(output, /Updated policy/); + assert.include(output, user); + assert.notMatch(output, /undefined/); + }); +}); diff --git a/security-center/snippets/system-test/v1/listAllAssets.test.js b/security-center/snippets/system-test/v1/listAllAssets.test.js new file mode 100644 index 0000000000..516c8c8a84 --- /dev/null +++ b/security-center/snippets/system-test/v1/listAllAssets.test.js @@ -0,0 +1,30 @@ +// Copyright 2019 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 {assert} = require('chai'); +const {describe, it} = require('mocha'); +const {execSync} = require('child_process'); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); + +const organization_id = process.env['GCLOUD_ORGANIZATION']; + +describe('listAllAssets', () => { + it('should print all assets in org', () => { + const output = exec(`node v1/listAllAssets.js ${organization_id}`); + assert.isAtLeast(output.match(/\n/g).length + 1, 62); + assert.notMatch(output, /undefined/); + }); +}); diff --git a/security-center/snippets/system-test/v1/listAssetsAndChanges.test.js b/security-center/snippets/system-test/v1/listAssetsAndChanges.test.js new file mode 100644 index 0000000000..c8975d9d15 --- /dev/null +++ b/security-center/snippets/system-test/v1/listAssetsAndChanges.test.js @@ -0,0 +1,31 @@ +// Copyright 2019 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 {assert} = require('chai'); +const {describe, it} = require('mocha'); +const {execSync} = require('child_process'); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); + +const organization_id = process.env['GCLOUD_ORGANIZATION']; + +describe('listAssetsandChanges', () => { + it('should print projects with state changes', () => { + const output = exec(`node v1/listAssetsAndChanges.js ${organization_id}`); + assert.match(output, /(ADDED|ACTIVE)/); + assert.equal(4, output.match(/\n/g).length + 1, '== number of projects'); + assert.notMatch(output, /undefined/); + }); +}); diff --git a/security-center/snippets/system-test/v1/listAssetsAtTime.test.js b/security-center/snippets/system-test/v1/listAssetsAtTime.test.js new file mode 100644 index 0000000000..cad70cb513 --- /dev/null +++ b/security-center/snippets/system-test/v1/listAssetsAtTime.test.js @@ -0,0 +1,30 @@ +// Copyright 2019 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 {assert} = require('chai'); +const {describe, it} = require('mocha'); +const {execSync} = require('child_process'); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); + +const organization_id = process.env['GCLOUD_ORGANIZATION']; + +describe('listAssetsAttime', () => { + it('should print projects', () => { + const output = exec(`node v1/listAssetsAtTime.js ${organization_id}`); + assert.equal(4, output.match(/\n/g).length + 1, '== number of projects'); + assert.notMatch(output, /undefined/); + }); +}); diff --git a/security-center/snippets/system-test/v1/listFilteredAssets.test.js b/security-center/snippets/system-test/v1/listFilteredAssets.test.js new file mode 100644 index 0000000000..ef544da721 --- /dev/null +++ b/security-center/snippets/system-test/v1/listFilteredAssets.test.js @@ -0,0 +1,30 @@ +// Copyright 2019 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 {assert} = require('chai'); +const {describe, it} = require('mocha'); +const {execSync} = require('child_process'); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); + +const organization_id = process.env['GCLOUD_ORGANIZATION']; + +describe('listAllAssets', () => { + it('should print all assets in org', () => { + const output = exec(`node v1/listFilteredAssets.js ${organization_id}`); + assert.isAtLeast(4, output.match(/\n/g).length + 1); + assert.notMatch(output, /undefined/); + }); +}); diff --git a/security-center/snippets/system-test/v1/notifications.test.js b/security-center/snippets/system-test/v1/notifications.test.js new file mode 100644 index 0000000000..5c51b726f1 --- /dev/null +++ b/security-center/snippets/system-test/v1/notifications.test.js @@ -0,0 +1,110 @@ +// Copyright 2020 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 {SecurityCenterClient} = require('@google-cloud/security-center'); +const uuidv1 = require('uuid').v1; +const {assert} = require('chai'); +const {describe, it, before, after} = require('mocha'); +const {execSync} = require('child_process'); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); + +const organizationId = process.env['GCLOUD_ORGANIZATION']; +const orgName = 'organizations/' + organizationId; +const pubsubTopic = 'projects/project-a-id/topics/notifications-sample-topic'; + +describe('Client with Notifications', async () => { + const createConfig = 'notif-config-test-node-create' + uuidv1(); + const deleteConfig = 'notif-config-test-node-delete' + uuidv1(); + const getConfig = 'notif-config-test-node-get' + uuidv1(); + const listConfig = 'notif-config-test-node-list' + uuidv1(); + const updateConfig = 'notif-config-test-node-update' + uuidv1(); + + before(async () => { + const client = new SecurityCenterClient(); + async function createNotificationConfig(configId) { + /*eslint no-unused-vars: ["error", { "varsIgnorePattern": "^_" }]*/ + const [_response] = await client.createNotificationConfig({ + parent: orgName, + configId: configId, + notificationConfig: { + description: 'Sample config for node.js', + pubsubTopic: pubsubTopic, + streamingConfig: {filter: 'state = "ACTIVE"'}, + }, + }); + } + + await createNotificationConfig(deleteConfig); + await createNotificationConfig(getConfig); + await createNotificationConfig(listConfig); + await createNotificationConfig(updateConfig); + }); + + after(async () => { + const client = new SecurityCenterClient(); + async function deleteNotificationConfig(configId) { + const name = client.notificationConfigPath(organizationId, configId); + await client.deleteNotificationConfig({name: name}); + } + + await deleteNotificationConfig(createConfig); + await deleteNotificationConfig(getConfig); + await deleteNotificationConfig(listConfig); + await deleteNotificationConfig(updateConfig); + }); + + it('client can create config', () => { + const output = exec( + `node v1/createNotificationConfig.js ${organizationId} ${createConfig} ${pubsubTopic}` + ); + assert.include(output, createConfig); + assert.match(output, /Notification config creation succeeded/); + assert.notMatch(output, /undefined/); + }); + + it('client can delete config', () => { + const output = exec( + `node v1/deleteNotificationConfig.js ${organizationId} ${deleteConfig}` + ); + assert.include(output, 'Notification config deleted'); + assert.notMatch(output, /undefined/); + }); + + it('client can get config', () => { + const output = exec( + `node v1/getNotificationConfig.js ${organizationId} ${getConfig}` + ); + assert.include(output, getConfig); + assert.match(output, /Notification config/); + assert.notMatch(output, /undefined/); + }); + + it('client can list configs', () => { + const output = exec(`node v1/listNotificationConfigs.js ${organizationId}`); + assert.include(output, listConfig); + assert.match(output, /Received Notification configs/); + assert.notMatch(output, /undefined/); + }); + + it('client can update configs', () => { + const output = exec( + `node v1/updateNotificationConfig.js ${organizationId} ${updateConfig} ${pubsubTopic}` + ); + assert.include(output, updateConfig); + assert.match(output, /notification config update succeeded/); + assert.notMatch(output, /undefined/); + }); +}); diff --git a/security-center/snippets/system-test/v1/orgSettings.test.js b/security-center/snippets/system-test/v1/orgSettings.test.js new file mode 100644 index 0000000000..a3fc8498fc --- /dev/null +++ b/security-center/snippets/system-test/v1/orgSettings.test.js @@ -0,0 +1,36 @@ +// Copyright 2019 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 {assert} = require('chai'); +const {describe, it} = require('mocha'); +const {execSync} = require('child_process'); +const exec = cmd => execSync(cmd, {encoding: 'utf8'}); + +const organizationId = process.env['GCLOUD_ORGANIZATION']; + +describe('client with organization settings', () => { + it('client can enable asset discovery', () => { + const output = exec(`node v1/enableAssetDiscovery.js ${organizationId}`); + assert.match(output, new RegExp(organizationId)); + assert.match(output, /true/); + assert.notMatch(output, /undefined/); + }); + + it('client can get organization settings', () => { + const output = exec(`node v1/getOrganizationSettings.js ${organizationId}`); + assert.match(output, new RegExp(organizationId)); + }); +}); diff --git a/security-center/snippets/v1/addDeleteSecurityMarks.js b/security-center/snippets/v1/addDeleteSecurityMarks.js new file mode 100644 index 0000000000..000f834625 --- /dev/null +++ b/security-center/snippets/v1/addDeleteSecurityMarks.js @@ -0,0 +1,49 @@ +// Copyright 2019 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'; + +/** + * Demostrates adding/updating at the same time as deleting security + * marks from an asset. + */ +function main(assetName = 'full asset path to add marks to') { + // [START securitycenter_add_delete_security_marks] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + async function addDeleteSecurityMarks() { + // assetName is the full resource path for the asset to update. + /* + * TODO(developer): Uncomment the following lines + */ + // assetName = "organizations/123123342/assets/12312321"; + const [newMarks] = await client.updateSecurityMarks({ + securityMarks: { + name: `${assetName}/securityMarks`, + marks: {key_a: 'new_value_a'}, + }, + // Only update the enableAssetDiscovery field. + updateMask: {paths: ['marks.key_a', 'marks.key_b']}, + }); + + console.log('New marks: %j', newMarks); + } + addDeleteSecurityMarks(); + // [END securitycenter_add_delete_security_marks] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/addFindingSecurityMarks.js b/security-center/snippets/v1/addFindingSecurityMarks.js new file mode 100644 index 0000000000..f834e0cb62 --- /dev/null +++ b/security-center/snippets/v1/addFindingSecurityMarks.js @@ -0,0 +1,49 @@ +// Copyright 2019 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'; + +/** + * Demostrates adding security marks to a finding. + */ +function main(findingName = 'full finding path to add marks to') { + // [START securitycenter_add_finding_security_marks] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + async function addFindingSecurityMarks() { + // findingName is the full resource path for the finding to update. + /* + * TODO(developer): Uncomment the following lines + */ + // const findingName = + // "organizations/123123342/sources/1213/findings/findingid"; + const [newMarks] = await client.updateSecurityMarks({ + securityMarks: { + name: `${findingName}/securityMarks`, + marks: {key_a: 'value_a', key_b: 'value_b'}, + }, + // Only update the marks with these keys. + updateMask: {paths: ['marks.key_a', 'marks.key_b']}, + }); + + console.log('New marks: %j', newMarks); + } + addFindingSecurityMarks(); + // [END securitycenter_add_finding_security_marks] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/addSecurityMarks.js b/security-center/snippets/v1/addSecurityMarks.js new file mode 100644 index 0000000000..203efef8f9 --- /dev/null +++ b/security-center/snippets/v1/addSecurityMarks.js @@ -0,0 +1,49 @@ +// Copyright 2019 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'; + +/** + * Demostrates adding security marks to an asset. + */ +function main(assetName = 'full asset path to add marks to') { + // [START securitycenter_add_security_marks] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + async function addSecurityMarks() { + // assetName is the full resource path for the asset to update. + /* + * TODO(developer): Uncomment the following lines + */ + // const assetName = "organizations/123123342/assets/12312321"; + const [newMarks] = await client.updateSecurityMarks({ + securityMarks: { + name: `${assetName}/securityMarks`, + marks: {key_a: 'value_a', key_b: 'value_b'}, + }, + // Only update the marks with these keys. + updateMask: {paths: ['marks.key_a', 'marks.key_b']}, + }); + + console.log('New marks: %', newMarks); + } + addSecurityMarks(); + // [END securitycenter_add_security_marks] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/createFinding.js b/security-center/snippets/v1/createFinding.js new file mode 100644 index 0000000000..4e360ae31e --- /dev/null +++ b/security-center/snippets/v1/createFinding.js @@ -0,0 +1,61 @@ +/* + * Copyright 2019, 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'; + +/** + * Demonstrates how to create a new security finding in CSCC. + */ +function main(sourceName = 'FULL_PATH_TO_SOURCE_FOR_FINDING') { + // [START securitycenter_create_finding] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // sourceName is the full resource name of the source the finding should + // be associated with. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + + // Use now as the eventTime for the security finding. + const eventTime = new Date(); + async function createFinding() { + const [newFinding] = await client.createFinding({ + parent: sourceName, + findingId: 'samplefindingid', + finding: { + state: 'ACTIVE', + // Resource the finding is associated with. This is an + // example any resource identifier can be used. + resourceName: + '//cloudresourcemanager.googleapis.com/organizations/11232', + // A free-form category. + category: 'MEDIUM_RISK_ONE', + // The time associated with discovering the issue. + eventTime: { + seconds: Math.floor(eventTime.getTime() / 1000), + nanos: (eventTime.getTime() % 1000) * 1e6, + }, + }, + }); + console.log('New finding created: %j', newFinding); + } + createFinding(); + // [END securitycenter_create_finding] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/createFindingSourceProperties.js b/security-center/snippets/v1/createFindingSourceProperties.js new file mode 100644 index 0000000000..8f15c79828 --- /dev/null +++ b/security-center/snippets/v1/createFindingSourceProperties.js @@ -0,0 +1,66 @@ +/* + * Copyright 2019, 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'; + +/** + * Demonstrates how to create a new security finding in CSCC with source + * properties. + */ +function main(sourceName = 'FULL_PATH_TO_SOURCE_FOR_FINDING') { + // [START securitycenter_create_finding_with_source_properties] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // sourceName is the full resource name of the source the finding should + // be associated with. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + + // Use now as the eventTime for the security finding. + const eventTime = new Date(); + async function createFinding() { + const [newFinding] = await client.createFinding({ + parent: sourceName, + findingId: 'findingwithprops', + finding: { + state: 'ACTIVE', + // Resource the finding is associated with. This is an + // example any resource identifier can be used. + resourceName: + '//cloudresourcemanager.googleapis.com/organizations/11232', + // A free-form category. + category: 'MEDIUM_RISK_ONE', + // The time associated with discovering the issue. + eventTime: { + seconds: Math.floor(eventTime.getTime() / 1000), + nanos: (eventTime.getTime() % 1000) * 1e6, + }, + sourceProperties: { + s_value: {stringValue: 'string_example'}, + n_value: {numberValue: 1234}, + }, + }, + }); + console.log('New finding created: %j', newFinding); + } + createFinding(); + // [END securitycenter_create_finding_with_source_properties] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/createNotificationConfig.js b/security-center/snippets/v1/createNotificationConfig.js new file mode 100644 index 0000000000..d08431c0d9 --- /dev/null +++ b/security-center/snippets/v1/createNotificationConfig.js @@ -0,0 +1,51 @@ +// Copyright 2020 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'; + +function main( + organizationId = 'your-org-id', + configId = 'your-config-name', + pubsubTopic = 'projects/{your-project}/topics/{your-topic}' +) { + // [START securitycenter_create_notification_config] + // npm install @google-cloud/security-center/ + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + const client = new SecurityCenterClient(); + + // organizationId = "your-org-id"; + // configId = "your-config-name"; + // pubsubTopic = "projects/{your-project}/topics/{your-topic}"; + // Ensure this Service Account has the "pubsub.topics.setIamPolicy" permission on this topic. + + const orgName = client.organizationPath(organizationId); + + async function createNotificationConfig() { + const [response] = await client.createNotificationConfig({ + parent: orgName, + configId: configId, + notificationConfig: { + description: 'Sample config for node.js', + pubsubTopic: pubsubTopic, + streamingConfig: {filter: 'state = "ACTIVE"'}, + }, + }); + console.log('Notification config creation succeeded: ', response); + } + + createNotificationConfig(); + // [END securitycenter_create_notification_config] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/createSource.js b/security-center/snippets/v1/createSource.js new file mode 100644 index 0000000000..4d85070867 --- /dev/null +++ b/security-center/snippets/v1/createSource.js @@ -0,0 +1,46 @@ +/* + * Copyright 2019, 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'; + +/** + * createSource demonstrates how to create a new security finding source. + */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_create_source] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // organizationId is numeric organization identifier. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizationId = "1234567777"; + async function createSource() { + const [source] = await client.createSource({ + source: { + displayName: 'Customized Display Name', + description: 'A new custom source that does X', + }, + parent: client.organizationPath(organizationId), + }); + console.log('New Source: %j', source); + } + createSource(); + // [END securitycenter_create_source] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/deleteNotificationConfig.js b/security-center/snippets/v1/deleteNotificationConfig.js new file mode 100644 index 0000000000..944f28b20e --- /dev/null +++ b/security-center/snippets/v1/deleteNotificationConfig.js @@ -0,0 +1,39 @@ +// Copyright 2020 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'; + +function main(organizationId = 'your-org-id', configId = 'your-config-id') { + // [START securitycenter_delete_notification_config] + // npm install @google-cloud/security-center/ + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + const client = new SecurityCenterClient(); + + // organizationId = "your-org-id"; + // configId = "your-config-id"; + const formattedConfigName = client.notificationConfigPath( + organizationId, + configId + ); + + async function deleteNotificationConfg() { + await client.deleteNotificationConfig({name: formattedConfigName}); + console.log('Notification config deleted: ', formattedConfigName); + } + + deleteNotificationConfg(); + // [END securitycenter_delete_notification_config] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/deleteSecurityMarks.js b/security-center/snippets/v1/deleteSecurityMarks.js new file mode 100644 index 0000000000..7ed7e187ae --- /dev/null +++ b/security-center/snippets/v1/deleteSecurityMarks.js @@ -0,0 +1,49 @@ +// Copyright 2019 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'; + +/** + * Demostrates deleting security marks on an asset. + */ +function main(assetName = 'full asset path to add marks to') { + // [START securitycenter_delete_security_marks] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + async function deleteSecurityMarks() { + // assetName is the full resource path for the asset to update. + /* + * TODO(developer): Uncomment the following lines + */ + // const assetName = "organizations/123123342/assets/12312321"; + const [newMarks] = await client.updateSecurityMarks({ + securityMarks: { + name: `${assetName}/securityMarks`, + // Intentionally, not setting marks to delete them. + }, + // Only delete marks for the following keys. + updateMask: {paths: ['marks.key_a', 'marks.key_b']}, + }); + + console.log('Updated marks: %j', newMarks); + } + deleteSecurityMarks(); + // [END securitycenter_delete_security_marks] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/enableAssetDiscovery.js b/security-center/snippets/v1/enableAssetDiscovery.js new file mode 100644 index 0000000000..af11e12d48 --- /dev/null +++ b/security-center/snippets/v1/enableAssetDiscovery.js @@ -0,0 +1,50 @@ +// Copyright 2019 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'; + +/** + * Demostrates enabling asset discovery for an organization. + */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_enable_asset_discovery] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + async function updateOrgSettings() { + // organizationId is the numeric ID of the organization. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizationId = "111122222444"; + const orgName = client.organizationPath(organizationId); + const [newSettings] = await client.updateOrganizationSettings({ + organizationSettings: { + name: `${orgName}/organizationSettings`, + enableAssetDiscovery: true, + }, + // Only update the enableAssetDiscovery field. + updateMask: {paths: ['enable_asset_discovery']}, + }); + + console.log('New settings: %j', newSettings); + } + updateOrgSettings(); + // [END securitycenter_enable_asset_discovery] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/getNotificationConfig.js b/security-center/snippets/v1/getNotificationConfig.js new file mode 100644 index 0000000000..a6742c9c73 --- /dev/null +++ b/security-center/snippets/v1/getNotificationConfig.js @@ -0,0 +1,41 @@ +// Copyright 2020 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'; + +function main(organizationId = 'your-org-id', configId = 'your-config-id') { + // [START securitycenter_get_notification_config] + // npm install @google-cloud/security-center/ + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + const client = new SecurityCenterClient(); + + // organizationId = "your-org-id"; + // configId = "your-config-id"; + const formattedConfigName = client.notificationConfigPath( + organizationId, + configId + ); + + async function getNotificationConfg() { + const [response] = await client.getNotificationConfig({ + name: formattedConfigName, + }); + console.log('Notification config: ', response); + } + + getNotificationConfg(); + // [END securitycenter_get_notification_config] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/getOrganizationSettings.js b/security-center/snippets/v1/getOrganizationSettings.js new file mode 100644 index 0000000000..3e169f0b87 --- /dev/null +++ b/security-center/snippets/v1/getOrganizationSettings.js @@ -0,0 +1,46 @@ +// Copyright 2019 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'; + +/* + * Demostrates retrieving the current organization settings for CSCC. This + * includes the current status of asset recovery. + */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_get_org_settings] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + async function getOrgSettings() { + // organizationId is the numeric ID of the organization. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizaionId = "111122222444"; + const orgName = client.organizationPath(organizationId); + const [settings] = await client.getOrganizationSettings({ + name: `${orgName}/organizationSettings`, + }); + + console.log('Current settings: %j', settings); + } + getOrgSettings(); + // [END securitycenter_get_org_settings] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/getSource.js b/security-center/snippets/v1/getSource.js new file mode 100644 index 0000000000..1603221e03 --- /dev/null +++ b/security-center/snippets/v1/getSource.js @@ -0,0 +1,42 @@ +// Copyright 2019 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'; + +/** + * Demonstrates how to update fields on a security findings + * source. + */ +function main(sourceName = 'FULL_PATH_TO_SOURCE') { + // [START securitycenter_get_source] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // sourceName is the full resource name of the source to be retrieved. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + async function getSource() { + const [source] = await client.getSource({name: sourceName}); + console.log('Source: %j', source); + } + + getSource(); + // [END securitycenter_get_source] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/getSourceIam.js b/security-center/snippets/v1/getSourceIam.js new file mode 100644 index 0000000000..e2e37a6f89 --- /dev/null +++ b/security-center/snippets/v1/getSourceIam.js @@ -0,0 +1,45 @@ +// Copyright 2019 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'; + +/* + * Demostrates retrieving the current IAM policy for a source. + */ +function main(sourceName = 'FULL_PATH_TO_SOURCE') { + // [START securitycenter_get_source_iam] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + async function getSourceIamPolicy() { + // sourceName is the full resource name to retrieve the policy for. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + + const [existingPolicy] = await client.getIamPolicy({ + resource: sourceName, + }); + + console.log('Current policy: %j', existingPolicy); + } + getSourceIamPolicy(); + // [END securitycenter_get_source_iam] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listAllAssets.js b/security-center/snippets/v1/listAllAssets.js new file mode 100644 index 0000000000..85c42cc437 --- /dev/null +++ b/security-center/snippets/v1/listAllAssets.js @@ -0,0 +1,48 @@ +// Copyright 2019 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'; + +/** Prints all assets in an organization. */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_list_all_assets] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // organizationId is the numeric ID of the organization. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizationId = "111122222444"; + const orgName = client.organizationPath(organizationId); + // Call the API with automatic pagination. + async function listAssets() { + const [response] = await client.listAssets({parent: orgName}); + let count = 0; + Array.from(response).forEach(result => + console.log( + `${++count} ${result.asset.name} ${ + result.asset.securityCenterProperties.resourceName + }` + ) + ); + } + + listAssets(); + // [END securitycenter_list_all_assets] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listAllFindings.js b/security-center/snippets/v1/listAllFindings.js new file mode 100644 index 0000000000..fba81eb297 --- /dev/null +++ b/security-center/snippets/v1/listAllFindings.js @@ -0,0 +1,47 @@ +/* + * Copyright 2019, 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'; + +/** Prints all findings across all sources. */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_list_all_findings] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // organizationId is the numeric ID of the organization. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizationId = "1234567777"; + + async function listAllFindings() { + const [response] = await client.listFindings({ + // List findings across all sources. + parent: `organizations/${organizationId}/sources/-`, + }); + let count = 0; + Array.from(response).forEach(result => + console.log( + `${++count} ${result.finding.name} ${result.finding.resourceName}` + ) + ); + } + listAllFindings(); + // [END securitycenter_list_all_findings] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listAllSources.js b/security-center/snippets/v1/listAllSources.js new file mode 100644 index 0000000000..44e21d87a3 --- /dev/null +++ b/security-center/snippets/v1/listAllSources.js @@ -0,0 +1,45 @@ +// Copyright 2019 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'; + +/** Prints all sources in an organization. */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_list_sources] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // organizationId is the numeric ID of the organization. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizaionId = "111122222444"; + const orgName = client.organizationPath(organizationId); + // Call the API with automatic pagination. + async function listSources() { + const [response] = await client.listSources({parent: orgName}); + let count = 0; + console.log('Sources:'); + Array.from(response).forEach(source => + console.log('%d %j', ++count, source) + ); + } + + listSources(); + // [END securitycenter_list_sources] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listAssetsAndChanges.js b/security-center/snippets/v1/listAssetsAndChanges.js new file mode 100644 index 0000000000..233629bbf9 --- /dev/null +++ b/security-center/snippets/v1/listAssetsAndChanges.js @@ -0,0 +1,56 @@ +// Copyright 2019 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'; + +/** + * Prints project assets for the organization and there state changes from 30 + * days ago. + */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_list_assets_and_changes] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // organizationId is the numeric ID of the organization. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizationId = "1234567777"; + const orgName = client.organizationPath(organizationId); + // Call the API with automatic pagination. + async function listAssetsAndChanges() { + const [response] = await client.listAssets({ + parent: orgName, + compareDuration: {seconds: 30 * /*Second in Day=*/ 86400, nanos: 0}, + filter: + 'security_center_properties.resource_type="google.cloud.resourcemanager.Project"', + }); + let count = 0; + Array.from(response).forEach(result => + console.log( + `${++count} ${result.asset.name} ${ + result.asset.securityCenterProperties.resourceName + } ${result.stateChange}` + ) + ); + } + + listAssetsAndChanges(); + // [END securitycenter_list_assets_and_changes] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listAssetsAtTime.js b/security-center/snippets/v1/listAssetsAtTime.js new file mode 100644 index 0000000000..72aeef914f --- /dev/null +++ b/security-center/snippets/v1/listAssetsAtTime.js @@ -0,0 +1,64 @@ +/* + * Copyright 2019, 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'; + +/** + * Prints project assets for the organization as of yesterday. + */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_list_assets_at_time] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // organizationId is the numeric ID of the organization. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizationId = "1234567777"; + const orgName = client.organizationPath(organizationId); + + const oneDayAgo = new Date(); + oneDayAgo.setDate(oneDayAgo.getDate() - 1); + + // Call the API with automatic pagination. + async function listAssetsAtTime() { + const [response] = await client.listAssets({ + parent: orgName, + filter: + 'security_center_properties.resource_type="google.cloud.resourcemanager.Project"', + // readTime must be in the form of a google.protobuf.Timestamp object + // which takes seconds and nanoseconds. + readTime: { + seconds: Math.floor(oneDayAgo.getTime() / 1000), + nanos: (oneDayAgo.getTime() % 1000) * 1e6, + }, + }); + let count = 0; + Array.from(response).forEach(result => + console.log( + `${++count} ${result.asset.name} ${ + result.asset.securityCenterProperties.resourceName + }` + ) + ); + } + + listAssetsAtTime(); + // [END securitycenter_list_assets_at_time] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listAssetsWithSecurityMarks.js b/security-center/snippets/v1/listAssetsWithSecurityMarks.js new file mode 100644 index 0000000000..634401ddd4 --- /dev/null +++ b/security-center/snippets/v1/listAssetsWithSecurityMarks.js @@ -0,0 +1,54 @@ +/* + * Copyright 2019, 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'; + +/** + * Prints assets with security mark of key_a == value_a. + */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_list_assets_with_security_marks] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // organizationId is the numeric ID of the organization. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizationId = "1234567777"; + const orgName = client.organizationPath(organizationId); + + // Call the API with automatic pagination. + async function listAssetsWithSecurityMarks() { + const [response] = await client.listAssets({ + parent: orgName, + filter: 'security_marks.marks.key_a="value_a"', + }); + let count = 0; + Array.from(response).forEach(result => + console.log( + `${++count} ${result.asset.name} ${ + result.asset.securityCenterProperties.resourceName + }` + ) + ); + } + + listAssetsWithSecurityMarks(); + // [END securitycenter_list_assets_with_security_marks] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listFilteredAssets.js b/security-center/snippets/v1/listFilteredAssets.js new file mode 100644 index 0000000000..092db25279 --- /dev/null +++ b/security-center/snippets/v1/listFilteredAssets.js @@ -0,0 +1,55 @@ +/* + * Copyright 2019, 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'; + +/** + * Prints current project assets for the organization. + */ +function main(organizationId = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_list_assets_with_filter] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // organizationId is the numeric ID of the organization. + /* + * TODO(developer): Uncomment the following lines + */ + // const organizationId = "1234567777"; + const orgName = client.organizationPath(organizationId); + + // Call the API with automatic pagination. + async function listFilteredAssets() { + const [response] = await client.listAssets({ + parent: orgName, + filter: + 'security_center_properties.resource_type="google.cloud.resourcemanager.Project"', + }); + let count = 0; + Array.from(response).forEach(result => + console.log( + `${++count} ${result.asset.name} ${ + result.asset.securityCenterProperties.resourceName + } ${result.stateChange}` + ) + ); + } + + listFilteredAssets(); + // [END securitycenter_list_assets_with_filter] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listFilteredFindings.js b/security-center/snippets/v1/listFilteredFindings.js new file mode 100644 index 0000000000..295aeb5aa2 --- /dev/null +++ b/security-center/snippets/v1/listFilteredFindings.js @@ -0,0 +1,49 @@ +/* + * Copyright 2019, 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'; + +/** Demonstrates listing only specific findings. */ +function main(sourceName = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_list_filtered_findings] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // sourceName is the full resource path of the source to search for + // findings. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + + async function listFilteredFindings() { + const [response] = await client.listFindings({ + // List findings across all sources. + parent: sourceName, + filter: 'category="MEDIUM_RISK_ONE"', + }); + let count = 0; + Array.from(response).forEach(result => + console.log( + `${++count} ${result.finding.name} ${result.finding.resourceName}` + ) + ); + } + listFilteredFindings(); + // [END securitycenter_list_filtered_findings] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listFindingsAtTime.js b/security-center/snippets/v1/listFindingsAtTime.js new file mode 100644 index 0000000000..c3032f5b13 --- /dev/null +++ b/security-center/snippets/v1/listFindingsAtTime.js @@ -0,0 +1,55 @@ +/* + * Copyright 2019, 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'; + +/** Demonstrates listing findings at a point in time. */ +function main(sourceName = 'FULL RESOURCE PATH TO PARENT SOURCE') { + // [START securitycenter_list_findings_at_time] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // sourceName is the fully qualified source name to search for findings + // under. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + + const fiveDaysAgo = new Date(); + fiveDaysAgo.setDate(fiveDaysAgo.getDate() - 5); + + async function listFindingsAtTime() { + const [response] = await client.listFindings({ + // List findings across all sources. + parent: sourceName, + readTime: { + seconds: Math.floor(fiveDaysAgo.getTime() / 1000), + nanos: (fiveDaysAgo.getTime() % 1000) * 1e6, + }, + }); + let count = 0; + Array.from(response).forEach(result => + console.log( + `${++count} ${result.finding.name} ${result.finding.resourceName}` + ) + ); + } + listFindingsAtTime(); + // [END securitycenter_list_findings_at_time] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listFindingsWithSecurityMarks.js b/security-center/snippets/v1/listFindingsWithSecurityMarks.js new file mode 100644 index 0000000000..4eb6cde0f0 --- /dev/null +++ b/security-center/snippets/v1/listFindingsWithSecurityMarks.js @@ -0,0 +1,49 @@ +/* + * Copyright 2019, 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'; + +/** Demonstrates listing findings by filtering on security marks. */ +function main(sourceName = 'YOUR_NUMERIC_ORG_ID') { + // [START securitycenter_list_findings_with_security_marks] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // sourceName is the full resource path of the source to search for + // findings. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + + async function listFindingsWithSecurityMarks() { + const [response] = await client.listFindings({ + // List findings across all sources. + parent: sourceName, + filter: 'NOT security_marks.marks.key_a="value_a"', + }); + let count = 0; + Array.from(response).forEach(result => + console.log( + `${++count} ${result.finding.name} ${result.finding.resourceName}` + ) + ); + } + listFindingsWithSecurityMarks(); + // [END securitycenter_list_findings_with_security_marks] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/listNotificationConfigs.js b/security-center/snippets/v1/listNotificationConfigs.js new file mode 100644 index 0000000000..beb5e49c2f --- /dev/null +++ b/security-center/snippets/v1/listNotificationConfigs.js @@ -0,0 +1,38 @@ +// Copyright 2020 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'; + +function main(organizationId = 'your-org-id') { + // [START securitycenter_list_notification_configs] + // npm install @google-cloud/security-center/ + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + const client = new SecurityCenterClient(); + + // organizationId = "your-org-id"; + const orgName = client.organizationPath(organizationId); + + async function listNotificationConfigs() { + const [resources] = await client.listNotificationConfigs({parent: orgName}); + console.log('Received Notification configs: '); + for (const resource of resources) { + console.log(resource); + } + } + + listNotificationConfigs(); + // [END securitycenter_list_notification_configs] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/receiveNotifications.js b/security-center/snippets/v1/receiveNotifications.js new file mode 100644 index 0000000000..604e17f7e7 --- /dev/null +++ b/security-center/snippets/v1/receiveNotifications.js @@ -0,0 +1,60 @@ +// Copyright 2020 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'; + +function main( + projectId = 'your-project-id', + subscriptionId = 'your-subscription-id' +) { + // [START securitycenter_receive_notifications] + const {PubSub} = require('@google-cloud/pubsub'); + const {StringDecoder} = require('string_decoder'); + + // projectId = 'your-project-id' + // subscriptionId = 'your-subscription-id' + + const subscriptionName = + 'projects/' + projectId + '/subscriptions/' + subscriptionId; + const pubSubClient = new PubSub(); + + function listenForMessages() { + const subscription = pubSubClient.subscription(subscriptionName); + + // message.data is a buffer array of json + // 1. Convert buffer to normal string + // 2. Convert json to NotificationMessage object + const messageHandler = message => { + const jsonString = new StringDecoder('utf-8').write(message.data); + const parsedNotificationMessage = JSON.parse(jsonString); + + console.log(parsedNotificationMessage); + console.log(parsedNotificationMessage.finding); + + // ACK when done with message + message.ack(); + }; + + subscription.on('message', messageHandler); + + // Set timeout to 10 seconds + setTimeout(() => { + subscription.removeListener('message', messageHandler); + }, 10000); + } + + listenForMessages(); + // [END securitycenter_receive_notifications] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/setFindingState.js b/security-center/snippets/v1/setFindingState.js new file mode 100644 index 0000000000..8857afe2db --- /dev/null +++ b/security-center/snippets/v1/setFindingState.js @@ -0,0 +1,53 @@ +/* + * Copyright 2019, 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'; + +/** + * Demonstrates how to update a security finding's state in + * CSCC. + */ +function main(findingName = 'FULL_FINDING_PATH') { + // [START securitycenter_update_finding_state] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + // findingName is the full resource name of the source the finding should + // be associated with. + /* + * TODO(developer): Uncomment the following lines + */ + // const findingName = + // "organizations/111122222444/sources/1234/findings/findingid"; + async function setFindingState() { + const eventTime = new Date(); + const [updatedFinding] = await client.setFindingState({ + name: findingName, + state: 'INACTIVE', + // use now as the time when the new state takes effect. + startTime: { + seconds: Math.floor(eventTime.getTime() / 1000), + nanos: (eventTime.getTime() % 1000) * 1e6, + }, + }); + console.log('Updated Finding: %j', updatedFinding); + } + setFindingState(); + // [END securitycenter_update_finding_state] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/setSourceIam.js b/security-center/snippets/v1/setSourceIam.js new file mode 100644 index 0000000000..40d477e137 --- /dev/null +++ b/security-center/snippets/v1/setSourceIam.js @@ -0,0 +1,64 @@ +// Copyright 2019 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'; + +/* + * setSourceIamPolicy grants user roles/securitycenter.findingsEditor permision + * for a source. */ +function main( + sourceName = 'FULL_PATH_TO_SOURCE', + user = 'someuser@domain.com' +) { + // [START securitycenter_set_source_iam] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + async function setSourceIamPolicy() { + // sourceName is the full resource name of the source to be + // updated. + // user is an email address that IAM can grant permissions to. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + // const user = "someuser@domain.com"; + const [existingPolicy] = await client.getIamPolicy({ + resource: sourceName, + }); + + const [updatedPolicy] = await client.setIamPolicy({ + resource: sourceName, + policy: { + // Enables partial update of existing policy + etag: existingPolicy.etag, + bindings: [ + { + role: 'roles/securitycenter.findingsEditor', + // New IAM Binding for the user. + members: [`user:${user}`], + }, + ], + }, + }); + console.log('Updated policy: %j', updatedPolicy); + } + setSourceIamPolicy(); + // [END securitycenter_set_source_iam] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/testIam.js b/security-center/snippets/v1/testIam.js new file mode 100644 index 0000000000..14f23379be --- /dev/null +++ b/security-center/snippets/v1/testIam.js @@ -0,0 +1,60 @@ +/* + * Copyright 2019, 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'; + +/** + * Demonstrates how to determine if your service user has appropriate + * access to create and update findings. + */ +function main(sourceName = 'FULL_SOURCE_PATH') { + // [START securitycenter_test_iam] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + // sourceName is the full resource name of the source to test for permissions. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + async function testIam() { + { + const [policy] = await client.testIamPermissions({ + resource: sourceName, + permissions: ['securitycenter.findings.update'], + }); + console.log( + `Permissions to create/update findings? ${ + policy.permissions.length > 0 + }` + ); + } + { + const [policy] = await client.testIamPermissions({ + resource: sourceName, + permissions: ['securitycenter.findings.setState'], + }); + console.log( + `Permissions to update state? ${policy.permissions.length > 0}` + ); + } + } + testIam(); + // [END securitycenter_test_iam] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/updateFindingSourceProperties.js b/security-center/snippets/v1/updateFindingSourceProperties.js new file mode 100644 index 0000000000..1db64e3e8b --- /dev/null +++ b/security-center/snippets/v1/updateFindingSourceProperties.js @@ -0,0 +1,59 @@ +/* + * Copyright 2019, 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'; + +/** + * Demonstrates how to update a security finding in CSCC. + */ +function main(findingName = 'FULL_FINDING_PATH') { + // [START securitycenter_update_finding_source_properties] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + + // findingName is the full resource name of the finding to update. + /* + * TODO(developer): Uncomment the following lines + */ + // const findingName = + // "organizations/111122222444/sources/1234/findings/findingid"; + + // Use now as the eventTime for the security finding. + const eventTime = new Date(); + console.log(findingName); + async function updateFinding() { + const [newFinding] = await client.updateFinding({ + updateMask: {paths: ['event_time', 'source_properties.s_value']}, + finding: { + name: findingName, + // The time associated with discovering the issue. + eventTime: { + seconds: Math.floor(eventTime.getTime() / 1000), + nanos: (eventTime.getTime() % 1000) * 1e6, + }, + sourceProperties: { + s_value: {stringValue: 'new_string_example'}, + }, + }, + }); + console.log('Updated Finding: %j', newFinding); + } + updateFinding(); + // [END securitycenter_update_finding_source_properties] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/updateNotificationConfig.js b/security-center/snippets/v1/updateNotificationConfig.js new file mode 100644 index 0000000000..a66d327948 --- /dev/null +++ b/security-center/snippets/v1/updateNotificationConfig.js @@ -0,0 +1,56 @@ +// Copyright 2020 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'; + +function main( + organizationId = 'your-org-id', + configId = 'your-config-name', + pubsubTopic = 'projects/{your-project}/topics/{your-topic}' +) { + // [START securitycenter_update_notification_config] + // npm install @google-cloud/security-center/ + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + const client = new SecurityCenterClient(); + + // organizationId = "your-org-id"; + // configId = "your-config-id"; + const formattedConfigName = client.notificationConfigPath( + organizationId, + configId + ); + + // pubsubTopic = "projects/{your-project}/topics/{your-topic}"; + // Ensure this Service Account has the "pubsub.topics.setIamPolicy" permission on this topic. + + async function updateNotificationConfig() { + const [response] = await client.updateNotificationConfig({ + updateMask: { + paths: ['description', 'pubsub_topic', 'streaming_config.filter'], + }, + notificationConfig: { + name: formattedConfigName, + description: 'Updated config description', + pubsubTopic: pubsubTopic, + streamingConfig: {filter: 'state = "INACTIVE"'}, + }, + }); + console.log('notification config update succeeded: ', response); + } + + updateNotificationConfig(); + // [END securitycenter_update_notification_config] +} + +main(...process.argv.slice(2)); diff --git a/security-center/snippets/v1/updateSource.js b/security-center/snippets/v1/updateSource.js new file mode 100644 index 0000000000..586c0ef34d --- /dev/null +++ b/security-center/snippets/v1/updateSource.js @@ -0,0 +1,50 @@ +// Copyright 2019 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'; + +/** + * updateSource demonstrates how to update fields on a security findings + * source. + */ +function main(sourceName = 'FULL_PATH_TO_SOURCE') { + // [START securitycenter_update_source] + // Imports the Google Cloud client library. + const {SecurityCenterClient} = require('@google-cloud/security-center'); + + // Creates a new client. + const client = new SecurityCenterClient(); + // sourceName is the full resource path to the update target. + /* + * TODO(developer): Uncomment the following lines + */ + // const sourceName = "organizations/111122222444/sources/1234"; + async function updateSource() { + const [source] = await client.updateSource({ + source: { + name: sourceName, + displayName: 'New Display Name', + }, + // Only update the display name field (if not set all mutable + // fields of the source will be updated. + updateMask: {paths: ['display_name']}, + }); + console.log('Updated source: %j', source); + } + + updateSource(); + // [END securitycenter_update_source] +} + +main(...process.argv.slice(2));