From 874955b277ffcb84b3719e33eca914301b9ad346 Mon Sep 17 00:00:00 2001 From: rudrakhsha Date: Fri, 28 Mar 2025 11:58:47 +0000 Subject: [PATCH 1/5] Added CRUD code snippets with codeowners file --- .github/blunderbuss.yml | 8 + CODEOWNERS | 1 + model-armor/package.json | 26 ++ model-armor/snippets/createTemplate.js | 92 +++++ .../snippets/createTemplateWithAdvancedSdp.js | 129 ++++++ .../snippets/createTemplateWithBasicSdp.js | 99 +++++ .../snippets/createTemplateWithLabels.js | 92 +++++ .../snippets/createTemplateWithMetadata.js | 92 +++++ model-armor/snippets/deleteTemplate.js | 56 +++ model-armor/snippets/getTemplate.js | 58 +++ model-armor/snippets/listTemplates.js | 58 +++ .../snippets/listTemplatesWithFilter.js | 61 +++ model-armor/snippets/updateTemplate.js | 82 ++++ model-armor/snippets/updateTemplateLabels.js | 71 ++++ .../snippets/updateTemplateMetadata.js | 83 ++++ .../updateTemplateWithMaskConfiguration.js | 90 +++++ model-armor/test/.eslintrc.yml | 3 + model-armor/test/modelarmor.test.js | 367 ++++++++++++++++++ 18 files changed, 1468 insertions(+) create mode 100644 model-armor/package.json create mode 100644 model-armor/snippets/createTemplate.js create mode 100644 model-armor/snippets/createTemplateWithAdvancedSdp.js create mode 100644 model-armor/snippets/createTemplateWithBasicSdp.js create mode 100644 model-armor/snippets/createTemplateWithLabels.js create mode 100644 model-armor/snippets/createTemplateWithMetadata.js create mode 100644 model-armor/snippets/deleteTemplate.js create mode 100644 model-armor/snippets/getTemplate.js create mode 100644 model-armor/snippets/listTemplates.js create mode 100644 model-armor/snippets/listTemplatesWithFilter.js create mode 100644 model-armor/snippets/updateTemplate.js create mode 100644 model-armor/snippets/updateTemplateLabels.js create mode 100644 model-armor/snippets/updateTemplateMetadata.js create mode 100644 model-armor/snippets/updateTemplateWithMaskConfiguration.js create mode 100644 model-armor/test/.eslintrc.yml create mode 100644 model-armor/test/modelarmor.test.js diff --git a/.github/blunderbuss.yml b/.github/blunderbuss.yml index 383983316f..83cbed66df 100644 --- a/.github/blunderbuss.yml +++ b/.github/blunderbuss.yml @@ -44,6 +44,10 @@ assign_issues_by: - "api: parametermanager" to: - GoogleCloudPlatform/cloud-parameters-team +- labels: + - "api: modelarmor" + to: + - GoogleCloudPlatform/cloud-modelarmor-team assign_prs_by: - labels: @@ -77,3 +81,7 @@ assign_prs_by: - "api: parametermanager" to: - GoogleCloudPlatform/cloud-parameters-team +- labels: + - "api: modelarmor" + to: + - GoogleCloudPlatform/cloud-modelarmor-team diff --git a/CODEOWNERS b/CODEOWNERS index e2e4a75e55..bba35081d8 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -44,6 +44,7 @@ document-warehouse @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPla ai-platform @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/text-embedding @GoogleCloudPlatform/cloud-samples-reviewers asset @GoogleCloudPlatform/cloud-asset-analysis-team @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers dlp @GoogleCloudPlatform/googleapis-dlp @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers +model-armor @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/cloud-modelarmor-team security-center @GoogleCloudPlatform/gcp-security-command-center @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers retail @GoogleCloudPlatform/cloud-retail-team @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers media @GoogleCloudPlatform/cloud-media-team @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers diff --git a/model-armor/package.json b/model-armor/package.json new file mode 100644 index 0000000000..40abac10c5 --- /dev/null +++ b/model-armor/package.json @@ -0,0 +1,26 @@ +{ + "name": "nodejs-model-armor-samples", + "private": true, + "license": "Apache-2.0", + "files": [ + "*.js" + ], + "author": "Google LLC", + "repository": "googleapis/nodejs-model-armor", + "engines": { + "node": ">=16.0.0" + }, + "scripts": { + "test": "c8 mocha -p -j 2 --recursive test/ --timeout=60000" + }, + "dependencies": { + "@google-cloud/modelarmor": "^0.1.0" + }, + "devDependencies": { + "c8": "^10.0.0", + "chai": "^4.5.0", + "mocha": "^10.0.0", + "uuid": "^10.0.0" + } +} + \ No newline at end of file diff --git a/model-armor/snippets/createTemplate.js b/model-armor/snippets/createTemplate.js new file mode 100644 index 0000000000..d971ba8aa1 --- /dev/null +++ b/model-armor/snippets/createTemplate.js @@ -0,0 +1,92 @@ +// 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 +// +// 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'; + +/** + * Creates a Model Armor template with Responsible AI (RAI) filters. + * + * This function creates a template that can be used for sanitizing user prompts and model responses. + * + * @param {string} projectId - Google Cloud project ID where the template will be created. + * @param {string} locationId - Google Cloud location (region) for the template, e.g., 'us-central1'. + * @param {string} templateId - Unique identifier for the new template. + */ +async function main(projectId, locationId, templateId) { + // [START modelarmor_create_template] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'us-central1'; + // const templateId = 'your-template-id'; + + const parent = `projects/${projectId}/locations/${locationId}`; + + // Imports the Model Armor library + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function createTemplate() { + /** Build the Model Armor template with your preferred filters. + For more details on filters, please refer to the following doc: + https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters + */ + const templateConfig = { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH, + }, + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType + .SEXUALLY_EXPLICIT, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel + .MEDIUM_AND_ABOVE, + }, + ], + }, + }, + }; + + // Construct request + const request = { + parent, + templateId, + template: templateConfig, + }; + + // Create the template + const [response] = await client.createTemplate(request); + console.log(`Created template: ${response.name}`); + } + + createTemplate(); + // [END modelarmor_create_template] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/createTemplateWithAdvancedSdp.js b/model-armor/snippets/createTemplateWithAdvancedSdp.js new file mode 100644 index 0000000000..01974be3ce --- /dev/null +++ b/model-armor/snippets/createTemplateWithAdvancedSdp.js @@ -0,0 +1,129 @@ +// 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 +// +// 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'; + +/** + * Creates a new model armor template with advanced SDP settings enabled. + * + * @param {string} projectId - Google Cloud project ID where the template will be created. + * @param {string} locationId - Google Cloud location where the template will be created. + * @param {string} templateId - ID for the template to create. + * @param {string} inspectTemplate - Optional. Sensitive Data Protection inspect template resource name. + If only inspect template is provided (de-identify template + not provided), then Sensitive Data Protection InspectContent + action is performed during Sanitization. All Sensitive Data + Protection findings identified during inspection will be + returned as SdpFinding in SdpInsepctionResult e.g. + `organizations/{organization}/inspectTemplates/{inspect_template}`, + `projects/{project}/inspectTemplates/{inspect_template}` + `organizations/{organization}/locations/{location}/inspectTemplates/{inspect_template}` + `projects/{project}/locations/{location}/inspectTemplates/{inspect_template}` + * @param {string} deidentifyTemplate - Optional. Optional Sensitive Data Protection Deidentify template resource name. + If provided then DeidentifyContent action is performed + during Sanitization using this template and inspect + template. The De-identified data will be returned in + SdpDeidentifyResult. Note that all info-types present in the + deidentify template must be present in inspect template. + e.g. + `organizations/{organization}/deidentifyTemplates/{deidentify_template}`, + `projects/{project}/deidentifyTemplates/{deidentify_template}` + `organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}` + `projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}` + */ +async function main( + projectId, + locationId, + templateId, + inspectTemplate, + deidentifyTemplate +) { + // [START modelarmor_create_template_with_advanced_sdp] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'us-central1'; + // const templateId = 'template-id'; + // const inspectTemplate = `projects/${projectId}/locations/${locationId}/inspectTemplates/inspect-template-id`; + // const deidentifyTemplate = `projects/${projectId}/locations/${locationId}/deidentifyTemplates/deidentify-template-id`; + + const parent = `projects/${projectId}/locations/${locationId}`; + + // Imports the Model Armor library + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + const RaiFilterType = protos.google.cloud.modelarmor.v1.RaiFilterType; + const DetectionConfidenceLevel = + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel; + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function createTemplateWithAdvancedSdp() { + // Configuration for the template with advanced SDP settings + const templateConfig = { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: RaiFilterType.DANGEROUS, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.HARASSMENT, + confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, + }, + { + filterType: RaiFilterType.HATE_SPEECH, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.SEXUALLY_EXPLICIT, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + ], + }, + sdpSettings: { + advancedConfig: { + inspectTemplate: inspectTemplate, + deidentifyTemplate: deidentifyTemplate, + }, + }, + }, + }; + + // Construct request + const request = { + parent, + templateId, + template: templateConfig, + }; + + // Create the template + const [response] = await client.createTemplate(request); + console.log(`Created template: ${response.name}`); + } + + createTemplateWithAdvancedSdp(); + // [END modelarmor_create_template_with_advanced_sdp] +} + +// Check if this script is being run directly +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/createTemplateWithBasicSdp.js b/model-armor/snippets/createTemplateWithBasicSdp.js new file mode 100644 index 0000000000..a13cd68437 --- /dev/null +++ b/model-armor/snippets/createTemplateWithBasicSdp.js @@ -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 +// +// 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'; + +/** + * Creates a new model armor template with basic SDP settings enabled. + * + * @param {string} projectId - Google Cloud project ID where the template will be created. + * @param {string} locationId - Google Cloud location where the template will be created. + * @param {string} templateId - ID for the template to create. + */ +async function main(projectId, locationId, templateId) { + // [START modelarmor_create_template_with_basic_sdp] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'us-central1'; + // const templateId = 'template-id'; + + const parent = `projects/${projectId}/locations/${locationId}`; + + // Imports the Model Armor library + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + const RaiFilterType = protos.google.cloud.modelarmor.v1.RaiFilterType; + const DetectionConfidenceLevel = + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel; + const SdpBasicConfigEnforcement = + protos.google.cloud.modelarmor.v1.SdpBasicConfig.SdpBasicConfigEnforcement; + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function createTemplateWithBasicSdp() { + // Configuration for the template with basic SDP settings + const templateConfig = { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: RaiFilterType.DANGEROUS, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.HARASSMENT, + confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, + }, + { + filterType: RaiFilterType.HATE_SPEECH, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.SEXUALLY_EXPLICIT, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + ], + }, + sdpSettings: { + basicConfig: { + filterEnforcement: SdpBasicConfigEnforcement.ENABLED, + }, + }, + }, + }; + + // Construct request + const request = { + parent, + templateId, + template: templateConfig, + }; + + const [response] = await client.createTemplate(request); + console.log(`Created template: ${response.name}`); + } + + return createTemplateWithBasicSdp(); + // [END modelarmor_create_template_with_basic_sdp] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/createTemplateWithLabels.js b/model-armor/snippets/createTemplateWithLabels.js new file mode 100644 index 0000000000..8d6c549cca --- /dev/null +++ b/model-armor/snippets/createTemplateWithLabels.js @@ -0,0 +1,92 @@ +// 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 +// +// 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'; + +/** + * Creates a Model Armor template with Responsible AI (RAI) filters and custom labels. + * + * @param {string} projectId - Google Cloud project ID where the template will be created. + * @param {string} locationId - Google Cloud location (region) for the template, e.g., 'us-central1'. + * @param {string} templateId - Unique identifier for the new template. + * @param {string} labelKey - The key for the label to add to the template. + * @param {string} labelValue - The value for the label. + */ +async function main(projectId, locationId, templateId, labelKey, labelValue) { + // [START modelarmor_create_template_with_labels] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'us-central1'; + // const templateId = 'your-template-id'; + // const labelKey = 'environment'; + // const labelValue = 'production'; + + const parent = `projects/${projectId}/locations/${locationId}`; + + // Imports the Model Armor library + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function createTemplateWithLabels() { + // Construct the request with template configuration and labels + const request = { + parent, + templateId, + template: { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel + .HIGH, + }, + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType + .SEXUALLY_EXPLICIT, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel + .MEDIUM_AND_ABOVE, + }, + ], + }, + }, + labels: { + [labelKey]: labelValue, + }, + }, + }; + + // Create the template + const [response] = await client.createTemplate(request); + console.log(`Created template: ${response.name}`); + } + + createTemplateWithLabels(); + // [END modelarmor_create_template_with_labels] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/createTemplateWithMetadata.js b/model-armor/snippets/createTemplateWithMetadata.js new file mode 100644 index 0000000000..3e07163150 --- /dev/null +++ b/model-armor/snippets/createTemplateWithMetadata.js @@ -0,0 +1,92 @@ +// 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 +// +// 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'; + +/** + * Creates a new model armor template with template metadata. + * + * @param {string} projectId - Google Cloud project ID where the template will be created. + * @param {string} locationId - Google Cloud location where the template will be created. + * @param {string} templateId - ID for the template to create. + */ +async function main(projectId, locationId, templateId) { + // [START modelarmor_create_template_with_metadata] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'us-central1'; + // const templateId = 'template-id'; + + const parent = `projects/${projectId}/locations/${locationId}`; + + // Imports the Model Armor library + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + const RaiFilterType = protos.google.cloud.modelarmor.v1.RaiFilterType; + const DetectionConfidenceLevel = + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel; + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function createTemplateWithMetadata() { + /** Add template metadata to the template. + * For more details on template metadata, please refer to the following doc: + * https://cloud.google.com/security-command-center/docs/reference/model-armor/rest/v1/projects.locations.templates#templatemetadata + */ + const templateConfig = { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: RaiFilterType.HATE_SPEECH, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.SEXUALLY_EXPLICIT, + confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, + }, + ], + }, + }, + templateMetadata: { + ignorePartialInvocationFailures: true, + logSanitizeOperations: true, + }, + }; + + // Construct request + const request = { + parent, + templateId, + template: templateConfig, + }; + + // Create the template + const [response] = await client.createTemplate(request); + console.log(`Created Model Armor Template: ${response.name}`); + } + + return createTemplateWithMetadata(); + // [END modelarmor_create_template_with_metadata] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/deleteTemplate.js b/model-armor/snippets/deleteTemplate.js new file mode 100644 index 0000000000..e82d58320e --- /dev/null +++ b/model-armor/snippets/deleteTemplate.js @@ -0,0 +1,56 @@ +// 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 +// +// 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'; + +/** + * Deletes a Model Armor template. + * + * @param {string} projectId - Google Cloud project ID where the template exists. + * @param {string} locationId - Google Cloud location (region) of the template, e.g., 'us-central1'. + * @param {string} templateId - Identifier of the template to delete. + */ +async function main(projectId, locationId, templateId) { + // [START modelarmor_delete_template] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'my-project'; + // const locationId = 'us-central1'; + // const templateId = 'my-template'; + + const name = `projects/${projectId}/locations/${locationId}/templates/${templateId}`; + + // Imports the Model Armor library + const {ModelArmorClient} = require('@google-cloud/modelarmor'); + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function deleteTemplate() { + await client.deleteTemplate({ + name: name, + }); + + console.log(`Deleted template ${name}`); + } + + deleteTemplate(); + // [END modelarmor_delete_template] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/getTemplate.js b/model-armor/snippets/getTemplate.js new file mode 100644 index 0000000000..28cda68bff --- /dev/null +++ b/model-armor/snippets/getTemplate.js @@ -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 +// +// 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'; + +/** + * Retrieves a Model Armor template by its ID. + * + * @param {string} projectId - Google Cloud project ID where the template exists. + * @param {string} locationId - Google Cloud location (region) of the template. + * @param {string} templateId - Identifier of the template to retrieve. + */ +async function main(projectId, locationId, templateId) { + // [START modelarmor_get_template] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'my-project'; + // const locationId = 'my-location'; + // const templateId = 'my-template'; + + const name = `projects/${projectId}/locations/${locationId}/templates/${templateId}`; + + // Imports the Model Armor library + const {ModelArmorClient} = require('@google-cloud/modelarmor').v1; + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function getModelArmorTemplate() { + const request = { + name: name, + }; + + // Run request + const response = await client.getTemplate(request); + console.log(`Template name: ${response[0].name}`); + } + + getModelArmorTemplate(); + // [END modelarmor_get_template] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/listTemplates.js b/model-armor/snippets/listTemplates.js new file mode 100644 index 0000000000..2412cb29ef --- /dev/null +++ b/model-armor/snippets/listTemplates.js @@ -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 +// +// 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'; + +/** + * Lists all Model Armor templates in a specified project and location. + * + * @param {string} projectId - Google Cloud project ID to list templates from. + * @param {string} locationId - Google Cloud location (region) to list templates from. + */ +async function main(projectId, locationId) { + // [START modelarmor_list_templates] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'YOUR_PROJECT_ID'; + // const locationId = 'us-central1'; + + const parent = `projects/${projectId}/locations/${locationId}`; + + // Imports the Model Armor library + const {ModelArmorClient} = require('@google-cloud/modelarmor'); + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function listTemplates() { + const request = { + parent: parent, + }; + + // Run request + const iterable = client.listTemplatesAsync(request); + for await (const template of iterable) { + console.log(template.name); + } + } + + listTemplates(); + // [END modelarmor_list_templates] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/listTemplatesWithFilter.js b/model-armor/snippets/listTemplatesWithFilter.js new file mode 100644 index 0000000000..7cf4cc469d --- /dev/null +++ b/model-armor/snippets/listTemplatesWithFilter.js @@ -0,0 +1,61 @@ +// 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 +// +// 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'; + +/** + * Lists Model Armor templates that match a specific filter criteria. + * + * @param {string} projectId - Google Cloud project ID to list templates from. + * @param {string} locationId - Google Cloud location (region) to list templates from, e.g., 'us-central1'. + * @param {string} templateId - Template ID to filter by. Only templates with this ID will be returned. + */ +async function main(projectId, locationId, templateId) { + // [START modelarmor_list_templates_with_filter] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'your-location-id'; + // const templateId = 'your-template-id'; + + const parent = `projects/${projectId}/locations/${locationId}`; + + // Imports the Model Armor library + const {ModelArmorClient} = require('@google-cloud/modelarmor').v1; + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function listModelArmorTemplatesWithFilter() { + const request = { + parent: parent, + filter: `name="${parent}/templates/${templateId}"`, + }; + + const iterable = await client.listTemplatesAsync(request); + + for await (const template of iterable) { + console.log(`Found template ${template.name}`); + } + } + + listModelArmorTemplatesWithFilter(); + // [END modelarmor_list_templates_with_filter] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/updateTemplate.js b/model-armor/snippets/updateTemplate.js new file mode 100644 index 0000000000..b894851b49 --- /dev/null +++ b/model-armor/snippets/updateTemplate.js @@ -0,0 +1,82 @@ +// 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 +// +// 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'; + +/** + * Updates an existing model armor template. + * + * @param {string} projectId - Google Cloud project ID where the template exists. + * @param {string} locationId - Google Cloud location where the template exists. + * @param {string} templateId - ID of the template to update. + */ +async function main(projectId, locationId, templateId) { + // [START modelarmor_update_template] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'us-central1'; + // const templateId = 'template-id'; + + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + const DetectionConfidenceLevel = + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel; + const PiAndJailbreakFilterEnforcement = + protos.google.cloud.modelarmor.v1.PiAndJailbreakFilterSettings + .PiAndJailbreakFilterEnforcement; + const MaliciousUriFilterEnforcement = + protos.google.cloud.modelarmor.v1.MaliciousUriFilterSettings + .MaliciousUriFilterEnforcement; + + // Instantiates a client + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function updateTemplate() { + // Build the updated template configuration + const updatedTemplate = { + name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`, + filterConfig: { + piAndJailbreakFilterSettings: { + filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, + confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE, + }, + maliciousUriFilterSettings: { + filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, + }, + }, + }; + + const request = { + template: updatedTemplate, + }; + + const [response] = await client.updateTemplate(request); + console.log( + 'Updated template filter configuration:', + response.filterConfig + ); + } + + return updateTemplate(); + // [END modelarmor_update_template] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/updateTemplateLabels.js b/model-armor/snippets/updateTemplateLabels.js new file mode 100644 index 0000000000..df0c23f18e --- /dev/null +++ b/model-armor/snippets/updateTemplateLabels.js @@ -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 +// +// 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'; + +/** + * Updates the labels of an existing model armor template. + * + * @param {string} projectId - Google Cloud project ID where the template exists. + * @param {string} locationId - Google Cloud location where the template exists. + * @param {string} templateId - ID of the template to update. + * @param {string} labelKey - The key for the label to add or update. + * @param {string} labelValue - The value for the label to add or update. + */ +async function main(projectId, locationId, templateId, labelKey, labelValue) { + // [START modelarmor_update_template_with_labels] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'us-central1'; + // const templateId = 'template-id'; + // const labelKey = 'env'; + // const labelValue = 'prod'; + + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + async function updateTemplateLabels() { + const labels = {}; + labels[labelKey] = labelValue; + + const template = { + name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`, + labels: labels, + }; + + const updateMask = { + paths: ['labels'], + }; + + const request = { + template: template, + updateMask: updateMask, + }; + + const [response] = await client.updateTemplate(request); + console.log(`Updated Model Armor Template: ${response.name}`); + } + + return updateTemplateLabels(); + // [END modelarmor_update_template_with_labels] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/updateTemplateMetadata.js b/model-armor/snippets/updateTemplateMetadata.js new file mode 100644 index 0000000000..4148700949 --- /dev/null +++ b/model-armor/snippets/updateTemplateMetadata.js @@ -0,0 +1,83 @@ +// 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 +// +// 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'; + +/** + * Updates the metadata of an existing model armor template. + * + * @param {string} projectId - Google Cloud project ID where the template exists. + * @param {string} locationId - Google Cloud location where the template exists. + * @param {string} templateId - ID of the template to update. + */ +async function main(projectId, locationId, templateId) { + // [START modelarmor_update_template_metadata] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'us-central1'; + // const templateId = 'template-id'; + + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + const DetectionConfidenceLevel = + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel; + const PiAndJailbreakFilterEnforcement = + protos.google.cloud.modelarmor.v1.PiAndJailbreakFilterSettings + .PiAndJailbreakFilterEnforcement; + const MaliciousUriFilterEnforcement = + protos.google.cloud.modelarmor.v1.MaliciousUriFilterSettings + .MaliciousUriFilterEnforcement; + + async function updateTemplateMetadata() { + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateId}`; + + const template = { + name: templateName, + filterConfig: { + piAndJailbreakFilterSettings: { + filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, + confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE, + }, + maliciousUriFilterSettings: { + filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, + }, + }, + templateMetadata: { + ignorePartialInvocationFailures: true, + logSanitizeOperations: false, + }, + }; + + const request = { + template: template, + }; + + const [response] = await client.updateTemplate(request); + console.log(`Updated Model Armor Template: ${response.name}`); + } + + updateTemplateMetadata(); + // [END modelarmor_update_template_metadata] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/updateTemplateWithMaskConfiguration.js b/model-armor/snippets/updateTemplateWithMaskConfiguration.js new file mode 100644 index 0000000000..6c0aed2eee --- /dev/null +++ b/model-armor/snippets/updateTemplateWithMaskConfiguration.js @@ -0,0 +1,90 @@ +// 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 +// +// 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'; + +/** + * Updates an existing model armor template with a specific update mask. + * + * @param {string} projectId - Google Cloud project ID where the template exists. + * @param {string} locationId - Google Cloud location where the template exists. + * @param {string} templateId - ID of the template to update. + */ +async function main(projectId, locationId, templateId) { + // [START modelarmor_update_template_with_mask_configuration] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + // const locationId = 'us-central1'; + // const templateId = 'template-id'; + + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + const client = new ModelArmorClient({ + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, + }); + + const DetectionConfidenceLevel = + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel; + const PiAndJailbreakFilterEnforcement = + protos.google.cloud.modelarmor.v1.PiAndJailbreakFilterSettings + .PiAndJailbreakFilterEnforcement; + const MaliciousUriFilterEnforcement = + protos.google.cloud.modelarmor.v1.MaliciousUriFilterSettings + .MaliciousUriFilterEnforcement; + + async function updateTemplateWithMaskConfiguration() { + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateId}`; + + // Build the Model Armor template with your preferred filters + // For more details on filters, please refer to the following doc: + // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters + const template = { + name: templateName, + filterConfig: { + piAndJailbreakFilterSettings: { + filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, + confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE, + }, + maliciousUriFilterSettings: { + filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, + }, + }, + }; + + // Mask config for specifying field to update + // Refer to following documentation for more details on update mask field and its usage: + // https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask + const updateMask = { + paths: ['filter_config'], + }; + + const request = { + template: template, + updateMask: updateMask, + }; + + const [response] = await client.updateTemplate(request); + console.log(`Updated Model Armor Template: ${response.name}`); + } + + updateTemplateWithMaskConfiguration(); + // [END modelarmor_update_template_with_mask_configuration] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/test/.eslintrc.yml b/model-armor/test/.eslintrc.yml new file mode 100644 index 0000000000..e28757c0a5 --- /dev/null +++ b/model-armor/test/.eslintrc.yml @@ -0,0 +1,3 @@ +--- +env: + mocha: true \ No newline at end of file diff --git a/model-armor/test/modelarmor.test.js b/model-armor/test/modelarmor.test.js new file mode 100644 index 0000000000..675518e7fc --- /dev/null +++ b/model-armor/test/modelarmor.test.js @@ -0,0 +1,367 @@ +// Copyright 2023 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 cp = require('child_process'); +const {v4: uuidv4} = require('uuid'); +const {ModelArmorClient} = require('@google-cloud/modelarmor').v1; + +let projectId; +const locationId = process.env.GCLOUD_LOCATION || 'us-central1'; +const options = { + apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, +}; + +const client = new ModelArmorClient(options); +const templateIdPrefix = `test-template-${uuidv4().substring(0, 8)}`; + +let emptyTemplateId; +let basicTemplateId; +let basicSdpTemplateId; +let templateToDeleteId; + +const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'}); + +// Helper function to create a template for sanitization tests +async function createTemplate(templateId, filterConfig) { + const parent = `projects/${projectId}/locations/${locationId}`; + + try { + const [response] = await client.createTemplate({ + parent: parent, + templateId: templateId, + template: { + filterConfig: filterConfig, + }, + }); + + console.log(`Created template: ${response.name}`); + return response; + } catch (error) { + console.error(`Error creating template ${templateId}:`, error); + throw error; + } +} + +// Helper function to delete a template +async function deleteTemplate(templateName) { + try { + await client.deleteTemplate({ + name: templateName, + }); + console.log(`Deleted template: ${templateName}`); + } catch (error) { + if (error.code === 5) { + // Not found + console.log(`Template ${templateName} was not found.`); + } else { + console.error(`Error deleting template ${templateName}:`, error); + } + } +} + +describe('Model Armor tests', () => { + const templatesToDelete = []; + + before(async () => { + // projectId = await client.getProjectId(); + projectId = 'ma-crest-data-test-2'; + + // Import necessary enums + const {protos} = require('@google-cloud/modelarmor'); + const DetectionConfidenceLevel = + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel; + const PiAndJailbreakFilterEnforcement = + protos.google.cloud.modelarmor.v1.PiAndJailbreakFilterSettings + .PiAndJailbreakFilterEnforcement; + const MaliciousUriFilterEnforcement = + protos.google.cloud.modelarmor.v1.MaliciousUriFilterSettings + .MaliciousUriFilterEnforcement; + const RaiFilterType = protos.google.cloud.modelarmor.v1.RaiFilterType; + const SdpBasicConfigEnforcement = + protos.google.cloud.modelarmor.v1.SdpBasicConfig + .SdpBasicConfigEnforcement; + + // Create empty template for sanitizeUserPrompt tests + emptyTemplateId = `${templateIdPrefix}-empty`; + await createTemplate(emptyTemplateId, {}); + + // Create basic template with PI/Jailbreak and Malicious URI filters for sanitizeUserPrompt tests + basicTemplateId = `${templateIdPrefix}-basic`; + await createTemplate(basicTemplateId, { + piAndJailbreakFilterSettings: { + filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, + confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, + }, + maliciousUriFilterSettings: { + filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, + }, + }); + + // Create a template to be deleted + templateToDeleteId = `${templateIdPrefix}-to-delete`; + await createTemplate(templateToDeleteId, { + piAndJailbreakFilterSettings: { + filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, + confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, + }, + maliciousUriFilterSettings: { + filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, + }, + }); + + // Create a basic SDP template for testing + basicSdpTemplateId = `${templateIdPrefix}-basic-sdp`; + await createTemplate(basicSdpTemplateId, { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: RaiFilterType.DANGEROUS, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.HARASSMENT, + confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, + }, + { + filterType: RaiFilterType.HATE_SPEECH, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.SEXUALLY_EXPLICIT, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + ], + }, + sdpSettings: { + basicConfig: { + filterEnforcement: SdpBasicConfigEnforcement.ENABLED, + }, + }, + }, + }); + + templatesToDelete.push( + `projects/${projectId}/locations/${locationId}/templates/${emptyTemplateId}`, + `projects/${projectId}/locations/${locationId}/templates/${basicTemplateId}`, + `projects/${projectId}/locations/${locationId}/templates/${basicSdpTemplateId}` + ); + }); + + after(async () => { + // Clean up all templates + const directTemplates = [emptyTemplateId, basicTemplateId]; + for (const templateId of directTemplates) { + await deleteTemplate( + `projects/${projectId}/locations/${locationId}/templates/${templateId}` + ); + } + + for (const templateName of templatesToDelete) { + try { + await client.deleteTemplate({name: templateName}); + console.log(`Cleaned up template: ${templateName}`); + } catch (error) { + console.error(`Failed to delete template ${templateName}:`, error); + } + } + }); + + // =================== Template Creation Tests =================== + + it('should create a basic template', async () => { + const testTemplateId = `${templateIdPrefix}-basic-create`; + + const output = execSync( + `node snippets/createTemplate.js ${projectId} ${locationId} ${testTemplateId}` + ); + + const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; + templatesToDelete.push(templateName); + + assert.match(output, new RegExp(`Created template: ${templateName}`)); + }); + + it('should create a template with basic SDP settings', async () => { + const testTemplateId = `${templateIdPrefix}-basic-sdp-1`; + + const output = execSync( + `node snippets/createTemplateWithBasicSdp.js ${projectId} ${locationId} ${testTemplateId}` + ); + + const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; + templatesToDelete.push(templateName); + + assert.match(output, new RegExp(`Created template: ${templateName}`)); + }); + + it('should create a template with advanced SDP settings', async () => { + const testTemplateId = `${templateIdPrefix}-adv-sdp`; + const inspectTemplate = basicSdpTemplateId; + const deidentifyTemplate = basicSdpTemplateId; + + const fullInspectTemplate = `projects/${projectId}/locations/${locationId}/inspectTemplates/${inspectTemplate}`; + const fullDeidentifyTemplate = `projects/${projectId}/locations/${locationId}/deidentifyTemplates/${deidentifyTemplate}`; + + const output = execSync( + `node snippets/createTemplateWithAdvancedSdp.js ${projectId} ${locationId} ${testTemplateId} ${fullInspectTemplate} ${fullDeidentifyTemplate}` + ); + + const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; + templatesToDelete.push(templateName); + + assert.match(output, new RegExp(`Created template: ${templateName}`)); + }); + + it('should create a template with metadata', async () => { + const testTemplateId = `${templateIdPrefix}-metadata`; + + const output = execSync( + `node snippets/createTemplateWithMetadata.js ${projectId} ${locationId} ${testTemplateId}` + ); + + const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; + templatesToDelete.push(templateName); + + assert.match( + output, + new RegExp(`Created Model Armor Template: ${templateName}`) + ); + }); + + it('should create a template with labels', async () => { + const testTemplateId = `${templateIdPrefix}-labels`; + const labelKey = 'environment'; + const labelValue = 'test'; + + const output = execSync( + `node snippets/createTemplateWithLabels.js ${projectId} ${locationId} ${testTemplateId} ${labelKey} ${labelValue}` + ); + + const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; + templatesToDelete.push(templateName); + + assert.match(output, new RegExp(`Created template: ${templateName}`)); + }); + + // =================== Template Management Tests =================== + + it('should get a template', async () => { + const templateToGet = `${templateIdPrefix}-basic-sdp`; + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToGet}`; + const output = execSync( + `node snippets/getTemplate.js ${projectId} ${locationId} ${templateToGet}` + ); + + assert.match(output, new RegExp(`Template name: ${templateName}`)); + }); + + it('should delete a template', async () => { + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToDeleteId}`; + + const output = execSync( + `node snippets/deleteTemplate.js ${projectId} ${locationId} ${templateToDeleteId}` + ); + + assert.match(output, new RegExp(`Deleted template ${templateName}`)); + }); + + it('should list templates', async () => { + const output = execSync( + `node snippets/listTemplates.js ${projectId} ${locationId}` + ); + + const templateNamePattern = `projects/${projectId}/locations/${locationId}/templates/${templateIdPrefix}`; + + assert.match(output, new RegExp(templateNamePattern)); + }); + + it('should list templates with filter', async () => { + const templateToGet = `${templateIdPrefix}-basic-sdp`; + const output = execSync( + `node snippets/listTemplatesWithFilter.js ${projectId} ${locationId} ${templateToGet}` + ); + + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToGet}`; + + assert.match(output, new RegExp(`Found template ${templateName}`)); + }); + + // =================== Template Update Tests =================== + + it('should update a template', async () => { + const templateToUpdate = `${templateIdPrefix}-basic-create`; + const output = execSync( + `node snippets/updateTemplate.js ${projectId} ${locationId} ${templateToUpdate}` + ); + + assert.match(output, /Updated template filter configuration:/); + + assert.match(output, /piAndJailbreakFilterSettings/); + assert.match(output, /filterEnforcement: 'ENABLED'/); + assert.match(output, /confidenceLevel: 'LOW_AND_ABOVE'/); + assert.match(output, /maliciousUriFilterSettings/); + }); + + it('should update template labels', async () => { + const labelKey = 'environment'; + const labelValue = 'testing'; + const templateToUpdate = `${templateIdPrefix}-basic-create`; + + const output = execSync( + `node snippets/updateTemplateLabels.js ${projectId} ${locationId} ${templateToUpdate} ${labelKey} ${labelValue}` + ); + + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToUpdate}`; + + assert.match( + output, + new RegExp(`Updated Model Armor Template: ${templateName}`) + ); + }); + + it('should update template metadata', async () => { + const templateToUpdateMetadata = `${templateIdPrefix}-metadata`; + + const output = execSync( + `node snippets/updateTemplateMetadata.js ${projectId} ${locationId} ${templateToUpdateMetadata}` + ); + + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToUpdateMetadata}`; + + assert.match( + output, + new RegExp(`Updated Model Armor Template: ${templateName}`) + ); + }); + + it('should update template with mask configuration', async () => { + const templateToUpdateWithMask = `${templateIdPrefix}-metadata`; + + const output = execSync( + `node snippets/updateTemplateWithMaskConfiguration.js ${projectId} ${locationId} ${templateToUpdateWithMask}` + ); + + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToUpdateWithMask}`; + + assert.match( + output, + new RegExp(`Updated Model Armor Template: ${templateName}`) + ); + }); + +}); From 8270ed77587d16042d6a52517bb007450caa9986 Mon Sep 17 00:00:00 2001 From: rudrakhsha Date: Fri, 28 Mar 2025 12:02:20 +0000 Subject: [PATCH 2/5] Solved linting errors --- model-armor/test/modelarmor.test.js | 1 - 1 file changed, 1 deletion(-) diff --git a/model-armor/test/modelarmor.test.js b/model-armor/test/modelarmor.test.js index 675518e7fc..3d86161f78 100644 --- a/model-armor/test/modelarmor.test.js +++ b/model-armor/test/modelarmor.test.js @@ -363,5 +363,4 @@ describe('Model Armor tests', () => { new RegExp(`Updated Model Armor Template: ${templateName}`) ); }); - }); From 3824b657b0572714354a0e9accd1c1c9657cbcff Mon Sep 17 00:00:00 2001 From: rudrakhsha Date: Fri, 28 Mar 2025 12:46:43 +0000 Subject: [PATCH 3/5] Added header comment --- model-armor/test/.eslintrc.yml | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/model-armor/test/.eslintrc.yml b/model-armor/test/.eslintrc.yml index e28757c0a5..9351c489b5 100644 --- a/model-armor/test/.eslintrc.yml +++ b/model-armor/test/.eslintrc.yml @@ -1,3 +1,17 @@ +# 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 +# +# 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. + --- env: mocha: true \ No newline at end of file From 0b9faee5fa474952dac7646afa5413f03eb933d1 Mon Sep 17 00:00:00 2001 From: rudrakhsha Date: Fri, 28 Mar 2025 15:51:01 +0000 Subject: [PATCH 4/5] Removed hardcoded value from test --- model-armor/test/modelarmor.test.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/model-armor/test/modelarmor.test.js b/model-armor/test/modelarmor.test.js index 3d86161f78..743f3f1bfe 100644 --- a/model-armor/test/modelarmor.test.js +++ b/model-armor/test/modelarmor.test.js @@ -77,8 +77,7 @@ describe('Model Armor tests', () => { const templatesToDelete = []; before(async () => { - // projectId = await client.getProjectId(); - projectId = 'ma-crest-data-test-2'; + projectId = await client.getProjectId(); // Import necessary enums const {protos} = require('@google-cloud/modelarmor'); From 7890c3a2786dc991604edbad800da44d7ed9ea8c Mon Sep 17 00:00:00 2001 From: rudrakhsha-crest Date: Fri, 25 Apr 2025 12:51:43 +0000 Subject: [PATCH 5/5] Updated code snippets and tests as per comments given in other PRs --- model-armor/snippets/createTemplate.js | 76 ++++--- .../snippets/createTemplateWithAdvancedSdp.js | 84 ++++---- .../snippets/createTemplateWithBasicSdp.js | 79 ++++--- .../snippets/createTemplateWithLabels.js | 78 +++---- .../snippets/createTemplateWithMetadata.js | 73 +++---- model-armor/snippets/deleteTemplate.js | 18 +- model-armor/snippets/getTemplate.js | 21 +- model-armor/snippets/listTemplates.js | 24 +-- .../snippets/listTemplatesWithFilter.js | 25 ++- model-armor/snippets/updateTemplate.js | 46 ++--- model-armor/snippets/updateTemplateLabels.js | 45 ++-- .../snippets/updateTemplateMetadata.js | 49 ++--- .../updateTemplateWithMaskConfiguration.js | 67 +++--- model-armor/test/modelarmor.test.js | 195 +++++++++++------- 14 files changed, 440 insertions(+), 440 deletions(-) diff --git a/model-armor/snippets/createTemplate.js b/model-armor/snippets/createTemplate.js index d971ba8aa1..43010db2f0 100644 --- a/model-armor/snippets/createTemplate.js +++ b/model-armor/snippets/createTemplate.js @@ -23,7 +23,7 @@ * @param {string} locationId - Google Cloud location (region) for the template, e.g., 'us-central1'. * @param {string} templateId - Unique identifier for the new template. */ -async function main(projectId, locationId, templateId) { +async function createTemplate(projectId, locationId, templateId) { // [START modelarmor_create_template] /** * TODO(developer): Uncomment these variables before running the sample. @@ -44,49 +44,43 @@ async function main(projectId, locationId, templateId) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function createTemplate() { - /** Build the Model Armor template with your preferred filters. - For more details on filters, please refer to the following doc: - https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters - */ - const templateConfig = { - filterConfig: { - raiSettings: { - raiFilters: [ - { - filterType: - protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH, - confidenceLevel: - protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH, - }, - { - filterType: - protos.google.cloud.modelarmor.v1.RaiFilterType - .SEXUALLY_EXPLICIT, - confidenceLevel: - protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel - .MEDIUM_AND_ABOVE, - }, - ], - }, + /** Build the Model Armor template with your preferred filters. + For more details on filters, please refer to the following doc: + https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters + */ + const templateConfig = { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH, + }, + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType.SEXUALLY_EXPLICIT, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel + .MEDIUM_AND_ABOVE, + }, + ], }, - }; - - // Construct request - const request = { - parent, - templateId, - template: templateConfig, - }; + }, + }; - // Create the template - const [response] = await client.createTemplate(request); - console.log(`Created template: ${response.name}`); - } + // Construct request + const request = { + parent, + templateId, + template: templateConfig, + }; - createTemplate(); + // Create the template + const [response] = await client.createTemplate(request); + return response; // [END modelarmor_create_template] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = createTemplate; diff --git a/model-armor/snippets/createTemplateWithAdvancedSdp.js b/model-armor/snippets/createTemplateWithAdvancedSdp.js index 01974be3ce..cef66edfaa 100644 --- a/model-armor/snippets/createTemplateWithAdvancedSdp.js +++ b/model-armor/snippets/createTemplateWithAdvancedSdp.js @@ -42,7 +42,7 @@ `organizations/{organization}/locations/{location}/deidentifyTemplates/{deidentify_template}` `projects/{project}/locations/{location}/deidentifyTemplates/{deidentify_template}` */ -async function main( +async function createTemplateWithAdvancedSdp( projectId, locationId, templateId, @@ -75,55 +75,49 @@ async function main( apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function createTemplateWithAdvancedSdp() { - // Configuration for the template with advanced SDP settings - const templateConfig = { - filterConfig: { - raiSettings: { - raiFilters: [ - { - filterType: RaiFilterType.DANGEROUS, - confidenceLevel: DetectionConfidenceLevel.HIGH, - }, - { - filterType: RaiFilterType.HARASSMENT, - confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, - }, - { - filterType: RaiFilterType.HATE_SPEECH, - confidenceLevel: DetectionConfidenceLevel.HIGH, - }, - { - filterType: RaiFilterType.SEXUALLY_EXPLICIT, - confidenceLevel: DetectionConfidenceLevel.HIGH, - }, - ], - }, - sdpSettings: { - advancedConfig: { - inspectTemplate: inspectTemplate, - deidentifyTemplate: deidentifyTemplate, + // Configuration for the template with advanced SDP settings + const templateConfig = { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: RaiFilterType.DANGEROUS, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.HARASSMENT, + confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, + }, + { + filterType: RaiFilterType.HATE_SPEECH, + confidenceLevel: DetectionConfidenceLevel.HIGH, }, + { + filterType: RaiFilterType.SEXUALLY_EXPLICIT, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + ], + }, + sdpSettings: { + advancedConfig: { + inspectTemplate: inspectTemplate, + deidentifyTemplate: deidentifyTemplate, }, }, - }; - - // Construct request - const request = { - parent, - templateId, - template: templateConfig, - }; + }, + }; - // Create the template - const [response] = await client.createTemplate(request); - console.log(`Created template: ${response.name}`); - } + // Construct request + const request = { + parent, + templateId, + template: templateConfig, + }; - createTemplateWithAdvancedSdp(); + // Create the template + const [response] = await client.createTemplate(request); + return response; // [END modelarmor_create_template_with_advanced_sdp] } -// Check if this script is being run directly -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = createTemplateWithAdvancedSdp; diff --git a/model-armor/snippets/createTemplateWithBasicSdp.js b/model-armor/snippets/createTemplateWithBasicSdp.js index a13cd68437..33ba1850e5 100644 --- a/model-armor/snippets/createTemplateWithBasicSdp.js +++ b/model-armor/snippets/createTemplateWithBasicSdp.js @@ -21,7 +21,7 @@ * @param {string} locationId - Google Cloud location where the template will be created. * @param {string} templateId - ID for the template to create. */ -async function main(projectId, locationId, templateId) { +async function createTemplateWithBasicSdp(projectId, locationId, templateId) { // [START modelarmor_create_template_with_basic_sdp] /** * TODO(developer): Uncomment these variables before running the sample. @@ -48,52 +48,47 @@ async function main(projectId, locationId, templateId) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function createTemplateWithBasicSdp() { - // Configuration for the template with basic SDP settings - const templateConfig = { - filterConfig: { - raiSettings: { - raiFilters: [ - { - filterType: RaiFilterType.DANGEROUS, - confidenceLevel: DetectionConfidenceLevel.HIGH, - }, - { - filterType: RaiFilterType.HARASSMENT, - confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, - }, - { - filterType: RaiFilterType.HATE_SPEECH, - confidenceLevel: DetectionConfidenceLevel.HIGH, - }, - { - filterType: RaiFilterType.SEXUALLY_EXPLICIT, - confidenceLevel: DetectionConfidenceLevel.HIGH, - }, - ], - }, - sdpSettings: { - basicConfig: { - filterEnforcement: SdpBasicConfigEnforcement.ENABLED, + // Configuration for the template with basic SDP settings + const templateConfig = { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: RaiFilterType.DANGEROUS, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.HARASSMENT, + confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, + }, + { + filterType: RaiFilterType.HATE_SPEECH, + confidenceLevel: DetectionConfidenceLevel.HIGH, }, + { + filterType: RaiFilterType.SEXUALLY_EXPLICIT, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + ], + }, + sdpSettings: { + basicConfig: { + filterEnforcement: SdpBasicConfigEnforcement.ENABLED, }, }, - }; - - // Construct request - const request = { - parent, - templateId, - template: templateConfig, - }; + }, + }; - const [response] = await client.createTemplate(request); - console.log(`Created template: ${response.name}`); - } + // Construct request + const request = { + parent, + templateId, + template: templateConfig, + }; - return createTemplateWithBasicSdp(); + const [response] = await client.createTemplate(request); + return response; // [END modelarmor_create_template_with_basic_sdp] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = createTemplateWithBasicSdp; diff --git a/model-armor/snippets/createTemplateWithLabels.js b/model-armor/snippets/createTemplateWithLabels.js index 8d6c549cca..610081fa4c 100644 --- a/model-armor/snippets/createTemplateWithLabels.js +++ b/model-armor/snippets/createTemplateWithLabels.js @@ -23,7 +23,13 @@ * @param {string} labelKey - The key for the label to add to the template. * @param {string} labelValue - The value for the label. */ -async function main(projectId, locationId, templateId, labelKey, labelValue) { +async function createTemplateWithLabels( + projectId, + locationId, + templateId, + labelKey, + labelValue +) { // [START modelarmor_create_template_with_labels] /** * TODO(developer): Uncomment these variables before running the sample. @@ -46,47 +52,41 @@ async function main(projectId, locationId, templateId, labelKey, labelValue) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function createTemplateWithLabels() { - // Construct the request with template configuration and labels - const request = { - parent, - templateId, - template: { - filterConfig: { - raiSettings: { - raiFilters: [ - { - filterType: - protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH, - confidenceLevel: - protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel - .HIGH, - }, - { - filterType: - protos.google.cloud.modelarmor.v1.RaiFilterType - .SEXUALLY_EXPLICIT, - confidenceLevel: - protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel - .MEDIUM_AND_ABOVE, - }, - ], - }, - }, - labels: { - [labelKey]: labelValue, + // Construct the request with template configuration and labels + const request = { + parent, + templateId, + template: { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH, + }, + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType + .SEXUALLY_EXPLICIT, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel + .MEDIUM_AND_ABOVE, + }, + ], }, }, - }; - - // Create the template - const [response] = await client.createTemplate(request); - console.log(`Created template: ${response.name}`); - } + labels: { + [labelKey]: labelValue, + }, + }, + }; - createTemplateWithLabels(); + // Create the template + const [response] = await client.createTemplate(request); + return response; // [END modelarmor_create_template_with_labels] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = createTemplateWithLabels; diff --git a/model-armor/snippets/createTemplateWithMetadata.js b/model-armor/snippets/createTemplateWithMetadata.js index 3e07163150..d1e182eb4d 100644 --- a/model-armor/snippets/createTemplateWithMetadata.js +++ b/model-armor/snippets/createTemplateWithMetadata.js @@ -21,7 +21,7 @@ * @param {string} locationId - Google Cloud location where the template will be created. * @param {string} templateId - ID for the template to create. */ -async function main(projectId, locationId, templateId) { +async function createTemplateWithMetadata(projectId, locationId, templateId) { // [START modelarmor_create_template_with_metadata] /** * TODO(developer): Uncomment these variables before running the sample. @@ -46,47 +46,42 @@ async function main(projectId, locationId, templateId) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function createTemplateWithMetadata() { - /** Add template metadata to the template. - * For more details on template metadata, please refer to the following doc: - * https://cloud.google.com/security-command-center/docs/reference/model-armor/rest/v1/projects.locations.templates#templatemetadata - */ - const templateConfig = { - filterConfig: { - raiSettings: { - raiFilters: [ - { - filterType: RaiFilterType.HATE_SPEECH, - confidenceLevel: DetectionConfidenceLevel.HIGH, - }, - { - filterType: RaiFilterType.SEXUALLY_EXPLICIT, - confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, - }, - ], - }, - }, - templateMetadata: { - ignorePartialInvocationFailures: true, - logSanitizeOperations: true, + /** Add template metadata to the template. + * For more details on template metadata, please refer to the following doc: + * https://cloud.google.com/security-command-center/docs/reference/model-armor/rest/v1/projects.locations.templates#templatemetadata + */ + const templateConfig = { + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: RaiFilterType.HATE_SPEECH, + confidenceLevel: DetectionConfidenceLevel.HIGH, + }, + { + filterType: RaiFilterType.SEXUALLY_EXPLICIT, + confidenceLevel: DetectionConfidenceLevel.MEDIUM_AND_ABOVE, + }, + ], }, - }; - - // Construct request - const request = { - parent, - templateId, - template: templateConfig, - }; + }, + templateMetadata: { + ignorePartialInvocationFailures: true, + logSanitizeOperations: true, + }, + }; - // Create the template - const [response] = await client.createTemplate(request); - console.log(`Created Model Armor Template: ${response.name}`); - } + // Construct request + const request = { + parent, + templateId, + template: templateConfig, + }; - return createTemplateWithMetadata(); + // Create the template + const [response] = await client.createTemplate(request); + return response; // [END modelarmor_create_template_with_metadata] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = createTemplateWithMetadata; diff --git a/model-armor/snippets/deleteTemplate.js b/model-armor/snippets/deleteTemplate.js index e82d58320e..8bcabc1e55 100644 --- a/model-armor/snippets/deleteTemplate.js +++ b/model-armor/snippets/deleteTemplate.js @@ -21,7 +21,7 @@ * @param {string} locationId - Google Cloud location (region) of the template, e.g., 'us-central1'. * @param {string} templateId - Identifier of the template to delete. */ -async function main(projectId, locationId, templateId) { +async function deleteTemplate(projectId, locationId, templateId) { // [START modelarmor_delete_template] /** * TODO(developer): Uncomment these variables before running the sample. @@ -40,17 +40,11 @@ async function main(projectId, locationId, templateId) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function deleteTemplate() { - await client.deleteTemplate({ - name: name, - }); - - console.log(`Deleted template ${name}`); - } - - deleteTemplate(); + const response = await client.deleteTemplate({ + name: name, + }); + return response; // [END modelarmor_delete_template] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = deleteTemplate; diff --git a/model-armor/snippets/getTemplate.js b/model-armor/snippets/getTemplate.js index 28cda68bff..3f82094fee 100644 --- a/model-armor/snippets/getTemplate.js +++ b/model-armor/snippets/getTemplate.js @@ -21,7 +21,7 @@ * @param {string} locationId - Google Cloud location (region) of the template. * @param {string} templateId - Identifier of the template to retrieve. */ -async function main(projectId, locationId, templateId) { +async function getTemplate(projectId, locationId, templateId) { // [START modelarmor_get_template] /** * TODO(developer): Uncomment these variables before running the sample. @@ -40,19 +40,14 @@ async function main(projectId, locationId, templateId) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function getModelArmorTemplate() { - const request = { - name: name, - }; + const request = { + name: name, + }; - // Run request - const response = await client.getTemplate(request); - console.log(`Template name: ${response[0].name}`); - } - - getModelArmorTemplate(); + // Run request + const [response] = await client.getTemplate(request); + return response; // [END modelarmor_get_template] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = getTemplate; diff --git a/model-armor/snippets/listTemplates.js b/model-armor/snippets/listTemplates.js index 2412cb29ef..0a348262a6 100644 --- a/model-armor/snippets/listTemplates.js +++ b/model-armor/snippets/listTemplates.js @@ -20,7 +20,7 @@ * @param {string} projectId - Google Cloud project ID to list templates from. * @param {string} locationId - Google Cloud location (region) to list templates from. */ -async function main(projectId, locationId) { +async function listTemplates(projectId, locationId) { // [START modelarmor_list_templates] /** * TODO(developer): Uncomment these variables before running the sample. @@ -38,21 +38,19 @@ async function main(projectId, locationId) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function listTemplates() { - const request = { - parent: parent, - }; + const request = { + parent: parent, + }; - // Run request - const iterable = client.listTemplatesAsync(request); - for await (const template of iterable) { - console.log(template.name); - } + // Run request and collect all results + const templates = []; + const iterable = client.listTemplatesAsync(request); + for await (const template of iterable) { + templates.push(template); } - listTemplates(); + return templates; // [END modelarmor_list_templates] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = listTemplates; diff --git a/model-armor/snippets/listTemplatesWithFilter.js b/model-armor/snippets/listTemplatesWithFilter.js index 7cf4cc469d..64910720c5 100644 --- a/model-armor/snippets/listTemplatesWithFilter.js +++ b/model-armor/snippets/listTemplatesWithFilter.js @@ -21,7 +21,7 @@ * @param {string} locationId - Google Cloud location (region) to list templates from, e.g., 'us-central1'. * @param {string} templateId - Template ID to filter by. Only templates with this ID will be returned. */ -async function main(projectId, locationId, templateId) { +async function listTemplatesWithFilter(projectId, locationId, templateId) { // [START modelarmor_list_templates_with_filter] /** * TODO(developer): Uncomment these variables before running the sample. @@ -40,22 +40,21 @@ async function main(projectId, locationId, templateId) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function listModelArmorTemplatesWithFilter() { - const request = { - parent: parent, - filter: `name="${parent}/templates/${templateId}"`, - }; + const request = { + parent: parent, + filter: `name="${parent}/templates/${templateId}"`, + }; - const iterable = await client.listTemplatesAsync(request); + // Run request and collect all results + const templates = []; + const iterable = await client.listTemplatesAsync(request); - for await (const template of iterable) { - console.log(`Found template ${template.name}`); - } + for await (const template of iterable) { + templates.push(template); } - listModelArmorTemplatesWithFilter(); + return templates; // [END modelarmor_list_templates_with_filter] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = listTemplatesWithFilter; diff --git a/model-armor/snippets/updateTemplate.js b/model-armor/snippets/updateTemplate.js index b894851b49..b7edf2dc67 100644 --- a/model-armor/snippets/updateTemplate.js +++ b/model-armor/snippets/updateTemplate.js @@ -21,7 +21,7 @@ * @param {string} locationId - Google Cloud location where the template exists. * @param {string} templateId - ID of the template to update. */ -async function main(projectId, locationId, templateId) { +async function updateTemplate(projectId, locationId, templateId) { // [START modelarmor_update_template] /** * TODO(developer): Uncomment these variables before running the sample. @@ -48,35 +48,27 @@ async function main(projectId, locationId, templateId) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function updateTemplate() { - // Build the updated template configuration - const updatedTemplate = { - name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`, - filterConfig: { - piAndJailbreakFilterSettings: { - filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, - confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE, - }, - maliciousUriFilterSettings: { - filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, - }, + // Build the updated template configuration + const updatedTemplate = { + name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`, + filterConfig: { + piAndJailbreakFilterSettings: { + filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, + confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE, }, - }; - - const request = { - template: updatedTemplate, - }; + maliciousUriFilterSettings: { + filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, + }, + }, + }; - const [response] = await client.updateTemplate(request); - console.log( - 'Updated template filter configuration:', - response.filterConfig - ); - } + const request = { + template: updatedTemplate, + }; - return updateTemplate(); + const [response] = await client.updateTemplate(request); + return response; // [END modelarmor_update_template] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = updateTemplate; diff --git a/model-armor/snippets/updateTemplateLabels.js b/model-armor/snippets/updateTemplateLabels.js index df0c23f18e..63a4cc466c 100644 --- a/model-armor/snippets/updateTemplateLabels.js +++ b/model-armor/snippets/updateTemplateLabels.js @@ -23,7 +23,13 @@ * @param {string} labelKey - The key for the label to add or update. * @param {string} labelValue - The value for the label to add or update. */ -async function main(projectId, locationId, templateId, labelKey, labelValue) { +async function updateTemplateWithLabels( + projectId, + locationId, + templateId, + labelKey, + labelValue +) { // [START modelarmor_update_template_with_labels] /** * TODO(developer): Uncomment these variables before running the sample. @@ -41,31 +47,26 @@ async function main(projectId, locationId, templateId, labelKey, labelValue) { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }); - async function updateTemplateLabels() { - const labels = {}; - labels[labelKey] = labelValue; + const labels = {}; + labels[labelKey] = labelValue; - const template = { - name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`, - labels: labels, - }; + const template = { + name: `projects/${projectId}/locations/${locationId}/templates/${templateId}`, + labels: labels, + }; - const updateMask = { - paths: ['labels'], - }; + const updateMask = { + paths: ['labels'], + }; - const request = { - template: template, - updateMask: updateMask, - }; + const request = { + template: template, + updateMask: updateMask, + }; - const [response] = await client.updateTemplate(request); - console.log(`Updated Model Armor Template: ${response.name}`); - } - - return updateTemplateLabels(); + const [response] = await client.updateTemplate(request); + return response; // [END modelarmor_update_template_with_labels] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = updateTemplateWithLabels; diff --git a/model-armor/snippets/updateTemplateMetadata.js b/model-armor/snippets/updateTemplateMetadata.js index 4148700949..82a8f608da 100644 --- a/model-armor/snippets/updateTemplateMetadata.js +++ b/model-armor/snippets/updateTemplateMetadata.js @@ -21,7 +21,7 @@ * @param {string} locationId - Google Cloud location where the template exists. * @param {string} templateId - ID of the template to update. */ -async function main(projectId, locationId, templateId) { +async function updateTemplateMetadata(projectId, locationId, templateId) { // [START modelarmor_update_template_metadata] /** * TODO(developer): Uncomment these variables before running the sample. @@ -47,37 +47,32 @@ async function main(projectId, locationId, templateId) { protos.google.cloud.modelarmor.v1.MaliciousUriFilterSettings .MaliciousUriFilterEnforcement; - async function updateTemplateMetadata() { - const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateId}`; + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateId}`; - const template = { - name: templateName, - filterConfig: { - piAndJailbreakFilterSettings: { - filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, - confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE, - }, - maliciousUriFilterSettings: { - filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, - }, + const template = { + name: templateName, + filterConfig: { + piAndJailbreakFilterSettings: { + filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, + confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE, }, - templateMetadata: { - ignorePartialInvocationFailures: true, - logSanitizeOperations: false, + maliciousUriFilterSettings: { + filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, }, - }; + }, + templateMetadata: { + ignorePartialInvocationFailures: true, + logSanitizeOperations: false, + }, + }; - const request = { - template: template, - }; + const request = { + template: template, + }; - const [response] = await client.updateTemplate(request); - console.log(`Updated Model Armor Template: ${response.name}`); - } - - updateTemplateMetadata(); + const [response] = await client.updateTemplate(request); + return response; // [END modelarmor_update_template_metadata] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = updateTemplateMetadata; diff --git a/model-armor/snippets/updateTemplateWithMaskConfiguration.js b/model-armor/snippets/updateTemplateWithMaskConfiguration.js index 6c0aed2eee..0e7e596db3 100644 --- a/model-armor/snippets/updateTemplateWithMaskConfiguration.js +++ b/model-armor/snippets/updateTemplateWithMaskConfiguration.js @@ -21,7 +21,11 @@ * @param {string} locationId - Google Cloud location where the template exists. * @param {string} templateId - ID of the template to update. */ -async function main(projectId, locationId, templateId) { +async function updateTemplateWithMaskConfiguration( + projectId, + locationId, + templateId +) { // [START modelarmor_update_template_with_mask_configuration] /** * TODO(developer): Uncomment these variables before running the sample. @@ -47,44 +51,39 @@ async function main(projectId, locationId, templateId) { protos.google.cloud.modelarmor.v1.MaliciousUriFilterSettings .MaliciousUriFilterEnforcement; - async function updateTemplateWithMaskConfiguration() { - const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateId}`; + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateId}`; - // Build the Model Armor template with your preferred filters - // For more details on filters, please refer to the following doc: - // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters - const template = { - name: templateName, - filterConfig: { - piAndJailbreakFilterSettings: { - filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, - confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE, - }, - maliciousUriFilterSettings: { - filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, - }, + // Build the Model Armor template with your preferred filters + // For more details on filters, please refer to the following doc: + // https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters + const template = { + name: templateName, + filterConfig: { + piAndJailbreakFilterSettings: { + filterEnforcement: PiAndJailbreakFilterEnforcement.ENABLED, + confidenceLevel: DetectionConfidenceLevel.LOW_AND_ABOVE, }, - }; - - // Mask config for specifying field to update - // Refer to following documentation for more details on update mask field and its usage: - // https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask - const updateMask = { - paths: ['filter_config'], - }; + maliciousUriFilterSettings: { + filterEnforcement: MaliciousUriFilterEnforcement.ENABLED, + }, + }, + }; - const request = { - template: template, - updateMask: updateMask, - }; + // Mask config for specifying field to update + // Refer to following documentation for more details on update mask field and its usage: + // https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask + const updateMask = { + paths: ['filter_config'], + }; - const [response] = await client.updateTemplate(request); - console.log(`Updated Model Armor Template: ${response.name}`); - } + const request = { + template: template, + updateMask: updateMask, + }; - updateTemplateWithMaskConfiguration(); + const [response] = await client.updateTemplate(request); + return response; // [END modelarmor_update_template_with_mask_configuration] } -const args = process.argv.slice(2); -main(...args).catch(console.error); +module.exports = updateTemplateWithMaskConfiguration; diff --git a/model-armor/test/modelarmor.test.js b/model-armor/test/modelarmor.test.js index 743f3f1bfe..2cfb83077c 100644 --- a/model-armor/test/modelarmor.test.js +++ b/model-armor/test/modelarmor.test.js @@ -15,7 +15,6 @@ 'use strict'; const {assert} = require('chai'); -const cp = require('child_process'); const {v4: uuidv4} = require('uuid'); const {ModelArmorClient} = require('@google-cloud/modelarmor').v1; @@ -33,8 +32,6 @@ let basicTemplateId; let basicSdpTemplateId; let templateToDeleteId; -const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'}); - // Helper function to create a template for sanitization tests async function createTemplate(templateId, filterConfig) { const parent = `projects/${projectId}/locations/${locationId}`; @@ -184,77 +181,90 @@ describe('Model Armor tests', () => { it('should create a basic template', async () => { const testTemplateId = `${templateIdPrefix}-basic-create`; + const createTemplate = require('../snippets/createTemplate'); - const output = execSync( - `node snippets/createTemplate.js ${projectId} ${locationId} ${testTemplateId}` + const response = await createTemplate( + projectId, + locationId, + testTemplateId ); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; templatesToDelete.push(templateName); - assert.match(output, new RegExp(`Created template: ${templateName}`)); + assert.strictEqual(response.name, templateName); }); it('should create a template with basic SDP settings', async () => { const testTemplateId = `${templateIdPrefix}-basic-sdp-1`; + const createTemplateWithBasicSdp = require('../snippets/createTemplateWithBasicSdp'); - const output = execSync( - `node snippets/createTemplateWithBasicSdp.js ${projectId} ${locationId} ${testTemplateId}` + const response = await createTemplateWithBasicSdp( + projectId, + locationId, + testTemplateId ); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; templatesToDelete.push(templateName); - assert.match(output, new RegExp(`Created template: ${templateName}`)); + assert.strictEqual(response.name, templateName); }); it('should create a template with advanced SDP settings', async () => { const testTemplateId = `${templateIdPrefix}-adv-sdp`; const inspectTemplate = basicSdpTemplateId; const deidentifyTemplate = basicSdpTemplateId; + const createTemplateWithAdvancedSdp = require('../snippets/createTemplateWithAdvancedSdp'); const fullInspectTemplate = `projects/${projectId}/locations/${locationId}/inspectTemplates/${inspectTemplate}`; const fullDeidentifyTemplate = `projects/${projectId}/locations/${locationId}/deidentifyTemplates/${deidentifyTemplate}`; - const output = execSync( - `node snippets/createTemplateWithAdvancedSdp.js ${projectId} ${locationId} ${testTemplateId} ${fullInspectTemplate} ${fullDeidentifyTemplate}` + const response = await createTemplateWithAdvancedSdp( + projectId, + locationId, + testTemplateId, + fullInspectTemplate, + fullDeidentifyTemplate ); const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; templatesToDelete.push(templateName); - assert.match(output, new RegExp(`Created template: ${templateName}`)); + assert.strictEqual(response.name, templateName); }); it('should create a template with metadata', async () => { const testTemplateId = `${templateIdPrefix}-metadata`; + const createTemplateWithMetadata = require('../snippets/createTemplateWithMetadata'); - const output = execSync( - `node snippets/createTemplateWithMetadata.js ${projectId} ${locationId} ${testTemplateId}` + const response = await createTemplateWithMetadata( + projectId, + locationId, + testTemplateId ); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; templatesToDelete.push(templateName); - assert.match( - output, - new RegExp(`Created Model Armor Template: ${templateName}`) - ); + assert.strictEqual(response.name, templateName); }); it('should create a template with labels', async () => { const testTemplateId = `${templateIdPrefix}-labels`; const labelKey = 'environment'; const labelValue = 'test'; - - const output = execSync( - `node snippets/createTemplateWithLabels.js ${projectId} ${locationId} ${testTemplateId} ${labelKey} ${labelValue}` + const createTemplateWithLabels = require('../snippets/createTemplateWithLabels'); + + const response = await createTemplateWithLabels( + projectId, + locationId, + testTemplateId, + labelKey, + labelValue ); const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; templatesToDelete.push(templateName); - assert.match(output, new RegExp(`Created template: ${templateName}`)); + assert.strictEqual(response.name, templateName); }); // =================== Template Management Tests =================== @@ -262,104 +272,143 @@ describe('Model Armor tests', () => { it('should get a template', async () => { const templateToGet = `${templateIdPrefix}-basic-sdp`; const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToGet}`; - const output = execSync( - `node snippets/getTemplate.js ${projectId} ${locationId} ${templateToGet}` - ); - assert.match(output, new RegExp(`Template name: ${templateName}`)); + const getTemplate = require('../snippets/getTemplate'); + const template = await getTemplate(projectId, locationId, templateToGet); + + assert.strictEqual(template.name, templateName); }); it('should delete a template', async () => { - const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToDeleteId}`; - - const output = execSync( - `node snippets/deleteTemplate.js ${projectId} ${locationId} ${templateToDeleteId}` + const deleteTemplate = require('../snippets/deleteTemplate'); + const response = await deleteTemplate( + projectId, + locationId, + templateToDeleteId ); + assert.isArray(response); + assert.isObject(response[0]); + assert.isNull(response[1]); + assert.isNull(response[2]); - assert.match(output, new RegExp(`Deleted template ${templateName}`)); + assert.deepEqual(response[0], {}); }); it('should list templates', async () => { - const output = execSync( - `node snippets/listTemplates.js ${projectId} ${locationId}` - ); + const listTemplates = require('../snippets/listTemplates'); + const templates = await listTemplates(projectId, locationId); - const templateNamePattern = `projects/${projectId}/locations/${locationId}/templates/${templateIdPrefix}`; + const hasMatchingTemplate = templates.some(template => + template.name.includes(templateIdPrefix) + ); - assert.match(output, new RegExp(templateNamePattern)); + assert.isTrue( + hasMatchingTemplate, + `Should find at least one template with prefix ${templateIdPrefix}` + ); }); it('should list templates with filter', async () => { const templateToGet = `${templateIdPrefix}-basic-sdp`; - const output = execSync( - `node snippets/listTemplatesWithFilter.js ${projectId} ${locationId} ${templateToGet}` - ); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToGet}`; - assert.match(output, new RegExp(`Found template ${templateName}`)); + const listTemplatesWithFilter = require('../snippets/listTemplatesWithFilter'); + const templates = await listTemplatesWithFilter( + projectId, + locationId, + templateToGet + ); + // Should find exactly one template + assert.strictEqual(templates.length, 1); + assert.strictEqual(templates[0].name, templateName); }); // =================== Template Update Tests =================== it('should update a template', async () => { const templateToUpdate = `${templateIdPrefix}-basic-create`; - const output = execSync( - `node snippets/updateTemplate.js ${projectId} ${locationId} ${templateToUpdate}` + + const updateTemplate = require('../snippets/updateTemplate'); + const response = await updateTemplate( + projectId, + locationId, + templateToUpdate ); + assert.property(response, 'filterConfig'); + assert.property(response.filterConfig, 'piAndJailbreakFilterSettings'); + assert.property(response.filterConfig, 'maliciousUriFilterSettings'); - assert.match(output, /Updated template filter configuration:/); + const piSettings = response.filterConfig.piAndJailbreakFilterSettings; + assert.strictEqual(piSettings.filterEnforcement, 'ENABLED'); + assert.strictEqual(piSettings.confidenceLevel, 'LOW_AND_ABOVE'); - assert.match(output, /piAndJailbreakFilterSettings/); - assert.match(output, /filterEnforcement: 'ENABLED'/); - assert.match(output, /confidenceLevel: 'LOW_AND_ABOVE'/); - assert.match(output, /maliciousUriFilterSettings/); + const uriSettings = response.filterConfig.maliciousUriFilterSettings; + assert.strictEqual(uriSettings.filterEnforcement, 'ENABLED'); }); it('should update template labels', async () => { const labelKey = 'environment'; const labelValue = 'testing'; const templateToUpdate = `${templateIdPrefix}-basic-create`; - - const output = execSync( - `node snippets/updateTemplateLabels.js ${projectId} ${locationId} ${templateToUpdate} ${labelKey} ${labelValue}` - ); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToUpdate}`; - assert.match( - output, - new RegExp(`Updated Model Armor Template: ${templateName}`) + const updateTemplateWithLabels = require('../snippets/updateTemplateLabels'); + const response = await updateTemplateWithLabels( + projectId, + locationId, + templateToUpdate, + labelKey, + labelValue ); + + assert.strictEqual(response.name, templateName); + assert.property(response, 'labels'); }); it('should update template metadata', async () => { const templateToUpdateMetadata = `${templateIdPrefix}-metadata`; + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToUpdateMetadata}`; - const output = execSync( - `node snippets/updateTemplateMetadata.js ${projectId} ${locationId} ${templateToUpdateMetadata}` + const updateTemplateMetadata = require('../snippets/updateTemplateMetadata'); + const response = await updateTemplateMetadata( + projectId, + locationId, + templateToUpdateMetadata ); + assert.strictEqual(response.name, templateName); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToUpdateMetadata}`; - - assert.match( - output, - new RegExp(`Updated Model Armor Template: ${templateName}`) + assert.property(response, 'templateMetadata'); + assert.property( + response.templateMetadata, + 'ignorePartialInvocationFailures' ); + assert.property(response.templateMetadata, 'logSanitizeOperations'); + assert.strictEqual( + response.templateMetadata.ignorePartialInvocationFailures, + true + ); + assert.strictEqual(response.templateMetadata.logSanitizeOperations, false); }); it('should update template with mask configuration', async () => { const templateToUpdateWithMask = `${templateIdPrefix}-metadata`; + const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToUpdateWithMask}`; - const output = execSync( - `node snippets/updateTemplateWithMaskConfiguration.js ${projectId} ${locationId} ${templateToUpdateWithMask}` + const updateTemplateWithMaskConfiguration = require('../snippets/updateTemplateWithMaskConfiguration'); + const response = await updateTemplateWithMaskConfiguration( + projectId, + locationId, + templateToUpdateWithMask ); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToUpdateWithMask}`; + assert.strictEqual(response.name, templateName); - assert.match( - output, - new RegExp(`Updated Model Armor Template: ${templateName}`) - ); + assert.property(response, 'filterConfig'); + assert.property(response.filterConfig, 'piAndJailbreakFilterSettings'); + assert.property(response.filterConfig, 'maliciousUriFilterSettings'); + + const piSettings = response.filterConfig.piAndJailbreakFilterSettings; + assert.strictEqual(piSettings.filterEnforcement, 'ENABLED'); + assert.strictEqual(piSettings.confidenceLevel, 'LOW_AND_ABOVE'); }); });