From 874955b277ffcb84b3719e33eca914301b9ad346 Mon Sep 17 00:00:00 2001 From: rudrakhsha Date: Fri, 28 Mar 2025 11:58:47 +0000 Subject: [PATCH 1/8] 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/8] 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/8] 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/8] 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 16111a565aaf04b76b2cb89e7d1c18cc3cd359d1 Mon Sep 17 00:00:00 2001 From: rudrakhsha Date: Fri, 28 Mar 2025 16:00:34 +0000 Subject: [PATCH 5/8] Added floor settings snippets --- .../snippets/getFolderFloorSettings.js | 52 +++++ .../snippets/getOrganizationFloorSettings.js | 54 +++++ .../snippets/getProjectFloorSettings.js | 54 +++++ .../snippets/updateFolderFloorSettings.js | 73 +++++++ .../updateOrganizationFloorSettings.js | 68 ++++++ .../snippets/updateProjectFloorSettings.js | 67 ++++++ model-armor/test/modelarmor.test.js | 197 ++++-------------- 7 files changed, 410 insertions(+), 155 deletions(-) create mode 100644 model-armor/snippets/getFolderFloorSettings.js create mode 100644 model-armor/snippets/getOrganizationFloorSettings.js create mode 100644 model-armor/snippets/getProjectFloorSettings.js create mode 100644 model-armor/snippets/updateFolderFloorSettings.js create mode 100644 model-armor/snippets/updateOrganizationFloorSettings.js create mode 100644 model-armor/snippets/updateProjectFloorSettings.js diff --git a/model-armor/snippets/getFolderFloorSettings.js b/model-armor/snippets/getFolderFloorSettings.js new file mode 100644 index 0000000000..d0233bf379 --- /dev/null +++ b/model-armor/snippets/getFolderFloorSettings.js @@ -0,0 +1,52 @@ +// 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 the floor settings for a Google Cloud folder. + * + * @param {string} folderId - The ID of the Google Cloud folder for which to retrieve floor settings. + */ +async function main(folderId) { + // [START modelarmor_get_folder_floor_settings] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const folderId = 'your-folder-id'; + + const name = `folders/${folderId}/locations/global/floorSetting`; + + // Imports the Modelarmor library + const {ModelArmorClient} = require('@google-cloud/modelarmor').v1; + + // Instantiates a client + const modelarmorClient = new ModelArmorClient(); + + async function getFolderFloorSettings() { + // Construct request + const request = { + name, + }; + + const response = await modelarmorClient.getFloorSetting(request); + console.log(response); + } + + getFolderFloorSettings(); + // [END modelarmor_get_folder_floor_settings] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/getOrganizationFloorSettings.js b/model-armor/snippets/getOrganizationFloorSettings.js new file mode 100644 index 0000000000..e0c07ad5f7 --- /dev/null +++ b/model-armor/snippets/getOrganizationFloorSettings.js @@ -0,0 +1,54 @@ +// 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 the floor settings for a Google Cloud organization. + * + * @param {string} organizationId - The ID of the Google Cloud organization for which to retrieve + * floor settings. + */ +async function main(organizationId) { + // [START modelarmor_get_organization_floor_settings] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const organizationId = 'your-organization-id'; + + const name = `organizations/${organizationId}/locations/global/floorSetting`; + + // Imports the Modelarmor library + const {ModelArmorClient} = require('@google-cloud/modelarmor').v1; + + // Instantiates a client + const modelarmorClient = new ModelArmorClient(); + + async function getOrganizationFloorSettings() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await modelarmorClient.getFloorSetting(request); + console.log(response); + } + + getOrganizationFloorSettings(); + // [END modelarmor_get_organization_floor_settings] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/getProjectFloorSettings.js b/model-armor/snippets/getProjectFloorSettings.js new file mode 100644 index 0000000000..e8922afba3 --- /dev/null +++ b/model-armor/snippets/getProjectFloorSettings.js @@ -0,0 +1,54 @@ +// 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 the floor settings for a Google Cloud project. + * + * @param {string} projectId - The ID of the Google Cloud project for which to retrieve + * floor settings. + */ +async function main(projectId) { + // [START modelarmor_get_project_floor_settings] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + + const name = `projects/${projectId}/locations/global/floorSetting`; + + // Imports the Modelarmor library + const {ModelArmorClient} = require('@google-cloud/modelarmor').v1; + + // Instantiates a client + const modelarmorClient = new ModelArmorClient(); + + async function getProjectFloorSettings() { + // Construct request + const request = { + name, + }; + + // Run request + const response = await modelarmorClient.getFloorSetting(request); + console.log(response); + } + + getProjectFloorSettings(); + // [END modelarmor_get_project_floor_settings] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/updateFolderFloorSettings.js b/model-armor/snippets/updateFolderFloorSettings.js new file mode 100644 index 0000000000..46ebb1bfb8 --- /dev/null +++ b/model-armor/snippets/updateFolderFloorSettings.js @@ -0,0 +1,73 @@ +// 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 floor settings of a folder in Model Armor. + * + * @param {string} folderId - Google Cloud folder ID for which floor settings need to be updated. + */ +async function main(folderId) { + // [START modelarmor_update_folder_floor_settings] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const folderId = 'your-folder-id'; + + // 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(); + + async function updateFolderFloorSettings() { + const floorSettingsName = `folders/${folderId}/locations/global/floorSetting`; + + // Build the floor settings 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 floorSetting = { + name: floorSettingsName, + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH, + }, + ], + }, + }, + enableFloorSettingEnforcement: true, + }; + + const request = { + floorSetting: floorSetting, + }; + + const [response] = await client.updateFloorSetting(request); + console.log('Updated folder floor settings', response); + } + + updateFolderFloorSettings(); + // [END modelarmor_update_folder_floor_settings] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/updateOrganizationFloorSettings.js b/model-armor/snippets/updateOrganizationFloorSettings.js new file mode 100644 index 0000000000..1625ed2cd8 --- /dev/null +++ b/model-armor/snippets/updateOrganizationFloorSettings.js @@ -0,0 +1,68 @@ +// 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 floor settings of an organization in Model Armor. + * + * @param {string} organizationId - Google Cloud organization ID for which floor settings need to be updated. + */ +async function main(organizationId) { + // [START modelarmor_update_organization_floor_settings] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const organizationId = 'your-organization-id'; + + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + const client = new ModelArmorClient(); + + const floorSettingsName = `organizations/${organizationId}/locations/global/floorSetting`; + + // Build the floor settings 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 floorSetting = { + name: floorSettingsName, + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH, + }, + ], + }, + }, + enableFloorSettingEnforcement: true, + }; + + const request = { + floorSetting: floorSetting, + }; + + const [response] = await client.updateFloorSetting(request); + console.log('Updated organization floor settings:', response); + + // [END modelarmor_update_organization_floor_settings] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/snippets/updateProjectFloorSettings.js b/model-armor/snippets/updateProjectFloorSettings.js new file mode 100644 index 0000000000..b8787a2a7d --- /dev/null +++ b/model-armor/snippets/updateProjectFloorSettings.js @@ -0,0 +1,67 @@ +// 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 floor settings of a project in Model Armor. + * + * @param {string} projectId - Google Cloud project ID for which floor settings need to be updated. + */ +async function main(projectId) { + // [START modelarmor_update_project_floor_settings] + /** + * TODO(developer): Uncomment these variables before running the sample. + */ + // const projectId = 'your-project-id'; + + const modelarmor = require('@google-cloud/modelarmor'); + const {ModelArmorClient} = modelarmor.v1; + const {protos} = modelarmor; + + const client = new ModelArmorClient(); + + const floorSettingsName = `projects/${projectId}/locations/global/floorSetting`; + + // Build the floor settings 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 floorSetting = { + name: floorSettingsName, + filterConfig: { + raiSettings: { + raiFilters: [ + { + filterType: + protos.google.cloud.modelarmor.v1.RaiFilterType.HATE_SPEECH, + confidenceLevel: + protos.google.cloud.modelarmor.v1.DetectionConfidenceLevel.HIGH, + }, + ], + }, + }, + enableFloorSettingEnforcement: true, + }; + + const request = { + floorSetting: floorSetting, + }; + + const [response] = await client.updateFloorSetting(request); + console.log('Updated project floor settings:', response); + // [END modelarmor_update_project_floor_settings] +} + +const args = process.argv.slice(2); +main(...args).catch(console.error); diff --git a/model-armor/test/modelarmor.test.js b/model-armor/test/modelarmor.test.js index 743f3f1bfe..d5f6447e76 100644 --- a/model-armor/test/modelarmor.test.js +++ b/model-armor/test/modelarmor.test.js @@ -21,6 +21,8 @@ const {ModelArmorClient} = require('@google-cloud/modelarmor').v1; let projectId; const locationId = process.env.GCLOUD_LOCATION || 'us-central1'; +const folderId = process.env.FOLDER_ID; +const organizationId = process.env.ORGANIZATION_ID; const options = { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, }; @@ -180,186 +182,71 @@ describe('Model Armor tests', () => { } }); - // =================== Template Creation Tests =================== - - it('should create a basic template', async () => { - const testTemplateId = `${templateIdPrefix}-basic-create`; + // =================== Floor Settings Tests =================== + it('should get organization floor settings', () => { const output = execSync( - `node snippets/createTemplate.js ${projectId} ${locationId} ${testTemplateId}` - ); - - const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; - templatesToDelete.push(templateName); + `node snippets/getOrganizationFloorSettings.js ${organizationId}` + ).toString(); - assert.match(output, new RegExp(`Created template: ${templateName}`)); + // Check for expected name format in output + const expectedName = `organizations/${organizationId}/locations/global/floorSetting`; + assert.match(output, new RegExp(expectedName.replace(/\//g, '\\/'))); }); - it('should create a template with basic SDP settings', async () => { - const testTemplateId = `${templateIdPrefix}-basic-sdp-1`; - + it('should get folder floor settings', () => { const output = execSync( - `node snippets/createTemplateWithBasicSdp.js ${projectId} ${locationId} ${testTemplateId}` - ); + `node snippets/getFolderFloorSettings.js ${folderId}` + ).toString(); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; - templatesToDelete.push(templateName); - - assert.match(output, new RegExp(`Created template: ${templateName}`)); + // Check for expected name format in output + const expectedName = `folders/${folderId}/locations/global/floorSetting`; + assert.match(output, new RegExp(expectedName.replace(/\//g, '\\/'))); }); - 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}`; - + it('should get project floor settings', () => { const output = execSync( - `node snippets/createTemplateWithAdvancedSdp.js ${projectId} ${locationId} ${testTemplateId} ${fullInspectTemplate} ${fullDeidentifyTemplate}` - ); + `node snippets/getProjectFloorSettings.js ${projectId}` + ).toString(); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; - templatesToDelete.push(templateName); - - assert.match(output, new RegExp(`Created template: ${templateName}`)); + // Check for expected name format in output + const expectedName = `projects/${projectId}/locations/global/floorSetting`; + assert.match(output, new RegExp(expectedName.replace(/\//g, '\\/'))); }); - it('should create a template with metadata', async () => { - const testTemplateId = `${templateIdPrefix}-metadata`; - + it('should update organization floor settings', () => { const output = execSync( - `node snippets/createTemplateWithMetadata.js ${projectId} ${locationId} ${testTemplateId}` - ); + `node snippets/updateOrganizationFloorSettings.js ${organizationId}` + ).toString(); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; - templatesToDelete.push(templateName); + // Check that the update was performed + assert.match(output, /Updated organization floor settings/); - assert.match( - output, - new RegExp(`Created Model Armor Template: ${templateName}`) - ); + // Check that the response contains enableFloorSettingEnforcement=true + assert.match(output, /enableFloorSettingEnforcement:\s*true/); }); - it('should create a template with labels', async () => { - const testTemplateId = `${templateIdPrefix}-labels`; - const labelKey = 'environment'; - const labelValue = 'test'; - + it('should update folder floor settings', () => { const output = execSync( - `node snippets/createTemplateWithLabels.js ${projectId} ${locationId} ${testTemplateId} ${labelKey} ${labelValue}` - ); + `node snippets/updateFolderFloorSettings.js ${folderId}` + ).toString(); - const templateName = `projects/${projectId}/locations/${locationId}/templates/${testTemplateId}`; - templatesToDelete.push(templateName); + // Check that the update was performed + assert.match(output, /Updated folder floor settings/); - assert.match(output, new RegExp(`Created template: ${templateName}`)); + // Check that the response contains enableFloorSettingEnforcement=true + assert.match(output, /enableFloorSettingEnforcement:\s*true/); }); - // =================== Template Management Tests =================== - - it('should get a template', async () => { - const templateToGet = `${templateIdPrefix}-basic-sdp`; - const templateName = `projects/${projectId}/locations/${locationId}/templates/${templateToGet}`; + it('should update project floor settings', () => { const output = execSync( - `node snippets/getTemplate.js ${projectId} ${locationId} ${templateToGet}` - ); + `node snippets/updateProjectFloorSettings.js ${projectId}` + ).toString(); - 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}` - ); + // Check that the update was performed + assert.match(output, /Updated project floor settings/); - 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}`) - ); + // Check that the response contains enableFloorSettingEnforcement=true + assert.match(output, /enableFloorSettingEnforcement:\s*true/); }); }); From d15d0064f352ee727b967c9ca961a4087e43e521 Mon Sep 17 00:00:00 2001 From: rudrakhsha Date: Fri, 28 Mar 2025 16:34:26 +0000 Subject: [PATCH 6/8] Removed crud specific files --- 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 ------------ 13 files changed, 1063 deletions(-) delete mode 100644 model-armor/snippets/createTemplate.js delete mode 100644 model-armor/snippets/createTemplateWithAdvancedSdp.js delete mode 100644 model-armor/snippets/createTemplateWithBasicSdp.js delete mode 100644 model-armor/snippets/createTemplateWithLabels.js delete mode 100644 model-armor/snippets/createTemplateWithMetadata.js delete mode 100644 model-armor/snippets/deleteTemplate.js delete mode 100644 model-armor/snippets/getTemplate.js delete mode 100644 model-armor/snippets/listTemplates.js delete mode 100644 model-armor/snippets/listTemplatesWithFilter.js delete mode 100644 model-armor/snippets/updateTemplate.js delete mode 100644 model-armor/snippets/updateTemplateLabels.js delete mode 100644 model-armor/snippets/updateTemplateMetadata.js delete mode 100644 model-armor/snippets/updateTemplateWithMaskConfiguration.js diff --git a/model-armor/snippets/createTemplate.js b/model-armor/snippets/createTemplate.js deleted file mode 100644 index d971ba8aa1..0000000000 --- a/model-armor/snippets/createTemplate.js +++ /dev/null @@ -1,92 +0,0 @@ -// 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 deleted file mode 100644 index 01974be3ce..0000000000 --- a/model-armor/snippets/createTemplateWithAdvancedSdp.js +++ /dev/null @@ -1,129 +0,0 @@ -// 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 deleted file mode 100644 index a13cd68437..0000000000 --- a/model-armor/snippets/createTemplateWithBasicSdp.js +++ /dev/null @@ -1,99 +0,0 @@ -// 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 deleted file mode 100644 index 8d6c549cca..0000000000 --- a/model-armor/snippets/createTemplateWithLabels.js +++ /dev/null @@ -1,92 +0,0 @@ -// 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 deleted file mode 100644 index 3e07163150..0000000000 --- a/model-armor/snippets/createTemplateWithMetadata.js +++ /dev/null @@ -1,92 +0,0 @@ -// 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 deleted file mode 100644 index e82d58320e..0000000000 --- a/model-armor/snippets/deleteTemplate.js +++ /dev/null @@ -1,56 +0,0 @@ -// 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 deleted file mode 100644 index 28cda68bff..0000000000 --- a/model-armor/snippets/getTemplate.js +++ /dev/null @@ -1,58 +0,0 @@ -// 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 deleted file mode 100644 index 2412cb29ef..0000000000 --- a/model-armor/snippets/listTemplates.js +++ /dev/null @@ -1,58 +0,0 @@ -// 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 deleted file mode 100644 index 7cf4cc469d..0000000000 --- a/model-armor/snippets/listTemplatesWithFilter.js +++ /dev/null @@ -1,61 +0,0 @@ -// 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 deleted file mode 100644 index b894851b49..0000000000 --- a/model-armor/snippets/updateTemplate.js +++ /dev/null @@ -1,82 +0,0 @@ -// 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 deleted file mode 100644 index df0c23f18e..0000000000 --- a/model-armor/snippets/updateTemplateLabels.js +++ /dev/null @@ -1,71 +0,0 @@ -// 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 deleted file mode 100644 index 4148700949..0000000000 --- a/model-armor/snippets/updateTemplateMetadata.js +++ /dev/null @@ -1,83 +0,0 @@ -// 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 deleted file mode 100644 index 6c0aed2eee..0000000000 --- a/model-armor/snippets/updateTemplateWithMaskConfiguration.js +++ /dev/null @@ -1,90 +0,0 @@ -// 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); From 313bd645073862dfa5d0e10450736656d23b90ae Mon Sep 17 00:00:00 2001 From: rudrakhsha-crest Date: Fri, 18 Apr 2025 12:46:57 +0000 Subject: [PATCH 7/8] Updated test to disable floor settings in the after code --- model-armor/test/modelarmor.test.js | 69 ++++++++++++++++++++++++++++- 1 file changed, 68 insertions(+), 1 deletion(-) diff --git a/model-armor/test/modelarmor.test.js b/model-armor/test/modelarmor.test.js index d5f6447e76..a4a2ae29ba 100644 --- a/model-armor/test/modelarmor.test.js +++ b/model-armor/test/modelarmor.test.js @@ -75,6 +75,70 @@ async function deleteTemplate(templateName) { } } +async function disableFloorSettings() { + try { + // Disable project floor settings + const [projectFloorSettings] = await client.getFloorSetting({ + name: `projects/${projectId}/locations/global/floorSetting`, + }); + + if (projectFloorSettings.enableFloorSettingEnforcement) { + const [updatedProjectSettings] = await client.updateFloorSetting({ + floorSetting: { + name: `projects/${projectId}/locations/global/floorSetting`, + enableFloorSettingEnforcement: false, + }, + updateMask: { + paths: ['enable_floor_setting_enforcement'], + }, + }); + console.log('Disabled project floor settings:', updatedProjectSettings.name); + } + + // Disable folder floor settings if folderId is available + if (folderId) { + const [folderFloorSettings] = await client.getFloorSetting({ + name: `folders/${folderId}/locations/global/floorSetting`, + }); + + if (folderFloorSettings.enableFloorSettingEnforcement) { + const [updatedFolderSettings] = await client.updateFloorSetting({ + floorSetting: { + name: `folders/${folderId}/locations/global/floorSetting`, + enableFloorSettingEnforcement: false, + }, + updateMask: { + paths: ['enable_floor_setting_enforcement'], + }, + }); + console.log('Disabled folder floor settings:', updatedFolderSettings.name); + } + } + + // Disable organization floor settings if organizationId is available + if (organizationId) { + const [orgFloorSettings] = await client.getFloorSetting({ + name: `organizations/${organizationId}/locations/global/floorSetting`, + }); + + if (orgFloorSettings.enableFloorSettingEnforcement) { + const [updatedOrgSettings] = await client.updateFloorSetting({ + floorSetting: { + name: `organizations/${organizationId}/locations/global/floorSetting`, + enableFloorSettingEnforcement: false, + }, + updateMask: { + paths: ['enable_floor_setting_enforcement'], + }, + }); + console.log('Disabled organization floor settings:', updatedOrgSettings.name); + } + } + } catch (error) { + console.error('Error disabling floor settings:', error); + } +} + describe('Model Armor tests', () => { const templatesToDelete = []; @@ -164,6 +228,9 @@ describe('Model Armor tests', () => { }); after(async () => { + // Disable floor settings to restore original state + await disableFloorSettings(); + // Clean up all templates const directTemplates = [emptyTemplateId, basicTemplateId]; for (const templateId of directTemplates) { @@ -249,4 +316,4 @@ describe('Model Armor tests', () => { // Check that the response contains enableFloorSettingEnforcement=true assert.match(output, /enableFloorSettingEnforcement:\s*true/); }); -}); +}); \ No newline at end of file From 8bd485468ed086b7c6a9ccb0563955548ad3a46f Mon Sep 17 00:00:00 2001 From: rudrakhsha-crest Date: Mon, 21 Apr 2025 06:38:04 +0000 Subject: [PATCH 8/8] Updated variable names in tests for org id and folder id --- model-armor/test/modelarmor.test.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/model-armor/test/modelarmor.test.js b/model-armor/test/modelarmor.test.js index a4a2ae29ba..a3574fcfe4 100644 --- a/model-armor/test/modelarmor.test.js +++ b/model-armor/test/modelarmor.test.js @@ -21,8 +21,8 @@ const {ModelArmorClient} = require('@google-cloud/modelarmor').v1; let projectId; const locationId = process.env.GCLOUD_LOCATION || 'us-central1'; -const folderId = process.env.FOLDER_ID; -const organizationId = process.env.ORGANIZATION_ID; +const folderId = process.env.MA_FOLDER_ID; +const organizationId = process.env.MA_ORG_ID; const options = { apiEndpoint: `modelarmor.${locationId}.rep.googleapis.com`, };