From d0b6026696ba872c905e2d82fb54b8f801bd5f69 Mon Sep 17 00:00:00 2001 From: tirthrajsinh-zala-crest Date: Tue, 8 Apr 2025 15:17:40 +0530 Subject: [PATCH 01/12] feat(modelarmor): Added samples for creating, listing, updating and deleting model armor templates --- modelarmor/create_template.go | 105 ++++ .../create_template_with_advanced_sdp.go | 130 +++++ modelarmor/create_template_with_basic_sdp.go | 127 +++++ modelarmor/create_template_with_labels.go | 119 +++++ modelarmor/create_template_with_metadata.go | 125 +++++ modelarmor/delete_template.go | 84 ++++ modelarmor/get_template.go | 88 ++++ modelarmor/go.mod | 56 +++ modelarmor/go.sum | 123 +++++ modelarmor/list_templates.go | 96 ++++ modelarmor/list_templates_with_filter.go | 101 ++++ modelarmor/modelarmor_test.go | 457 ++++++++++++++++++ modelarmor/testdata/env/test.env | 2 + modelarmor/update_template.go | 104 ++++ modelarmor/update_template_labels.go | 106 ++++ modelarmor/update_template_metadata.go | 133 +++++ ...update_template_with_mask_configuration.go | 136 ++++++ 17 files changed, 2092 insertions(+) create mode 100644 modelarmor/create_template.go create mode 100644 modelarmor/create_template_with_advanced_sdp.go create mode 100644 modelarmor/create_template_with_basic_sdp.go create mode 100644 modelarmor/create_template_with_labels.go create mode 100644 modelarmor/create_template_with_metadata.go create mode 100644 modelarmor/delete_template.go create mode 100644 modelarmor/get_template.go create mode 100644 modelarmor/go.mod create mode 100644 modelarmor/go.sum create mode 100644 modelarmor/list_templates.go create mode 100644 modelarmor/list_templates_with_filter.go create mode 100644 modelarmor/modelarmor_test.go create mode 100644 modelarmor/testdata/env/test.env create mode 100644 modelarmor/update_template.go create mode 100644 modelarmor/update_template_labels.go create mode 100644 modelarmor/update_template_metadata.go create mode 100644 modelarmor/update_template_with_mask_configuration.go diff --git a/modelarmor/create_template.go b/modelarmor/create_template.go new file mode 100644 index 0000000000..6e56a94d6a --- /dev/null +++ b/modelarmor/create_template.go @@ -0,0 +1,105 @@ +// 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. + +// Sample code for creating a new model armor template. + +package modelarmor + +// [START modelarmor_create_template] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" +) + +// createModelArmorTemplate creates a new Model Armor template. +// +// This method creates a new Model Armor template with the provided settings. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the Google Cloud project. +// locationID string: The ID of the Google Cloud location. +// templateID string: The ID of the template to create. +// +// Returns: +// +// *modelarmorpb.Template: The created template. +// error: Any error that occurred during template creation. +// +// Example: +// +// template, err := createModelArmorTemplate( +// os.Stdout, +// "my-project", +// "us-central1", +// "my-template", +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(template) +func createModelArmorTemplate(w io.Writer, projectID, location, templateID string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) + template := &modelarmorpb.Template{ + FilterConfig: &modelarmorpb.FilterConfig{ + PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{ + FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, + }, + MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{ + FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED, + }, + }, + } + + // Prepare the request for creating the template. + req := &modelarmorpb.CreateTemplateRequest{ + Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location), + TemplateId: templateID, + Template: template, + } + + // Create the template. + response, err := client.CreateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to create template: %v", err) + } + + // Print the new template name using fmt.Fprintf with the io.Writer. + fmt.Fprintf(w, "Created template: %s\n", response.Name) + + // [END modelarmor_create_template] + + return response, nil +} diff --git a/modelarmor/create_template_with_advanced_sdp.go b/modelarmor/create_template_with_advanced_sdp.go new file mode 100644 index 0000000000..9ef7de847e --- /dev/null +++ b/modelarmor/create_template_with_advanced_sdp.go @@ -0,0 +1,130 @@ +// 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. + +// Sample code for creating a new model armor template with advanced SDP settings enabled. + +package modelarmor + +// [START modelarmor_create_template_with_advanced_sdp] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" +) + +// createModelArmorTemplateWithAdvancedSDP creates a new Model Armor template with advanced SDP settings. +// +// This method creates a new Model Armor template with advanced SDP settings, including inspect and deidentify templates. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the Google Cloud project. +// locationID string: The ID of the Google Cloud location. +// templateID string: The ID of the template to create. +// inspectTemplate string: The ID of the inspect template to use. +// deidentifyTemplate string: The ID of the deidentify template to use. +// +// Returns: +// +// *modelarmorpb.Template: The created template. +// error: Any error that occurred during template creation. +// +// Example: +// +// template, err := createModelArmorTemplateWithAdvancedSDP( +// os.Stdout, +// "my-project", +// "us-central1", +// "my-template", +// "my-inspect-template", +// "my-deidentify-template", +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(template) +func createModelArmorTemplateWithAdvancedSDP(w io.Writer, projectID, locationID, templateID, inspectTemplate, deidentifyTemplate string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) + + // Build the Model Armor template with your preferred filters. + template := &modelarmorpb.Template{ + FilterConfig: &modelarmorpb.FilterConfig{ + RaiSettings: &modelarmorpb.RaiFilterSettings{ + RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ + { + FilterType: modelarmorpb.RaiFilterType_DANGEROUS, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_HARASSMENT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, + }, + { + FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + }, + }, + SdpSettings: &modelarmorpb.SdpFilterSettings{ + SdpConfiguration: &modelarmorpb.SdpFilterSettings_AdvancedConfig{ + AdvancedConfig: &modelarmorpb.SdpAdvancedConfig{ + InspectTemplate: inspectTemplate, + DeidentifyTemplate: deidentifyTemplate, + }, + }, + }, + }, + } + + // Prepare the request for creating the template. + req := &modelarmorpb.CreateTemplateRequest{ + Parent: parent, + TemplateId: templateID, + Template: template, + } + + // Create the template. + response, err := client.CreateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to create template: %v", err) + } + + // Print the new template name using fmt.Fprint with the io.Writer. + fmt.Fprintf(w, "Created Template with advanced SDP: %s\n", response.Name) + + // [END modelarmor_create_template_with_advanced_sdp] + + return response, nil +} diff --git a/modelarmor/create_template_with_basic_sdp.go b/modelarmor/create_template_with_basic_sdp.go new file mode 100644 index 0000000000..d1dfb9f365 --- /dev/null +++ b/modelarmor/create_template_with_basic_sdp.go @@ -0,0 +1,127 @@ +// 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. + +// Sample code for creating a new model armor template with basic SDP settings enabled. + +package modelarmor + +// [START modelarmor_create_template_with_basic_sdp] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" +) + +// createModelArmorTemplateWithBasicSDP creates a new Model Armor template with basic SDP settings. +// +// This method creates a new Model Armor template with basic SDP settings. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the Google Cloud project. +// locationID string: The ID of the Google Cloud location. +// templateID string: The ID of the template to create. +// +// Returns: +// +// *modelarmorpb.Template: The created template. +// error: Any error that occurred during template creation. +// +// Example: +// +// template, err := createModelArmorTemplateWithBasicSDP( +// os.Stdout, +// "my-project", +// "us-central1", +// "my-template", +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(template) +func createModelArmorTemplateWithBasicSDP(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) + + // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) + template := &modelarmorpb.Template{ + FilterConfig: &modelarmorpb.FilterConfig{ + RaiSettings: &modelarmorpb.RaiFilterSettings{ + RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ + { + FilterType: modelarmorpb.RaiFilterType_DANGEROUS, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_HARASSMENT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, + }, + { + FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + }, + }, + SdpSettings: &modelarmorpb.SdpFilterSettings{ + SdpConfiguration: &modelarmorpb.SdpFilterSettings_BasicConfig{ + BasicConfig: &modelarmorpb.SdpBasicConfig{ + FilterEnforcement: modelarmorpb.SdpBasicConfig_ENABLED, + }, + }, + }, + }, + } + + // Prepare the request for creating the template. + req := &modelarmorpb.CreateTemplateRequest{ + Parent: parent, + TemplateId: templateID, + Template: template, + } + + // Create the template. + response, err := client.CreateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to create template: %v", err) + } + + // Print the new template name using fmt.Fprintf with the io.Writer. + fmt.Fprintf(w, "Created Template with basic SDP: %s\n", response.Name) + + // [END modelarmor_create_template_with_basic_sdp] + + return response, nil +} diff --git a/modelarmor/create_template_with_labels.go b/modelarmor/create_template_with_labels.go new file mode 100644 index 0000000000..dc2c56df00 --- /dev/null +++ b/modelarmor/create_template_with_labels.go @@ -0,0 +1,119 @@ +// 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. + +// Sample code for creating a new model armor template with labels. + +package modelarmor + +// [START modelarmor_create_template_with_labels] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" +) + +// createModelArmorTemplateWithLabels creates a new Model Armor template with custom labels. +// +// This method creates a new Model Armor template with custom labels. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the Google Cloud project. +// locationID string: The ID of the Google Cloud location. +// templateID string: The ID of the template to create. +// labels map[string]string: A map of custom labels to apply to the template. +// +// Returns: +// +// *modelarmorpb.Template: The created template. +// error: Any error that occurred during template creation. +// +// Example: +// +// labels := map[string]string{ +// "env": "dev", +// "team": "security", +// } +// template, err := createModelArmorTemplateWithLabels( +// os.Stdout, +// "my-project", +// "us-central1", +// "my-template", +// labels, +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(template) +func createModelArmorTemplateWithLabels(w io.Writer, projectID, locationID, templateID string, labels map[string]string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) + + // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) + template := &modelarmorpb.Template{ + FilterConfig: &modelarmorpb.FilterConfig{ + RaiSettings: &modelarmorpb.RaiFilterSettings{ + RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ + { + FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, + }, + }, + }, + }, + Labels: labels, + } + + // Prepare the request for creating the template. + req := &modelarmorpb.CreateTemplateRequest{ + Parent: parent, + TemplateId: templateID, + Template: template, + } + + // Create the template. + response, err := client.CreateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to create template: %v", err) + } + + // Print the new template name using fmt.Fprintf with the io.Writer. + fmt.Fprintf(w, "Created Template with labels: %s\n", response.Name) + + // [END modelarmor_create_template_with_labels] + + return response, nil +} diff --git a/modelarmor/create_template_with_metadata.go b/modelarmor/create_template_with_metadata.go new file mode 100644 index 0000000000..196b438ac9 --- /dev/null +++ b/modelarmor/create_template_with_metadata.go @@ -0,0 +1,125 @@ +// 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. + +// Sample code for creating a new model armor template with template metadata. + +package modelarmor + +// [START modelarmor_create_template_with_metadata] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" +) + +// createModelArmorTemplateWithMetadata creates a new Model Armor template with template metadata. +// +// This method creates a new Model Armor template with template metadata. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the Google Cloud project. +// locationID string: The ID of the Google Cloud location. +// templateID string: The ID of the template to create. +// metadata *modelarmorpb.TemplateMetadata: The template metadata to apply. +// +// Returns: +// +// *modelarmorpb.Template: The created template. +// error: Any error that occurred during template creation. +// +// Example: +// +// metadata := &modelarmorpb.TemplateMetadata{ +// Description: "My template", +// Version: "1.0", +// } +// template, err := createModelArmorTemplateWithMetadata( +// os.Stdout, +// "my-project", +// "us-central1", +// "my-template", +// metadata, +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(template) +func createModelArmorTemplateWithMetadata(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) + + // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) + template := &modelarmorpb.Template{ + FilterConfig: &modelarmorpb.FilterConfig{ + RaiSettings: &modelarmorpb.RaiFilterSettings{ + RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ + { + FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, + }, + }, + }, + }, + // 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](https://cloud.google.com/security-command-center/docs/reference/model-armor/rest/v1/projects.locations.templates#templatemetadata) + TemplateMetadata: &modelarmorpb.Template_TemplateMetadata{ + IgnorePartialInvocationFailures: true, + LogSanitizeOperations: true, + }, + } + + // Prepare the request for creating the template. + req := &modelarmorpb.CreateTemplateRequest{ + Parent: parent, + TemplateId: templateID, + Template: template, + } + + // Create the template. + response, err := client.CreateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to create template: %v", err) + } + + // Print the new template name using fmt.Fprintf with the io.Writer. + fmt.Fprintf(w, "Created Model Armor Template: %s\n", response.Name) + + // [END modelarmor_create_template_with_metadata] + + return response, nil +} diff --git a/modelarmor/delete_template.go b/modelarmor/delete_template.go new file mode 100644 index 0000000000..d23bef5fad --- /dev/null +++ b/modelarmor/delete_template.go @@ -0,0 +1,84 @@ +// 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. + +// Sample code for deleting a model armor template. + +package modelarmor + +// [START modelarmor_delete_template] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" +) + +// deleteModelArmorTemplate deletes a Model Armor template. +// +// This method deletes a Model Armor template with the provided ID. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the Google Cloud project. +// locationID string: The ID of the Google Cloud location. +// templateID string: The ID of the template to delete. +// +// Returns: +// +// error: Any error that occurred during template deletion. +// +// Example: +// +// err := deleteModelArmorTemplate( +// os.Stdout, +// "my-project", +// "us-central1", +// "my-template", +// ) +// if err != nil { +// log.Fatal(err) +// } +func deleteModelArmorTemplate(w io.Writer, projectID, location, templateID string) error { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), + ) + if err != nil { + return fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + // Build the request for deleting the template. + req := &modelarmorpb.DeleteTemplateRequest{ + Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, location, templateID), + } + + // Delete the template. + if err := client.DeleteTemplate(ctx, req); err != nil { + return fmt.Errorf("failed to delete template: %v", err) + } + + // Print the success message using fmt.Fprintf with the io.Writer. + fmt.Fprintf(w, "Successfully deleted Model Armor template: %s\n", req.Name) + // [END modelarmor_delete_template] + + return nil +} diff --git a/modelarmor/get_template.go b/modelarmor/get_template.go new file mode 100644 index 0000000000..e8ab646780 --- /dev/null +++ b/modelarmor/get_template.go @@ -0,0 +1,88 @@ +// 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. + +// Sample code for getting a model armor template. + +package modelarmor + +// [START modelarmor_get_template] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" +) + +// getModelArmorTemplate gets a Model Armor template. +// +// This method retrieves a Model Armor template. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the project. +// location string: The location of the template. +// templateID string: The ID of the template. +// +// Returns: +// +// *modelarmorpb.Template: The retrieved Model Armor template. +// error: Any error that occurred during retrieval. +// +// Example: +// +// template, err := getModelArmorTemplate( +// os.Stdout, +// "my-project", +// "my-location", +// "my-template", +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(template) +func getModelArmorTemplate(w io.Writer, projectID, location, templateID string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + // Initialize request arguments. + req := &modelarmorpb.GetTemplateRequest{ + Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, location, templateID), + } + + // Get the template. + response, err := client.GetTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to get template: %v", err) + } + + // Print the template name using fmt.Fprintf with the io.Writer. + fmt.Fprintf(w, "Retrieved template: %s\n", response.Name) + + // [END modelarmor_get_template] + + return response, nil +} diff --git a/modelarmor/go.mod b/modelarmor/go.mod new file mode 100644 index 0000000000..efc441148c --- /dev/null +++ b/modelarmor/go.mod @@ -0,0 +1,56 @@ +module github.com/GoogleCloudPlatform/golang-samples/modelarmor + +go 1.23.0 + +require ( + cloud.google.com/go/modelarmor v0.1.0 + github.com/GoogleCloudPlatform/golang-samples v0.0.0-20250404170905-0aca11152736 + github.com/google/uuid v1.6.0 + google.golang.org/api v0.226.0 + google.golang.org/grpc v1.71.0 + google.golang.org/protobuf v1.36.5 +) + +require ( + cel.dev/expr v0.19.1 // indirect + cloud.google.com/go v0.118.3 // indirect + cloud.google.com/go/auth v0.15.0 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.7 // indirect + cloud.google.com/go/compute/metadata v0.6.0 // indirect + cloud.google.com/go/iam v1.4.0 // indirect + cloud.google.com/go/monitoring v1.24.0 // indirect + cloud.google.com/go/storage v1.50.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.25.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.49.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.49.0 // indirect + github.com/cespare/xxhash/v2 v2.3.0 // indirect + github.com/cncf/xds/go v0.0.0-20250121191232-2f005788dc42 // indirect + github.com/envoyproxy/go-control-plane/envoy v1.32.4 // indirect + github.com/envoyproxy/protoc-gen-validate v1.2.1 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/go-logr/logr v1.4.2 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/google/s2a-go v0.1.9 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.5 // indirect + github.com/googleapis/gax-go/v2 v2.14.1 // indirect + github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect + go.opentelemetry.io/auto/sdk v1.1.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.34.0 // indirect + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 // indirect + go.opentelemetry.io/otel v1.34.0 // indirect + go.opentelemetry.io/otel/metric v1.34.0 // indirect + go.opentelemetry.io/otel/sdk v1.34.0 // indirect + go.opentelemetry.io/otel/sdk/metric v1.34.0 // indirect + go.opentelemetry.io/otel/trace v1.34.0 // indirect + golang.org/x/crypto v0.36.0 // indirect + golang.org/x/net v0.37.0 // indirect + golang.org/x/oauth2 v0.28.0 // indirect + golang.org/x/sync v0.12.0 // indirect + golang.org/x/sys v0.31.0 // indirect + golang.org/x/text v0.23.0 // indirect + golang.org/x/time v0.11.0 // indirect + google.golang.org/genproto v0.0.0-20250313205543-e70fdf4c4cb4 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20250313205543-e70fdf4c4cb4 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb // indirect +) diff --git a/modelarmor/go.sum b/modelarmor/go.sum new file mode 100644 index 0000000000..9fc4a07037 --- /dev/null +++ b/modelarmor/go.sum @@ -0,0 +1,123 @@ +cel.dev/expr v0.19.1 h1:NciYrtDRIR0lNCnH1LFJegdjspNx9fI59O7TWcua/W4= +cel.dev/expr v0.19.1/go.mod h1:MrpN08Q+lEBs+bGYdLxxHkZoUSsCp0nSKTs0nTymJgw= +cloud.google.com/go v0.118.3 h1:jsypSnrE/w4mJysioGdMBg4MiW/hHx/sArFpaBWHdME= +cloud.google.com/go v0.118.3/go.mod h1:Lhs3YLnBlwJ4KA6nuObNMZ/fCbOQBPuWKPoE0Wa/9Vc= +cloud.google.com/go/auth v0.15.0 h1:Ly0u4aA5vG/fsSsxu98qCQBemXtAtJf+95z9HK+cxps= +cloud.google.com/go/auth v0.15.0/go.mod h1:WJDGqZ1o9E9wKIL+IwStfyn/+s59zl4Bi+1KQNVXLZ8= +cloud.google.com/go/auth/oauth2adapt v0.2.7 h1:/Lc7xODdqcEw8IrZ9SvwnlLX6j9FHQM74z6cBk9Rw6M= +cloud.google.com/go/auth/oauth2adapt v0.2.7/go.mod h1:NTbTTzfvPl1Y3V1nPpOgl2w6d/FjO7NNUQaWSox6ZMc= +cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= +cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= +cloud.google.com/go/iam v1.4.0 h1:ZNfy/TYfn2uh/ukvhp783WhnbVluqf/tzOaqVUPlIPA= +cloud.google.com/go/iam v1.4.0/go.mod h1:gMBgqPaERlriaOV0CUl//XUzDhSfXevn4OEUbg6VRs4= +cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= +cloud.google.com/go/logging v1.13.0/go.mod h1:36CoKh6KA/M0PbhPKMq6/qety2DCAErbhXT62TuXALA= +cloud.google.com/go/longrunning v0.6.4 h1:3tyw9rO3E2XVXzSApn1gyEEnH2K9SynNQjMlBi3uHLg= +cloud.google.com/go/longrunning v0.6.4/go.mod h1:ttZpLCe6e7EXvn9OxpBRx7kZEB0efv8yBO6YnVMfhJs= +cloud.google.com/go/modelarmor v0.1.0 h1:iiq7y+aPUAitUv3DgzQ8Xz22Byznm3Z5/SZryafyGUg= +cloud.google.com/go/modelarmor v0.1.0/go.mod h1:2uB1YjphtsdN3jjNZRYVdzKFVj2zcVXtYOIlp7OlkIs= +cloud.google.com/go/monitoring v1.24.0 h1:csSKiCJ+WVRgNkRzzz3BPoGjFhjPY23ZTcaenToJxMM= +cloud.google.com/go/monitoring v1.24.0/go.mod h1:Bd1PRK5bmQBQNnuGwHBfUamAV1ys9049oEPHnn4pcsc= +cloud.google.com/go/storage v1.50.0 h1:3TbVkzTooBvnZsk7WaAQfOsNrdoM8QHusXA1cpk6QJs= +cloud.google.com/go/storage v1.50.0/go.mod h1:l7XeiD//vx5lfqE3RavfmU9yvk5Pp0Zhcv482poyafY= +cloud.google.com/go/trace v1.11.3 h1:c+I4YFjxRQjvAhRmSsmjpASUKq88chOX854ied0K/pE= +cloud.google.com/go/trace v1.11.3/go.mod h1:pt7zCYiDSQjC9Y2oqCsh9jF4GStB/hmjrYLsxRR27q8= +github.com/GoogleCloudPlatform/golang-samples v0.0.0-20250404170905-0aca11152736 h1:hILvef57YioyME1mqLE3l683Ts79+k3PSjEiooHfmLw= +github.com/GoogleCloudPlatform/golang-samples v0.0.0-20250404170905-0aca11152736/go.mod h1:pro/7J5Dd9+sI+NAZUopa1sW4YuthozUkor+3MF6fIU= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.25.0 h1:3c8yed4lgqTt+oTQ+JNMDo+F4xprBf+O/il4ZC0nRLw= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.25.0/go.mod h1:obipzmGjfSjam60XLwGfqUkJsfiheAl+TUjG+4yzyPM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.49.0 h1:o90wcURuxekmXrtxmYWTyNla0+ZEHhud6DI1ZTxd1vI= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.49.0/go.mod h1:6fTWu4m3jocfUZLYF5KsZC1TUfRvEjs7lM4crme/irw= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.49.0 h1:jJKWl98inONJAr/IZrdFQUWcwUO95DLY1XMD1ZIut+g= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.49.0/go.mod h1:l2fIqmwB+FKSfvn3bAD/0i+AXAxhIZjTK2svT/mgUXs= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.49.0 h1:GYUJLfvd++4DMuMhCFLgLXvFwofIxh/qOwoGuS/LTew= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.49.0/go.mod h1:wRbFgBQUVm1YXrvWKofAEmq9HNJTDphbAaJSSX01KUI= +github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs= +github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/cncf/xds/go v0.0.0-20250121191232-2f005788dc42 h1:Om6kYQYDUk5wWbT0t0q6pvyM49i9XZAv9dDrkDA7gjk= +github.com/cncf/xds/go v0.0.0-20250121191232-2f005788dc42/go.mod h1:W+zGtBO5Y1IgJhy4+A9GOqVhqLpfZi+vwmdNXUehLA8= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/envoyproxy/go-control-plane v0.13.4 h1:zEqyPVyku6IvWCFwux4x9RxkLOMUL+1vC9xUFv5l2/M= +github.com/envoyproxy/go-control-plane v0.13.4/go.mod h1:kDfuBlDVsSj2MjrLEtRWtHlsWIFcGyB2RMO44Dc5GZA= +github.com/envoyproxy/go-control-plane/envoy v1.32.4 h1:jb83lalDRZSpPWW2Z7Mck/8kXZ5CQAFYVjQcdVIr83A= +github.com/envoyproxy/go-control-plane/envoy v1.32.4/go.mod h1:Gzjc5k8JcJswLjAx1Zm+wSYE20UrLtt7JZMWiWQXQEw= +github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= +github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= +github.com/envoyproxy/protoc-gen-validate v1.2.1 h1:DEo3O99U8j4hBFwbJfrz9VtgcDfUKS7KJ7spH3d86P8= +github.com/envoyproxy/protoc-gen-validate v1.2.1/go.mod h1:d/C80l/jxXLdfEIhX1W2TmLfsJ31lvEjwamM4DxlWXU= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.2 h1:6pFjapn8bFcIbiKo3XT4j/BhANplGihG6tvd+8rYgrY= +github.com/go-logr/logr v1.4.2/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= +github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= +github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= +github.com/google/martian/v3 v3.3.3/go.mod h1:iEPrYcgCF7jA9OtScMFQyAlZZ4YXTKEtJ1E6RWzmBA0= +github.com/google/s2a-go v0.1.9 h1:LGD7gtMgezd8a/Xak7mEWL0PjoTQFvpRudN895yqKW0= +github.com/google/s2a-go v0.1.9/go.mod h1:YA0Ei2ZQL3acow2O62kdp9UlnvMmU7kA6Eutn0dXayM= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.3.5 h1:VgzTY2jogw3xt39CusEnFJWm7rlsq5yL5q9XdLOuP5g= +github.com/googleapis/enterprise-certificate-proxy v0.3.5/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= +github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= +github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= +github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= +github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA= +go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A= +go.opentelemetry.io/contrib/detectors/gcp v1.34.0 h1:JRxssobiPg23otYU5SbWtQC//snGVIM3Tx6QRzlQBao= +go.opentelemetry.io/contrib/detectors/gcp v1.34.0/go.mod h1:cV4BMFcscUR/ckqLkbfQmF0PRsq8w/lMGzdbCSveBHo= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0 h1:rgMkmiGfix9vFJDcDi1PK8WEQP4FLQwLDfhp5ZLpFeE= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.59.0/go.mod h1:ijPqXp5P6IRRByFVVg9DY8P5HkxkHE5ARIa+86aXPf4= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0 h1:CV7UdSGJt/Ao6Gp4CXckLxVRRsRgDHoI8XjbL3PDl8s= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.59.0/go.mod h1:FRmFuRJfag1IZ2dPkHnEoSFVgTVPUd2qf5Vi69hLb8I= +go.opentelemetry.io/otel v1.34.0 h1:zRLXxLCgL1WyKsPVrgbSdMN4c0FMkDAskSTQP+0hdUY= +go.opentelemetry.io/otel v1.34.0/go.mod h1:OWFPOQ+h4G8xpyjgqo4SxJYdDQ/qmRH+wivy7zzx9oI= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0 h1:WDdP9acbMYjbKIyJUhTvtzj601sVJOqgWdUxSdR/Ysc= +go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.29.0/go.mod h1:BLbf7zbNIONBLPwvFnwNHGj4zge8uTCM/UPIVW1Mq2I= +go.opentelemetry.io/otel/metric v1.34.0 h1:+eTR3U0MyfWjRDhmFMxe2SsW64QrZ84AOhvqS7Y+PoQ= +go.opentelemetry.io/otel/metric v1.34.0/go.mod h1:CEDrp0fy2D0MvkXE+dPV7cMi8tWZwX3dmaIhwPOaqHE= +go.opentelemetry.io/otel/sdk v1.34.0 h1:95zS4k/2GOy069d321O8jWgYsW3MzVV+KuSPKp7Wr1A= +go.opentelemetry.io/otel/sdk v1.34.0/go.mod h1:0e/pNiaMAqaykJGKbi+tSjWfNNHMTxoC9qANsCzbyxU= +go.opentelemetry.io/otel/sdk/metric v1.34.0 h1:5CeK9ujjbFVL5c1PhLuStg1wxA7vQv7ce1EK0Gyvahk= +go.opentelemetry.io/otel/sdk/metric v1.34.0/go.mod h1:jQ/r8Ze28zRKoNRdkjCZxfs6YvBTG1+YIqyFVFYec5w= +go.opentelemetry.io/otel/trace v1.34.0 h1:+ouXS2V8Rd4hp4580a8q23bg0azF2nI8cqLYnC8mh/k= +go.opentelemetry.io/otel/trace v1.34.0/go.mod h1:Svm7lSjQD7kG7KJ/MUHPVXSDGz2OX4h0M2jHBhmSfRE= +golang.org/x/crypto v0.36.0 h1:AnAEvhDddvBdpY+uR+MyHmuZzzNqXSe/GvuDeob5L34= +golang.org/x/crypto v0.36.0/go.mod h1:Y4J0ReaxCR1IMaabaSMugxJES1EpwhBHhv2bDHklZvc= +golang.org/x/net v0.37.0 h1:1zLorHbz+LYj7MQlSf1+2tPIIgibq2eL5xkrGk6f+2c= +golang.org/x/net v0.37.0/go.mod h1:ivrbrMbzFq5J41QOQh0siUuly180yBYtLp+CKbEaFx8= +golang.org/x/oauth2 v0.28.0 h1:CrgCKl8PPAVtLnU3c+EDw6x11699EWlsDeWNWKdIOkc= +golang.org/x/oauth2 v0.28.0/go.mod h1:onh5ek6nERTohokkhCD/y2cV4Do3fxFHFuAejCkRWT8= +golang.org/x/sync v0.12.0 h1:MHc5BpPuC30uJk597Ri8TV3CNZcTLu6B6z4lJy+g6Jw= +golang.org/x/sync v0.12.0/go.mod h1:1dzgHSNfp02xaA81J2MS99Qcpr2w7fw1gpm99rleRqA= +golang.org/x/sys v0.31.0 h1:ioabZlmFYtWhL+TRYpcnNlLwhyxaM9kWTDEmfnprqik= +golang.org/x/sys v0.31.0/go.mod h1:BJP2sWEmIv4KK5OTEluFJCKSidICx8ciO85XgH3Ak8k= +golang.org/x/text v0.23.0 h1:D71I7dUrlY+VX0gQShAThNGHFxZ13dGLBHQLVl1mJlY= +golang.org/x/text v0.23.0/go.mod h1:/BLNzu4aZCJ1+kcD0DNRotWKage4q2rGVAg4o22unh4= +golang.org/x/time v0.11.0 h1:/bpjEDfN9tkoN/ryeYHnv5hcMlc8ncjMcM4XBk5NWV0= +golang.org/x/time v0.11.0/go.mod h1:CDIdPxbZBQxdj6cxyCIdrNogrJKMJ7pr37NYpMcMDSg= +google.golang.org/api v0.226.0 h1:9A29y1XUD+YRXfnHkO66KggxHBZWg9LsTGqm7TkUvtQ= +google.golang.org/api v0.226.0/go.mod h1:WP/0Xm4LVvMOCldfvOISnWquSRWbG2kArDZcg+W2DbY= +google.golang.org/genproto v0.0.0-20250313205543-e70fdf4c4cb4 h1:kCjWYliqPA8g5z87mbjnf/cdgQqMzBfp9xYre5qKu2A= +google.golang.org/genproto v0.0.0-20250313205543-e70fdf4c4cb4/go.mod h1:SqIx1NV9hcvqdLHo7uNZDS5lrUJybQ3evo3+z/WBfA0= +google.golang.org/genproto/googleapis/api v0.0.0-20250313205543-e70fdf4c4cb4 h1:IFnXJq3UPB3oBREOodn1v1aGQeZYQclEmvWRMN0PSsY= +google.golang.org/genproto/googleapis/api v0.0.0-20250313205543-e70fdf4c4cb4/go.mod h1:c8q6Z6OCqnfVIqUFJkCzKcrj8eCvUrz+K4KRzSTuANg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb h1:TLPQVbx1GJ8VKZxz52VAxl1EBgKXXbTiU9Fc5fZeLn4= +google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb/go.mod h1:LuRYeWDFV6WOn90g357N17oMCaxpgCnbi/44qJvDn2I= +google.golang.org/grpc v1.71.0 h1:kF77BGdPTQ4/JZWMlb9VpJ5pa25aqvVqogsxNHHdeBg= +google.golang.org/grpc v1.71.0/go.mod h1:H0GRtasmQOh9LkFoCPDu3ZrwUtD1YGE+b2vYBYd/8Ec= +google.golang.org/protobuf v1.36.5 h1:tPhr+woSbjfYvY6/GPufUoYizxw1cF/yFoxJ2fmpwlM= +google.golang.org/protobuf v1.36.5/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/modelarmor/list_templates.go b/modelarmor/list_templates.go new file mode 100644 index 0000000000..81db6c5d84 --- /dev/null +++ b/modelarmor/list_templates.go @@ -0,0 +1,96 @@ +// 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](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. + +// Sample code for getting list of model armor templates. + +package modelarmor + +// [START modelarmor_list_templates] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/iterator" + "google.golang.org/api/option" +) + +// listModelArmorTemplates lists Model Armor templates. +// +// This method lists Model Armor templates for a project and location. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the project. +// location string: The location of the templates. +// +// Returns: +// +// []*modelarmorpb.Template: A list of Model Armor templates. +// error: Any error that occurred during retrieval. +// +// Example: +// +// templates, err := listModelArmorTemplates( +// os.Stdout, +// "my-project", +// "my-location", +// ) +// if err != nil { +// log.Fatal(err) +// } +// for _, template := range templates { +// fmt.Println(template) +// } +func listModelArmorTemplates(w io.Writer, projectID, location string) ([]*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + // Initialize request argument(s). + req := &modelarmorpb.ListTemplatesRequest{ + Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location), + } + + // Get list of templates. + it := client.ListTemplates(ctx, req) + var templates []*modelarmorpb.Template + + for { + template, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + return nil, fmt.Errorf("failed to iterate templates: %v", err) + } + templates = append(templates, template) + fmt.Fprintf(w, "Template: %s\n", template.Name) + } + + // [END modelarmor_list_templates] + + return templates, nil +} diff --git a/modelarmor/list_templates_with_filter.go b/modelarmor/list_templates_with_filter.go new file mode 100644 index 0000000000..c8407b5700 --- /dev/null +++ b/modelarmor/list_templates_with_filter.go @@ -0,0 +1,101 @@ +// 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](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. + +// Sample code for listing model armor templates with filters. + +package modelarmor + +// [START modelarmor_list_templates_with_filter] + +import ( + "context" + "fmt" + "io" + "strings" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/iterator" + "google.golang.org/api/option" +) + +// listModelArmorTemplatesWithFilter lists Model Armor templates with a filter. +// +// This method lists Model Armor templates that match the specified filter. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the project. +// locationID string: The ID of the location. +// templateID string: The ID of the template. +// +// Returns: +// +// []string: A list of template IDs that match the filter. +// error: Any error that occurred during retrieval. +// +// Example: +// +// templateIDs, err := listModelArmorTemplatesWithFilter( +// os.Stdout, +// "my-project", +// "my-location", +// "my-template", +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(templateIDs) +func listModelArmorTemplatesWithFilter(w io.Writer, projectID, locationID, templateID string) ([]string, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + // Preparing the parent path + parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) + + // Get the list of templates + req := &modelarmorpb.ListTemplatesRequest{ + Parent: parent, + Filter: fmt.Sprintf(`name="%s/templates/%s"`, parent, templateID), + } + + it := client.ListTemplates(ctx, req) + var templateNames []string + + for { + template, err := it.Next() + if err == iterator.Done { + break + } + if err != nil { + return nil, fmt.Errorf("failed to iterate templates: %v", err) + } + templateNames = append(templateNames, template.Name) + } + + // Print templates name using fmt.Fprintf with the io.Writer + fmt.Fprintf(w, "Templates Found: %s\n", strings.Join(templateNames, ", ")) + // [END modelarmor_list_templates_with_filter] + + return templateNames, nil +} diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go new file mode 100644 index 0000000000..476c28ac60 --- /dev/null +++ b/modelarmor/modelarmor_test.go @@ -0,0 +1,457 @@ +// 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. + +package modelarmor + +import ( + "bytes" + "context" + "fmt" + "os" + "strings" + "testing" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + + "github.com/GoogleCloudPlatform/golang-samples/internal/testutil" + "github.com/google/uuid" + "google.golang.org/api/option" + grpccodes "google.golang.org/grpc/codes" + grpcstatus "google.golang.org/grpc/status" + // modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" +) + +func testLocation(t *testing.T) string { + t.Helper() + + // Load the test.env file + err := godotenv.Load("./testdata/env/test.env") + if err != nil { + t.fatal(err) + } + + v := os.Getenv("GOLANG_SAMPLES_LOCATION") + if v == "" { + t.Skip("testIamUser: missing GOLANG_SAMPLES_LOCATION") + } + + return v +} + +func testClient(t *testing.T) (*modelarmor.Client, context.Context) { + t.Helper() + + ctx := context.Background() + + locationId := testLocation(t) + + //Endpoint to send the request to regional server + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationId)), + ) + if err != nil { + t.Fatalf("failed to create client: %v", err) + } + + return client, ctx +} + +func testTemplate(t *testing.T) *modelarmorpb.Template { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + template, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID) + if err != nil { + t.Fatal(err) + } + return template +} + +func testCleanupTemplate(t *testing.T, templateName string) { + t.Helper() + + client, ctx := testClient(t) + if err := client.DeleteTemplate(ctx, &modelarmorpb.DeleteTemplateRequest{Name: templateName}); err != nil { + if terr, ok := grpcstatus.FromError(err); !ok || terr.Code() != grpccodes.NotFound { + t.Fatalf("testCleanupTemplate: failed to delete template: %v", err) + } + } + +} + +func testSDPTemplate(t *testing.T, projectID string, locationID string) (string, string) { + inspectTemplateID := fmt.Sprintf("model-armour-inspect-template-%s", uuid.New().String()) + deidentifyTemplateID := fmt.Sprintf("model-armour-deidentify-template-%s", uuid.New().String()) + apiEndpoint := fmt.Sprintf("dlp.%s.rep.googleapis.com:443", locationID) + parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) + infoTypes := []*dlppb.InfoType{ + {Name: "EMAIL_ADDRESS"}, + {Name: "PHONE_NUMBER"}, + {Name: "US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER"}, + } + + // Create the DLP client. + ctx := context.Background() + fmt.Println("Before Client") + dlpClient, err := dlp.NewClient(ctx, option.WithEndpoint(apiEndpoint)) + if err != nil { + fmt.Println("Getting error while creating the client") + t.Fatal(err) + } + fmt.Println("After Client") + defer dlpClient.Close() + + Create the inspect template. + inspectRequest := &dlppb.CreateInspectTemplateRequest{ + Parent: parent, + TemplateId: inspectTemplateID, + InspectTemplate: &dlppb.InspectTemplate{ + InspectConfig: &dlppb.InspectConfig{ + InfoTypes: infoTypes, + }, + }, + } + inspectResponse, err := dlpClient.CreateInspectTemplate(ctx, inspectRequest) + if err != nil { + t.Fatal(err) + } + + Create the deidentify template. + deidentifyRequest := &dlppb.CreateDeidentifyTemplateRequest{ + Parent: parent, + TemplateId: deidentifyTemplateID, + DeidentifyTemplate: &dlppb.DeidentifyTemplate{ + DeidentifyConfig: &dlppb.DeidentifyConfig{ + Transformation: &dlppb.DeidentifyConfig_InfoTypeTransformations{ + InfoTypeTransformations: &dlppb.InfoTypeTransformations{ + Transformations: []*dlppb.InfoTypeTransformations_InfoTypeTransformation{ + { + InfoTypes: []*dlppb.InfoType{}, + PrimitiveTransformation: &dlppb.PrimitiveTransformation{ + Transformation: &dlppb.PrimitiveTransformation_ReplaceConfig{ + ReplaceConfig: &dlppb.ReplaceValueConfig{ + NewValue: &dlppb.Value{ + Type: &dlppb.Value_StringValue{StringValue: "REDACTED"}, + }, + }, + }, + }, + }, + }, + }, + }, + }, + }, + } + deidentifyResponse, err := dlpClient.CreateDeidentifyTemplate(ctx, deidentifyRequest) + if err != nil { + t.Fatal(err) + } + + inspectTemplateName, deidentifyTemplateName := inspectResponse.Name, deidentifyResponse.Name + + Clean up the templates. + defer func() { + time.Sleep(5 * time.Second) + err := dlpClient.DeleteInspectTemplate(ctx, &dlppb.DeleteInspectTemplateRequest{Name: inspectResponse.Name}) + if err != nil { + t.Errorf("failed to delete inspect template: %v", err) + } + err = dlpClient.DeleteDeidentifyTemplate(ctx, &dlppb.DeleteDeidentifyTemplateRequest{Name: deidentifyResponse.Name}) + if err != nil { + t.Errorf("failed to delete deidentify template: %v", err) + } + }() + + return inspectTemplateName, deidentifyTemplateName +} + +func TestCreateModelArmorTemplate(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if got, want := b.String(), "Created template:"; !strings.Contains(got, want) { + t.Errorf("createModelArmorTemplate: expected %q to contain %q", got, want) + } +} + +func TestCreateModelArmorTemplateWithMetadata(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplateWithMetadata(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if got, want := b.String(), "Created Model Armor Template:"; !strings.Contains(got, want) { + t.Errorf("createModelArmorTemplateWithMetadata: expected %q to contain %q", got, want) + } +} + +func TestCreateModelArmorTemplateWithLabels(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplateWithLabels(&b, tc.ProjectID, "us-central1", templateID, map[string]string{"testkey": "testvalue"}); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if got, want := b.String(), "Created Template with labels: "; !strings.Contains(got, want) { + fmt.Println("This is Got ", got) + fmt.Println("This is Want ", want) + t.Errorf("createModelArmorTemplateWithLabels: expected %q to contain %q", got, want) + } else { + template, err := getModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID) + if err != nil { + t.Fatal(err) + } + + // Verify the labels + if len(template.Labels) != 1 { + t.Errorf("expected 1 label, got %d", len(template.Labels)) + } + if template.Labels["testkey"] != "testvalue" { + t.Errorf("expected label testkey to be testvalue, got %s", template.Labels["testkey"]) + } + } +} + +func TestCreateModelArmorTemplateWithBasicSDP(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplateWithBasicSDP(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if got, want := b.String(), "Created Template with basic SDP: "; !strings.Contains(got, want) { + t.Errorf("createModelArmorTemplateWithBasicSDP: expected %q to contain %q", got, want) + } +} + +func TestCreateModelArmorTemplateWithAdvancedSDP(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + fmt.Println("BeforeTestSDPTemplate") + inspectTemplateName, deideintifyTemplateName := testSDPTemplate(t, tc.ProjectID, "us-central1") + fmt.Println("AfterTestSDPTemplate") + + var b bytes.Buffer + if _, err := createModelArmorTemplateWithAdvancedSDP(&b, tc.ProjectID, "us-central1", templateID, inspectTemplateName, deideintifyTemplateName); err != nil { + fmt.Println("Error is here") + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if got, want := b.String(), "Created Template with advanced SDP: "; !strings.Contains(got, want) { + t.Errorf("createModelArmorTemplateWithAdvancedSDP: expected %q to contain %q", got, want) + } +} + +func TestDeleteModelArmorTemplate(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + + if err := deleteModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + + if got, want := b.String(), "Successfully deleted Model Armor template:"; !strings.Contains(got, want) { + t.Errorf("deleteModelArmorTemplate: expected %q to contain %q", got, want) + } +} + +func TestGetModelArmorTemplate(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if _, err := getModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + + if got, want := b.String(), "Retrieved template: "; !strings.Contains(got, want) { + t.Errorf("getModelArmorTemplates: expected %q to contain %q", got, want) + } +} + +func TestListModelArmorTemplates(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if _, err := listModelArmorTemplates(&b, tc.ProjectID, "us-central1"); err != nil { + t.Fatal(err) + } + + if got, want := b.String(), "Template: "; !strings.Contains(got, want) { + t.Errorf("listModelArmorTemplates: expected %q to contain %q", got, want) + } +} + +func TestListModelArmorTemplatesWithFilter(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if _, err := listModelArmorTemplatesWithFilter(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + + if got, want := b.String(), "Templates Found: "; !strings.Contains(got, want) { + t.Errorf("listModelArmorTemplatesWithFilter: expected %q to contain %q", got, want) + } +} + +func TestUpdateTemplate(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if _, err := updateModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + + if got, want := b.String(), "Updated Filter Config: "; !strings.Contains(got, want) { + t.Errorf("updateModelArmorTemplate: expected %q to contain %q", got, want) + } +} + +func TestUpdateTemplateMetadata(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if _, err := updateModelArmorTemplateMetadata(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + + if got, want := b.String(), "Updated Model Armor Template Metadata: "; !strings.Contains(got, want) { + t.Errorf("updateModelArmorTemplateMetadata: expected %q to contain %q", got, want) + } +} + +func TestUpdateTemplateLabels(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if _, err := updateModelArmorTemplateLabels(&b, tc.ProjectID, "us-central1", templateID, map[string]string{"testkey": "testvalue"}); err != nil { + t.Fatal(err) + } + + if got, want := b.String(), "Updated Model Armor Template Labels: "; !strings.Contains(got, want) { + t.Errorf("updateModelArmorTemplateLabels: expected %q to contain %q", got, want) + } else { + template, err := getModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID) + if err != nil { + t.Fatal(err) + } + + // Verify the labels + if len(template.Labels) != 1 { + t.Errorf("expected 1 label, got %d", len(template.Labels)) + } + if template.Labels["testkey"] != "testvalue" { + t.Errorf("expected label testkey to be testvalue, got %s", template.Labels["testkey"]) + } + } +} + +func TestUpdateTemplateWithMaskConfiguration(t *testing.T) { + tc := testutil.SystemTest(t) + + templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + + var b bytes.Buffer + if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + + if _, err := updateModelArmorTemplateWithMaskConfiguration(&b, tc.ProjectID, "us-central1", templateID); err != nil { + t.Fatal(err) + } + + if got, want := b.String(), "Updated Model Armor Template: "; !strings.Contains(got, want) { + t.Errorf("updateModelArmorTemplateWithMaskConfiguration: expected %q to contain %q", got, want) + } +} + + + + + diff --git a/modelarmor/testdata/env/test.env b/modelarmor/testdata/env/test.env new file mode 100644 index 0000000000..4a734b2e2f --- /dev/null +++ b/modelarmor/testdata/env/test.env @@ -0,0 +1,2 @@ +GOLANG_SAMPLES_ORGANIZATION_ID: 951890214235 +GOLANG_SAMPLES_FOLDER_ID: 695279264361 \ No newline at end of file diff --git a/modelarmor/update_template.go b/modelarmor/update_template.go new file mode 100644 index 0000000000..e4c77a717e --- /dev/null +++ b/modelarmor/update_template.go @@ -0,0 +1,104 @@ +// 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](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. + +// Sample code for updating the model armor template. + +package modelarmor + +// [START modelarmor_update_template] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" +) + +// updateModelArmorTemplate updates a Model Armor template. +// +// This method updates a Model Armor template. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the project. +// locationID string: The ID of the location. +// templateID string: The ID of the template. +// +// Returns: +// +// *modelarmorpb.Template: The updated template. +// error: Any error that occurred during update. +// +// Example: +// +// updatedTemplate, err := updateModelArmorTemplate( +// os.Stdout, +// "my-project", +// "my-location", +// "my-template", +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(updatedTemplate) +func updateModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) + updatedTemplate := &modelarmorpb.Template{ + Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID), + FilterConfig: &modelarmorpb.FilterConfig{ + PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{ + FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_LOW_AND_ABOVE, + }, + MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{ + FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED, + }, + }, + } + + // Initialize request argument(s). + req := &modelarmorpb.UpdateTemplateRequest{ + Template: updatedTemplate, + } + + // Update the template. + response, err := client.UpdateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to update template: %v", err) + } + + // Print the updated filters in the template. + fmt.Fprintf(w, "Updated Filter Config: %+v\n", response.FilterConfig) + + // [END modelarmor_update_template] + + return response, nil +} diff --git a/modelarmor/update_template_labels.go b/modelarmor/update_template_labels.go new file mode 100644 index 0000000000..c9271117e4 --- /dev/null +++ b/modelarmor/update_template_labels.go @@ -0,0 +1,106 @@ +// 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](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. + +// Sample code for updating the labels of the given model armor template. + +package modelarmor + +// [START modelarmor_update_template_with_labels] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" + "google.golang.org/protobuf/types/known/fieldmaskpb" +) + +// updateModelArmorTemplateLabels updates the labels of a Model Armor template. +// +// This method updates the labels of a Model Armor template. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the project. +// locationID string: The ID of the location. +// templateID string: The ID of the template. +// labels map[string]string: The updated labels. +// +// Returns: +// +// *modelarmorpb.Template: The updated template with new labels. +// error: Any error that occurred during update. +// +// Example: +// +// updatedTemplate, err := updateModelArmorTemplateLabels( +// os.Stdout, +// "my-project", +// "my-location", +// "my-template", +// map[string]string{ +// "key1": "value1", +// "key2": "value2", +// }, +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(updatedTemplate) +func updateModelArmorTemplateLabels(w io.Writer, projectID, locationID, templateID string, labels map[string]string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) + template := &modelarmorpb.Template{ + Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID), + Labels: labels, + } + + // Prepare the request to update the template. + updateMask := &fieldmaskpb.FieldMask{ + Paths: []string{"labels"}, + } + + req := &modelarmorpb.UpdateTemplateRequest{ + Template: template, + UpdateMask: updateMask, + } + + // Update the template. + response, err := client.UpdateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to update template: %v", err) + } + + fmt.Fprintf(w, "Updated Model Armor Template Labels: %s\n", response.Name) + + // [END modelarmor_update_template_with_labels] + + return response, nil +} diff --git a/modelarmor/update_template_metadata.go b/modelarmor/update_template_metadata.go new file mode 100644 index 0000000000..70d9c77c21 --- /dev/null +++ b/modelarmor/update_template_metadata.go @@ -0,0 +1,133 @@ +// 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](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. + +// Sample code for updating the model armor template metadata. + +package modelarmor + +// [START modelarmor_update_template_metadata] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" +) + +// updateModelArmorTemplateMetadata updates the metadata of a Model Armor template. +// +// This method updates the metadata of a Model Armor template. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the project. +// locationID string: The ID of the location. +// templateID string: The ID of the template. +// +// Returns: +// +// *modelarmorpb.Template: The updated template with new metadata. +// error: Any error that occurred during update. +// +// Example: +// +// updatedTemplate, err := updateModelArmorTemplateMetadata( +// os.Stdout, +// "my-project", +// "my-location", +// "my-template", +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(updatedTemplate) +func updateModelArmorTemplateMetadata(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + // Build the full resource path for the template. + templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) + template := &modelarmorpb.Template{ + Name: templateName, + FilterConfig: &modelarmorpb.FilterConfig{ + RaiSettings: &modelarmorpb.RaiFilterSettings{ + RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ + { + FilterType: modelarmorpb.RaiFilterType_DANGEROUS, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_HARASSMENT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, + }, + { + FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + }, + }, + SdpSettings: &modelarmorpb.SdpFilterSettings{ + SdpConfiguration: &modelarmorpb.SdpFilterSettings_BasicConfig{ + BasicConfig: &modelarmorpb.SdpBasicConfig{ + FilterEnforcement: modelarmorpb.SdpBasicConfig_ENABLED, + }, + }, + }, + }, + // 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](https://cloud.google.com/security-command-center/docs/reference/model-armor/rest/v1/projects.locations.templates#templatemetadata) + TemplateMetadata: &modelarmorpb.Template_TemplateMetadata{ + IgnorePartialInvocationFailures: true, + LogSanitizeOperations: true, + }, + } + + // Prepare the request to update the template. + req := &modelarmorpb.UpdateTemplateRequest{ + Template: template, + } + + // Update the template. + response, err := client.UpdateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to update template: %v", err) + } + + fmt.Fprintf(w, "Updated Model Armor Template Metadata: %s\n", response.Name) + + // [END modelarmor_update_template_metadata] + + return response, nil +} diff --git a/modelarmor/update_template_with_mask_configuration.go b/modelarmor/update_template_with_mask_configuration.go new file mode 100644 index 0000000000..8629aa431d --- /dev/null +++ b/modelarmor/update_template_with_mask_configuration.go @@ -0,0 +1,136 @@ +// 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](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. + +// Sample code for updating the model armor template with update mask. + +package modelarmor + +// [START modelarmor_update_template_with_mask_configuration] + +import ( + "context" + "fmt" + "io" + + modelarmor "cloud.google.com/go/modelarmor/apiv1" + modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" + "google.golang.org/api/option" + "google.golang.org/protobuf/types/known/fieldmaskpb" +) + +// updateModelArmorTemplateWithMaskConfiguration updates a Model Armor template with mask configuration. +// +// This method updates a Model Armor template with mask configuration. +// +// Args: +// +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the project. +// locationID string: The ID of the location. +// templateID string: The ID of the template. +// +// Returns: +// +// *modelarmorpb.Template: The updated template with mask configuration. +// error: Any error that occurred during update. +// +// Example: +// +// updatedTemplate, err := updateModelArmorTemplateWithMaskConfiguration( +// os.Stdout, +// "my-project", +// "my-location", +// "my-template", +// ) +// if err != nil { +// log.Fatal(err) +// } +// fmt.Println(updatedTemplate) +func updateModelArmorTemplateWithMaskConfiguration(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { + ctx := context.Background() + + // Create the Model Armor client. + client, err := modelarmor.NewClient(ctx, + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + ) + if err != nil { + return nil, fmt.Errorf("failed to create client: %v", err) + } + defer client.Close() + + // Build the full resource path for the template. + templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) + template := &modelarmorpb.Template{ + Name: templateName, + FilterConfig: &modelarmorpb.FilterConfig{ + RaiSettings: &modelarmorpb.RaiFilterSettings{ + RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ + { + FilterType: modelarmorpb.RaiFilterType_DANGEROUS, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_HARASSMENT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, + }, + { + FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + { + FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, + }, + }, + }, + SdpSettings: &modelarmorpb.SdpFilterSettings{ + SdpConfiguration: &modelarmorpb.SdpFilterSettings_BasicConfig{ + BasicConfig: &modelarmorpb.SdpBasicConfig{ + FilterEnforcement: modelarmorpb.SdpBasicConfig_DISABLED, + }, + }, + }, + }, + } + + // 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](https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask) + updateMask := &fieldmaskpb.FieldMask{ + Paths: []string{"filter_config"}, + } + + // Prepare the request to update the template. + // If mask configuration is not provided, all provided fields will be overwritten. + req := &modelarmorpb.UpdateTemplateRequest{ + Template: template, + UpdateMask: updateMask, + } + + // Update the template. + response, err := client.UpdateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to update template: %v", err) + } + + fmt.Fprintf(w, "Updated Model Armor Template: %s\n", response.Name) + + // [END modelarmor_update_template_with_mask_configuration] + + return response, nil +} From 78110c9869c75462d91f4477720ae391551eaf51 Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Wed, 9 Apr 2025 12:28:01 +0530 Subject: [PATCH 02/12] feat(modelarmor): Added samples for creating, listing, updating and deleting modelarmor templates --- go.work | 1 + modelarmor/go.mod | 2 ++ modelarmor/go.sum | 4 ++++ modelarmor/modelarmor_test.go | 22 +++++++++------------- 4 files changed, 16 insertions(+), 13 deletions(-) diff --git a/go.work b/go.work index 6cdbf80018..aac100d800 100644 --- a/go.work +++ b/go.work @@ -106,6 +106,7 @@ use ( ./media ./memorystore ./monitoring + ./modelarmor ./opentelemetry/instrumentation/app ./opentelemetry/trace ./parametermanager diff --git a/modelarmor/go.mod b/modelarmor/go.mod index efc441148c..215868ddb4 100644 --- a/modelarmor/go.mod +++ b/modelarmor/go.mod @@ -3,6 +3,7 @@ module github.com/GoogleCloudPlatform/golang-samples/modelarmor go 1.23.0 require ( + cloud.google.com/go/dlp v1.21.0 cloud.google.com/go/modelarmor v0.1.0 github.com/GoogleCloudPlatform/golang-samples v0.0.0-20250404170905-0aca11152736 github.com/google/uuid v1.6.0 @@ -33,6 +34,7 @@ require ( github.com/google/s2a-go v0.1.9 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.5 // indirect github.com/googleapis/gax-go/v2 v2.14.1 // indirect + github.com/joho/godotenv v1.5.1 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect go.opentelemetry.io/contrib/detectors/gcp v1.34.0 // indirect diff --git a/modelarmor/go.sum b/modelarmor/go.sum index 9fc4a07037..59e3dbca2a 100644 --- a/modelarmor/go.sum +++ b/modelarmor/go.sum @@ -8,6 +8,8 @@ cloud.google.com/go/auth/oauth2adapt v0.2.7 h1:/Lc7xODdqcEw8IrZ9SvwnlLX6j9FHQM74 cloud.google.com/go/auth/oauth2adapt v0.2.7/go.mod h1:NTbTTzfvPl1Y3V1nPpOgl2w6d/FjO7NNUQaWSox6ZMc= cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= +cloud.google.com/go/dlp v1.21.0 h1:9kz7+gaB/0gBZsDUnNT1asDihNZSrRFSeUTBcBdUAkk= +cloud.google.com/go/dlp v1.21.0/go.mod h1:Y9HOVtPoArpL9sI1O33aN/vK9QRwDERU9PEJJfM8DvE= cloud.google.com/go/iam v1.4.0 h1:ZNfy/TYfn2uh/ukvhp783WhnbVluqf/tzOaqVUPlIPA= cloud.google.com/go/iam v1.4.0/go.mod h1:gMBgqPaERlriaOV0CUl//XUzDhSfXevn4OEUbg6VRs4= cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= @@ -67,6 +69,8 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.5 h1:VgzTY2jogw3xt39CusE github.com/googleapis/enterprise-certificate-proxy v0.3.5/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index 476c28ac60..0faebd1b50 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -21,12 +21,16 @@ import ( "os" "strings" "testing" + "time" + dlp "cloud.google.com/go/dlp/apiv2" + "cloud.google.com/go/dlp/apiv2/dlppb" modelarmor "cloud.google.com/go/modelarmor/apiv1" modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" "github.com/GoogleCloudPlatform/golang-samples/internal/testutil" "github.com/google/uuid" + "github.com/joho/godotenv" "google.golang.org/api/option" grpccodes "google.golang.org/grpc/codes" grpcstatus "google.golang.org/grpc/status" @@ -39,7 +43,7 @@ func testLocation(t *testing.T) string { // Load the test.env file err := godotenv.Load("./testdata/env/test.env") if err != nil { - t.fatal(err) + t.Fatalf(err.Error()) } v := os.Getenv("GOLANG_SAMPLES_LOCATION") @@ -106,16 +110,15 @@ func testSDPTemplate(t *testing.T, projectID string, locationID string) (string, // Create the DLP client. ctx := context.Background() - fmt.Println("Before Client") dlpClient, err := dlp.NewClient(ctx, option.WithEndpoint(apiEndpoint)) if err != nil { fmt.Println("Getting error while creating the client") t.Fatal(err) } - fmt.Println("After Client") + defer dlpClient.Close() - Create the inspect template. + // Create the inspect template. inspectRequest := &dlppb.CreateInspectTemplateRequest{ Parent: parent, TemplateId: inspectTemplateID, @@ -130,7 +133,7 @@ func testSDPTemplate(t *testing.T, projectID string, locationID string) (string, t.Fatal(err) } - Create the deidentify template. + // Create the deidentify template. deidentifyRequest := &dlppb.CreateDeidentifyTemplateRequest{ Parent: parent, TemplateId: deidentifyTemplateID, @@ -164,7 +167,7 @@ func testSDPTemplate(t *testing.T, projectID string, locationID string) (string, inspectTemplateName, deidentifyTemplateName := inspectResponse.Name, deidentifyResponse.Name - Clean up the templates. + // Clean up the templates. defer func() { time.Sleep(5 * time.Second) err := dlpClient.DeleteInspectTemplate(ctx, &dlppb.DeleteInspectTemplateRequest{Name: inspectResponse.Name}) @@ -263,9 +266,7 @@ func TestCreateModelArmorTemplateWithAdvancedSDP(t *testing.T) { tc := testutil.SystemTest(t) templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - fmt.Println("BeforeTestSDPTemplate") inspectTemplateName, deideintifyTemplateName := testSDPTemplate(t, tc.ProjectID, "us-central1") - fmt.Println("AfterTestSDPTemplate") var b bytes.Buffer if _, err := createModelArmorTemplateWithAdvancedSDP(&b, tc.ProjectID, "us-central1", templateID, inspectTemplateName, deideintifyTemplateName); err != nil { @@ -450,8 +451,3 @@ func TestUpdateTemplateWithMaskConfiguration(t *testing.T) { t.Errorf("updateModelArmorTemplateWithMaskConfiguration: expected %q to contain %q", got, want) } } - - - - - From 4095b9aa2f4e729d429eff4804c7893211c4cf03 Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Wed, 9 Apr 2025 15:34:00 +0530 Subject: [PATCH 03/12] feat(modelarmor): resolve review comments --- modelarmor/create_template.go | 2 +- modelarmor/create_template_with_advanced_sdp.go | 2 +- modelarmor/create_template_with_basic_sdp.go | 2 +- modelarmor/create_template_with_labels.go | 2 +- modelarmor/create_template_with_metadata.go | 2 +- modelarmor/delete_template.go | 2 +- modelarmor/get_template.go | 2 +- modelarmor/go.mod | 2 +- modelarmor/list_templates.go | 8 ++++---- modelarmor/list_templates_with_filter.go | 2 +- modelarmor/update_template.go | 2 +- modelarmor/update_template_labels.go | 2 +- modelarmor/update_template_metadata.go | 2 +- modelarmor/update_template_with_mask_configuration.go | 2 +- 14 files changed, 17 insertions(+), 17 deletions(-) diff --git a/modelarmor/create_template.go b/modelarmor/create_template.go index 6e56a94d6a..c42c4583ee 100644 --- a/modelarmor/create_template.go +++ b/modelarmor/create_template.go @@ -64,7 +64,7 @@ func createModelArmorTemplate(w io.Writer, projectID, location, templateID strin option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, location, err) } defer client.Close() diff --git a/modelarmor/create_template_with_advanced_sdp.go b/modelarmor/create_template_with_advanced_sdp.go index 9ef7de847e..d9eb3e97c1 100644 --- a/modelarmor/create_template_with_advanced_sdp.go +++ b/modelarmor/create_template_with_advanced_sdp.go @@ -68,7 +68,7 @@ func createModelArmorTemplateWithAdvancedSDP(w io.Writer, projectID, locationID, option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() diff --git a/modelarmor/create_template_with_basic_sdp.go b/modelarmor/create_template_with_basic_sdp.go index d1dfb9f365..4e3c83aea5 100644 --- a/modelarmor/create_template_with_basic_sdp.go +++ b/modelarmor/create_template_with_basic_sdp.go @@ -64,7 +64,7 @@ func createModelArmorTemplateWithBasicSDP(w io.Writer, projectID, locationID, te option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() diff --git a/modelarmor/create_template_with_labels.go b/modelarmor/create_template_with_labels.go index dc2c56df00..1982ec2072 100644 --- a/modelarmor/create_template_with_labels.go +++ b/modelarmor/create_template_with_labels.go @@ -70,7 +70,7 @@ func createModelArmorTemplateWithLabels(w io.Writer, projectID, locationID, temp option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() diff --git a/modelarmor/create_template_with_metadata.go b/modelarmor/create_template_with_metadata.go index 196b438ac9..230c889cb7 100644 --- a/modelarmor/create_template_with_metadata.go +++ b/modelarmor/create_template_with_metadata.go @@ -70,7 +70,7 @@ func createModelArmorTemplateWithMetadata(w io.Writer, projectID, locationID, te option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() diff --git a/modelarmor/delete_template.go b/modelarmor/delete_template.go index d23bef5fad..c58611de35 100644 --- a/modelarmor/delete_template.go +++ b/modelarmor/delete_template.go @@ -62,7 +62,7 @@ func deleteModelArmorTemplate(w io.Writer, projectID, location, templateID strin option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), ) if err != nil { - return fmt.Errorf("failed to create client: %v", err) + return fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, location, err) } defer client.Close() diff --git a/modelarmor/get_template.go b/modelarmor/get_template.go index e8ab646780..1df5efcdff 100644 --- a/modelarmor/get_template.go +++ b/modelarmor/get_template.go @@ -64,7 +64,7 @@ func getModelArmorTemplate(w io.Writer, projectID, location, templateID string) option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, location, err) } defer client.Close() diff --git a/modelarmor/go.mod b/modelarmor/go.mod index 215868ddb4..e983d55261 100644 --- a/modelarmor/go.mod +++ b/modelarmor/go.mod @@ -7,6 +7,7 @@ require ( cloud.google.com/go/modelarmor v0.1.0 github.com/GoogleCloudPlatform/golang-samples v0.0.0-20250404170905-0aca11152736 github.com/google/uuid v1.6.0 + github.com/joho/godotenv v1.5.1 google.golang.org/api v0.226.0 google.golang.org/grpc v1.71.0 google.golang.org/protobuf v1.36.5 @@ -34,7 +35,6 @@ require ( github.com/google/s2a-go v0.1.9 // indirect github.com/googleapis/enterprise-certificate-proxy v0.3.5 // indirect github.com/googleapis/gax-go/v2 v2.14.1 // indirect - github.com/joho/godotenv v1.5.1 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect go.opentelemetry.io/auto/sdk v1.1.0 // indirect go.opentelemetry.io/contrib/detectors/gcp v1.34.0 // indirect diff --git a/modelarmor/list_templates.go b/modelarmor/list_templates.go index 81db6c5d84..83486ad453 100644 --- a/modelarmor/list_templates.go +++ b/modelarmor/list_templates.go @@ -57,21 +57,21 @@ import ( // for _, template := range templates { // fmt.Println(template) // } -func listModelArmorTemplates(w io.Writer, projectID, location string) ([]*modelarmorpb.Template, error) { +func listModelArmorTemplates(w io.Writer, projectID, locationID string) ([]*modelarmorpb.Template, error) { ctx := context.Background() // Create the Model Armor client. client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), + option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() // Initialize request argument(s). req := &modelarmorpb.ListTemplatesRequest{ - Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location), + Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, locationID), } // Get list of templates. diff --git a/modelarmor/list_templates_with_filter.go b/modelarmor/list_templates_with_filter.go index c8407b5700..c11bbd7f7b 100644 --- a/modelarmor/list_templates_with_filter.go +++ b/modelarmor/list_templates_with_filter.go @@ -66,7 +66,7 @@ func listModelArmorTemplatesWithFilter(w io.Writer, projectID, locationID, templ option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() diff --git a/modelarmor/update_template.go b/modelarmor/update_template.go index e4c77a717e..f224e01f3e 100644 --- a/modelarmor/update_template.go +++ b/modelarmor/update_template.go @@ -64,7 +64,7 @@ func updateModelArmorTemplate(w io.Writer, projectID, locationID, templateID str option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() diff --git a/modelarmor/update_template_labels.go b/modelarmor/update_template_labels.go index c9271117e4..979cd4f02c 100644 --- a/modelarmor/update_template_labels.go +++ b/modelarmor/update_template_labels.go @@ -70,7 +70,7 @@ func updateModelArmorTemplateLabels(w io.Writer, projectID, locationID, template option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() diff --git a/modelarmor/update_template_metadata.go b/modelarmor/update_template_metadata.go index 70d9c77c21..a23c721483 100644 --- a/modelarmor/update_template_metadata.go +++ b/modelarmor/update_template_metadata.go @@ -64,7 +64,7 @@ func updateModelArmorTemplateMetadata(w io.Writer, projectID, locationID, templa option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() diff --git a/modelarmor/update_template_with_mask_configuration.go b/modelarmor/update_template_with_mask_configuration.go index 8629aa431d..263a42b384 100644 --- a/modelarmor/update_template_with_mask_configuration.go +++ b/modelarmor/update_template_with_mask_configuration.go @@ -65,7 +65,7 @@ func updateModelArmorTemplateWithMaskConfiguration(w io.Writer, projectID, locat option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), ) if err != nil { - return nil, fmt.Errorf("failed to create client: %v", err) + return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) } defer client.Close() From cb7c703d0bbfdc354e12ac3a0e151f9cc9eb179f Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Fri, 11 Apr 2025 14:50:43 +0530 Subject: [PATCH 04/12] feat(modelarmor): added samples for to create ma template with labels and metadata --- .../create_template_with_advanced_sdp.go | 130 -------- modelarmor/create_template_with_basic_sdp.go | 127 ------- modelarmor/go.mod | 3 +- modelarmor/go.sum | 2 - modelarmor/list_templates.go | 96 ------ modelarmor/list_templates_with_filter.go | 101 ------ modelarmor/modelarmor_test.go | 310 +----------------- modelarmor/update_template.go | 104 ------ modelarmor/update_template_labels.go | 106 ------ modelarmor/update_template_metadata.go | 133 -------- ...update_template_with_mask_configuration.go | 136 -------- 11 files changed, 2 insertions(+), 1246 deletions(-) delete mode 100644 modelarmor/create_template_with_advanced_sdp.go delete mode 100644 modelarmor/create_template_with_basic_sdp.go delete mode 100644 modelarmor/list_templates.go delete mode 100644 modelarmor/list_templates_with_filter.go delete mode 100644 modelarmor/update_template.go delete mode 100644 modelarmor/update_template_labels.go delete mode 100644 modelarmor/update_template_metadata.go delete mode 100644 modelarmor/update_template_with_mask_configuration.go diff --git a/modelarmor/create_template_with_advanced_sdp.go b/modelarmor/create_template_with_advanced_sdp.go deleted file mode 100644 index d9eb3e97c1..0000000000 --- a/modelarmor/create_template_with_advanced_sdp.go +++ /dev/null @@ -1,130 +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. - -// Sample code for creating a new model armor template with advanced SDP settings enabled. - -package modelarmor - -// [START modelarmor_create_template_with_advanced_sdp] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/option" -) - -// createModelArmorTemplateWithAdvancedSDP creates a new Model Armor template with advanced SDP settings. -// -// This method creates a new Model Armor template with advanced SDP settings, including inspect and deidentify templates. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the Google Cloud project. -// locationID string: The ID of the Google Cloud location. -// templateID string: The ID of the template to create. -// inspectTemplate string: The ID of the inspect template to use. -// deidentifyTemplate string: The ID of the deidentify template to use. -// -// Returns: -// -// *modelarmorpb.Template: The created template. -// error: Any error that occurred during template creation. -// -// Example: -// -// template, err := createModelArmorTemplateWithAdvancedSDP( -// os.Stdout, -// "my-project", -// "us-central1", -// "my-template", -// "my-inspect-template", -// "my-deidentify-template", -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(template) -func createModelArmorTemplateWithAdvancedSDP(w io.Writer, projectID, locationID, templateID, inspectTemplate, deidentifyTemplate string) (*modelarmorpb.Template, error) { - ctx := context.Background() - - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), - ) - if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) - } - defer client.Close() - - parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) - - // Build the Model Armor template with your preferred filters. - template := &modelarmorpb.Template{ - FilterConfig: &modelarmorpb.FilterConfig{ - RaiSettings: &modelarmorpb.RaiFilterSettings{ - RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ - { - FilterType: modelarmorpb.RaiFilterType_DANGEROUS, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - { - FilterType: modelarmorpb.RaiFilterType_HARASSMENT, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, - }, - { - FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - { - FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - }, - }, - SdpSettings: &modelarmorpb.SdpFilterSettings{ - SdpConfiguration: &modelarmorpb.SdpFilterSettings_AdvancedConfig{ - AdvancedConfig: &modelarmorpb.SdpAdvancedConfig{ - InspectTemplate: inspectTemplate, - DeidentifyTemplate: deidentifyTemplate, - }, - }, - }, - }, - } - - // Prepare the request for creating the template. - req := &modelarmorpb.CreateTemplateRequest{ - Parent: parent, - TemplateId: templateID, - Template: template, - } - - // Create the template. - response, err := client.CreateTemplate(ctx, req) - if err != nil { - return nil, fmt.Errorf("failed to create template: %v", err) - } - - // Print the new template name using fmt.Fprint with the io.Writer. - fmt.Fprintf(w, "Created Template with advanced SDP: %s\n", response.Name) - - // [END modelarmor_create_template_with_advanced_sdp] - - return response, nil -} diff --git a/modelarmor/create_template_with_basic_sdp.go b/modelarmor/create_template_with_basic_sdp.go deleted file mode 100644 index 4e3c83aea5..0000000000 --- a/modelarmor/create_template_with_basic_sdp.go +++ /dev/null @@ -1,127 +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. - -// Sample code for creating a new model armor template with basic SDP settings enabled. - -package modelarmor - -// [START modelarmor_create_template_with_basic_sdp] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/option" -) - -// createModelArmorTemplateWithBasicSDP creates a new Model Armor template with basic SDP settings. -// -// This method creates a new Model Armor template with basic SDP settings. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the Google Cloud project. -// locationID string: The ID of the Google Cloud location. -// templateID string: The ID of the template to create. -// -// Returns: -// -// *modelarmorpb.Template: The created template. -// error: Any error that occurred during template creation. -// -// Example: -// -// template, err := createModelArmorTemplateWithBasicSDP( -// os.Stdout, -// "my-project", -// "us-central1", -// "my-template", -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(template) -func createModelArmorTemplateWithBasicSDP(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { - ctx := context.Background() - - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), - ) - if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) - } - defer client.Close() - - parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) - - // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) - template := &modelarmorpb.Template{ - FilterConfig: &modelarmorpb.FilterConfig{ - RaiSettings: &modelarmorpb.RaiFilterSettings{ - RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ - { - FilterType: modelarmorpb.RaiFilterType_DANGEROUS, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - { - FilterType: modelarmorpb.RaiFilterType_HARASSMENT, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, - }, - { - FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - { - FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - }, - }, - SdpSettings: &modelarmorpb.SdpFilterSettings{ - SdpConfiguration: &modelarmorpb.SdpFilterSettings_BasicConfig{ - BasicConfig: &modelarmorpb.SdpBasicConfig{ - FilterEnforcement: modelarmorpb.SdpBasicConfig_ENABLED, - }, - }, - }, - }, - } - - // Prepare the request for creating the template. - req := &modelarmorpb.CreateTemplateRequest{ - Parent: parent, - TemplateId: templateID, - Template: template, - } - - // Create the template. - response, err := client.CreateTemplate(ctx, req) - if err != nil { - return nil, fmt.Errorf("failed to create template: %v", err) - } - - // Print the new template name using fmt.Fprintf with the io.Writer. - fmt.Fprintf(w, "Created Template with basic SDP: %s\n", response.Name) - - // [END modelarmor_create_template_with_basic_sdp] - - return response, nil -} diff --git a/modelarmor/go.mod b/modelarmor/go.mod index e983d55261..44782d3001 100644 --- a/modelarmor/go.mod +++ b/modelarmor/go.mod @@ -3,14 +3,12 @@ module github.com/GoogleCloudPlatform/golang-samples/modelarmor go 1.23.0 require ( - cloud.google.com/go/dlp v1.21.0 cloud.google.com/go/modelarmor v0.1.0 github.com/GoogleCloudPlatform/golang-samples v0.0.0-20250404170905-0aca11152736 github.com/google/uuid v1.6.0 github.com/joho/godotenv v1.5.1 google.golang.org/api v0.226.0 google.golang.org/grpc v1.71.0 - google.golang.org/protobuf v1.36.5 ) require ( @@ -55,4 +53,5 @@ require ( google.golang.org/genproto v0.0.0-20250313205543-e70fdf4c4cb4 // indirect google.golang.org/genproto/googleapis/api v0.0.0-20250313205543-e70fdf4c4cb4 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20250303144028-a0af3efb3deb // indirect + google.golang.org/protobuf v1.36.5 // indirect ) diff --git a/modelarmor/go.sum b/modelarmor/go.sum index 59e3dbca2a..62dc411e92 100644 --- a/modelarmor/go.sum +++ b/modelarmor/go.sum @@ -8,8 +8,6 @@ cloud.google.com/go/auth/oauth2adapt v0.2.7 h1:/Lc7xODdqcEw8IrZ9SvwnlLX6j9FHQM74 cloud.google.com/go/auth/oauth2adapt v0.2.7/go.mod h1:NTbTTzfvPl1Y3V1nPpOgl2w6d/FjO7NNUQaWSox6ZMc= cloud.google.com/go/compute/metadata v0.6.0 h1:A6hENjEsCDtC1k8byVsgwvVcioamEHvZ4j01OwKxG9I= cloud.google.com/go/compute/metadata v0.6.0/go.mod h1:FjyFAW1MW0C203CEOMDTu3Dk1FlqW3Rga40jzHL4hfg= -cloud.google.com/go/dlp v1.21.0 h1:9kz7+gaB/0gBZsDUnNT1asDihNZSrRFSeUTBcBdUAkk= -cloud.google.com/go/dlp v1.21.0/go.mod h1:Y9HOVtPoArpL9sI1O33aN/vK9QRwDERU9PEJJfM8DvE= cloud.google.com/go/iam v1.4.0 h1:ZNfy/TYfn2uh/ukvhp783WhnbVluqf/tzOaqVUPlIPA= cloud.google.com/go/iam v1.4.0/go.mod h1:gMBgqPaERlriaOV0CUl//XUzDhSfXevn4OEUbg6VRs4= cloud.google.com/go/logging v1.13.0 h1:7j0HgAp0B94o1YRDqiqm26w4q1rDMH7XNRU34lJXHYc= diff --git a/modelarmor/list_templates.go b/modelarmor/list_templates.go deleted file mode 100644 index 83486ad453..0000000000 --- a/modelarmor/list_templates.go +++ /dev/null @@ -1,96 +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](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. - -// Sample code for getting list of model armor templates. - -package modelarmor - -// [START modelarmor_list_templates] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/iterator" - "google.golang.org/api/option" -) - -// listModelArmorTemplates lists Model Armor templates. -// -// This method lists Model Armor templates for a project and location. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the project. -// location string: The location of the templates. -// -// Returns: -// -// []*modelarmorpb.Template: A list of Model Armor templates. -// error: Any error that occurred during retrieval. -// -// Example: -// -// templates, err := listModelArmorTemplates( -// os.Stdout, -// "my-project", -// "my-location", -// ) -// if err != nil { -// log.Fatal(err) -// } -// for _, template := range templates { -// fmt.Println(template) -// } -func listModelArmorTemplates(w io.Writer, projectID, locationID string) ([]*modelarmorpb.Template, error) { - ctx := context.Background() - - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), - ) - if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) - } - defer client.Close() - - // Initialize request argument(s). - req := &modelarmorpb.ListTemplatesRequest{ - Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, locationID), - } - - // Get list of templates. - it := client.ListTemplates(ctx, req) - var templates []*modelarmorpb.Template - - for { - template, err := it.Next() - if err == iterator.Done { - break - } - if err != nil { - return nil, fmt.Errorf("failed to iterate templates: %v", err) - } - templates = append(templates, template) - fmt.Fprintf(w, "Template: %s\n", template.Name) - } - - // [END modelarmor_list_templates] - - return templates, nil -} diff --git a/modelarmor/list_templates_with_filter.go b/modelarmor/list_templates_with_filter.go deleted file mode 100644 index c11bbd7f7b..0000000000 --- a/modelarmor/list_templates_with_filter.go +++ /dev/null @@ -1,101 +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](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. - -// Sample code for listing model armor templates with filters. - -package modelarmor - -// [START modelarmor_list_templates_with_filter] - -import ( - "context" - "fmt" - "io" - "strings" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/iterator" - "google.golang.org/api/option" -) - -// listModelArmorTemplatesWithFilter lists Model Armor templates with a filter. -// -// This method lists Model Armor templates that match the specified filter. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the project. -// locationID string: The ID of the location. -// templateID string: The ID of the template. -// -// Returns: -// -// []string: A list of template IDs that match the filter. -// error: Any error that occurred during retrieval. -// -// Example: -// -// templateIDs, err := listModelArmorTemplatesWithFilter( -// os.Stdout, -// "my-project", -// "my-location", -// "my-template", -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(templateIDs) -func listModelArmorTemplatesWithFilter(w io.Writer, projectID, locationID, templateID string) ([]string, error) { - ctx := context.Background() - - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), - ) - if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) - } - defer client.Close() - - // Preparing the parent path - parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) - - // Get the list of templates - req := &modelarmorpb.ListTemplatesRequest{ - Parent: parent, - Filter: fmt.Sprintf(`name="%s/templates/%s"`, parent, templateID), - } - - it := client.ListTemplates(ctx, req) - var templateNames []string - - for { - template, err := it.Next() - if err == iterator.Done { - break - } - if err != nil { - return nil, fmt.Errorf("failed to iterate templates: %v", err) - } - templateNames = append(templateNames, template.Name) - } - - // Print templates name using fmt.Fprintf with the io.Writer - fmt.Fprintf(w, "Templates Found: %s\n", strings.Join(templateNames, ", ")) - // [END modelarmor_list_templates_with_filter] - - return templateNames, nil -} diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index 0faebd1b50..e90959f449 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -21,10 +21,7 @@ import ( "os" "strings" "testing" - "time" - - dlp "cloud.google.com/go/dlp/apiv2" - "cloud.google.com/go/dlp/apiv2/dlppb" + modelarmor "cloud.google.com/go/modelarmor/apiv1" modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" @@ -72,19 +69,6 @@ func testClient(t *testing.T) (*modelarmor.Client, context.Context) { return client, ctx } -func testTemplate(t *testing.T) *modelarmorpb.Template { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - template, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID) - if err != nil { - t.Fatal(err) - } - return template -} - func testCleanupTemplate(t *testing.T, templateName string) { t.Helper() @@ -97,92 +81,6 @@ func testCleanupTemplate(t *testing.T, templateName string) { } -func testSDPTemplate(t *testing.T, projectID string, locationID string) (string, string) { - inspectTemplateID := fmt.Sprintf("model-armour-inspect-template-%s", uuid.New().String()) - deidentifyTemplateID := fmt.Sprintf("model-armour-deidentify-template-%s", uuid.New().String()) - apiEndpoint := fmt.Sprintf("dlp.%s.rep.googleapis.com:443", locationID) - parent := fmt.Sprintf("projects/%s/locations/%s", projectID, locationID) - infoTypes := []*dlppb.InfoType{ - {Name: "EMAIL_ADDRESS"}, - {Name: "PHONE_NUMBER"}, - {Name: "US_INDIVIDUAL_TAXPAYER_IDENTIFICATION_NUMBER"}, - } - - // Create the DLP client. - ctx := context.Background() - dlpClient, err := dlp.NewClient(ctx, option.WithEndpoint(apiEndpoint)) - if err != nil { - fmt.Println("Getting error while creating the client") - t.Fatal(err) - } - - defer dlpClient.Close() - - // Create the inspect template. - inspectRequest := &dlppb.CreateInspectTemplateRequest{ - Parent: parent, - TemplateId: inspectTemplateID, - InspectTemplate: &dlppb.InspectTemplate{ - InspectConfig: &dlppb.InspectConfig{ - InfoTypes: infoTypes, - }, - }, - } - inspectResponse, err := dlpClient.CreateInspectTemplate(ctx, inspectRequest) - if err != nil { - t.Fatal(err) - } - - // Create the deidentify template. - deidentifyRequest := &dlppb.CreateDeidentifyTemplateRequest{ - Parent: parent, - TemplateId: deidentifyTemplateID, - DeidentifyTemplate: &dlppb.DeidentifyTemplate{ - DeidentifyConfig: &dlppb.DeidentifyConfig{ - Transformation: &dlppb.DeidentifyConfig_InfoTypeTransformations{ - InfoTypeTransformations: &dlppb.InfoTypeTransformations{ - Transformations: []*dlppb.InfoTypeTransformations_InfoTypeTransformation{ - { - InfoTypes: []*dlppb.InfoType{}, - PrimitiveTransformation: &dlppb.PrimitiveTransformation{ - Transformation: &dlppb.PrimitiveTransformation_ReplaceConfig{ - ReplaceConfig: &dlppb.ReplaceValueConfig{ - NewValue: &dlppb.Value{ - Type: &dlppb.Value_StringValue{StringValue: "REDACTED"}, - }, - }, - }, - }, - }, - }, - }, - }, - }, - }, - } - deidentifyResponse, err := dlpClient.CreateDeidentifyTemplate(ctx, deidentifyRequest) - if err != nil { - t.Fatal(err) - } - - inspectTemplateName, deidentifyTemplateName := inspectResponse.Name, deidentifyResponse.Name - - // Clean up the templates. - defer func() { - time.Sleep(5 * time.Second) - err := dlpClient.DeleteInspectTemplate(ctx, &dlppb.DeleteInspectTemplateRequest{Name: inspectResponse.Name}) - if err != nil { - t.Errorf("failed to delete inspect template: %v", err) - } - err = dlpClient.DeleteDeidentifyTemplate(ctx, &dlppb.DeleteDeidentifyTemplateRequest{Name: deidentifyResponse.Name}) - if err != nil { - t.Errorf("failed to delete deidentify template: %v", err) - } - }() - - return inspectTemplateName, deidentifyTemplateName -} - func TestCreateModelArmorTemplate(t *testing.T) { tc := testutil.SystemTest(t) @@ -245,209 +143,3 @@ func TestCreateModelArmorTemplateWithLabels(t *testing.T) { } } } - -func TestCreateModelArmorTemplateWithBasicSDP(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - if _, err := createModelArmorTemplateWithBasicSDP(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) - - if got, want := b.String(), "Created Template with basic SDP: "; !strings.Contains(got, want) { - t.Errorf("createModelArmorTemplateWithBasicSDP: expected %q to contain %q", got, want) - } -} - -func TestCreateModelArmorTemplateWithAdvancedSDP(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - inspectTemplateName, deideintifyTemplateName := testSDPTemplate(t, tc.ProjectID, "us-central1") - - var b bytes.Buffer - if _, err := createModelArmorTemplateWithAdvancedSDP(&b, tc.ProjectID, "us-central1", templateID, inspectTemplateName, deideintifyTemplateName); err != nil { - fmt.Println("Error is here") - t.Fatal(err) - } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) - - if got, want := b.String(), "Created Template with advanced SDP: "; !strings.Contains(got, want) { - t.Errorf("createModelArmorTemplateWithAdvancedSDP: expected %q to contain %q", got, want) - } -} - -func TestDeleteModelArmorTemplate(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - - if err := deleteModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - - if got, want := b.String(), "Successfully deleted Model Armor template:"; !strings.Contains(got, want) { - t.Errorf("deleteModelArmorTemplate: expected %q to contain %q", got, want) - } -} - -func TestGetModelArmorTemplate(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) - - if _, err := getModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - - if got, want := b.String(), "Retrieved template: "; !strings.Contains(got, want) { - t.Errorf("getModelArmorTemplates: expected %q to contain %q", got, want) - } -} - -func TestListModelArmorTemplates(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) - - if _, err := listModelArmorTemplates(&b, tc.ProjectID, "us-central1"); err != nil { - t.Fatal(err) - } - - if got, want := b.String(), "Template: "; !strings.Contains(got, want) { - t.Errorf("listModelArmorTemplates: expected %q to contain %q", got, want) - } -} - -func TestListModelArmorTemplatesWithFilter(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) - - if _, err := listModelArmorTemplatesWithFilter(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - - if got, want := b.String(), "Templates Found: "; !strings.Contains(got, want) { - t.Errorf("listModelArmorTemplatesWithFilter: expected %q to contain %q", got, want) - } -} - -func TestUpdateTemplate(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) - - if _, err := updateModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - - if got, want := b.String(), "Updated Filter Config: "; !strings.Contains(got, want) { - t.Errorf("updateModelArmorTemplate: expected %q to contain %q", got, want) - } -} - -func TestUpdateTemplateMetadata(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) - - if _, err := updateModelArmorTemplateMetadata(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - - if got, want := b.String(), "Updated Model Armor Template Metadata: "; !strings.Contains(got, want) { - t.Errorf("updateModelArmorTemplateMetadata: expected %q to contain %q", got, want) - } -} - -func TestUpdateTemplateLabels(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) - - if _, err := updateModelArmorTemplateLabels(&b, tc.ProjectID, "us-central1", templateID, map[string]string{"testkey": "testvalue"}); err != nil { - t.Fatal(err) - } - - if got, want := b.String(), "Updated Model Armor Template Labels: "; !strings.Contains(got, want) { - t.Errorf("updateModelArmorTemplateLabels: expected %q to contain %q", got, want) - } else { - template, err := getModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID) - if err != nil { - t.Fatal(err) - } - - // Verify the labels - if len(template.Labels) != 1 { - t.Errorf("expected 1 label, got %d", len(template.Labels)) - } - if template.Labels["testkey"] != "testvalue" { - t.Errorf("expected label testkey to be testvalue, got %s", template.Labels["testkey"]) - } - } -} - -func TestUpdateTemplateWithMaskConfiguration(t *testing.T) { - tc := testutil.SystemTest(t) - - templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - - var b bytes.Buffer - if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) - - if _, err := updateModelArmorTemplateWithMaskConfiguration(&b, tc.ProjectID, "us-central1", templateID); err != nil { - t.Fatal(err) - } - - if got, want := b.String(), "Updated Model Armor Template: "; !strings.Contains(got, want) { - t.Errorf("updateModelArmorTemplateWithMaskConfiguration: expected %q to contain %q", got, want) - } -} diff --git a/modelarmor/update_template.go b/modelarmor/update_template.go deleted file mode 100644 index f224e01f3e..0000000000 --- a/modelarmor/update_template.go +++ /dev/null @@ -1,104 +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](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. - -// Sample code for updating the model armor template. - -package modelarmor - -// [START modelarmor_update_template] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/option" -) - -// updateModelArmorTemplate updates a Model Armor template. -// -// This method updates a Model Armor template. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the project. -// locationID string: The ID of the location. -// templateID string: The ID of the template. -// -// Returns: -// -// *modelarmorpb.Template: The updated template. -// error: Any error that occurred during update. -// -// Example: -// -// updatedTemplate, err := updateModelArmorTemplate( -// os.Stdout, -// "my-project", -// "my-location", -// "my-template", -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(updatedTemplate) -func updateModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { - ctx := context.Background() - - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), - ) - if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) - } - defer client.Close() - - // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) - updatedTemplate := &modelarmorpb.Template{ - Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID), - FilterConfig: &modelarmorpb.FilterConfig{ - PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{ - FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_LOW_AND_ABOVE, - }, - MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{ - FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED, - }, - }, - } - - // Initialize request argument(s). - req := &modelarmorpb.UpdateTemplateRequest{ - Template: updatedTemplate, - } - - // Update the template. - response, err := client.UpdateTemplate(ctx, req) - if err != nil { - return nil, fmt.Errorf("failed to update template: %v", err) - } - - // Print the updated filters in the template. - fmt.Fprintf(w, "Updated Filter Config: %+v\n", response.FilterConfig) - - // [END modelarmor_update_template] - - return response, nil -} diff --git a/modelarmor/update_template_labels.go b/modelarmor/update_template_labels.go deleted file mode 100644 index 979cd4f02c..0000000000 --- a/modelarmor/update_template_labels.go +++ /dev/null @@ -1,106 +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](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. - -// Sample code for updating the labels of the given model armor template. - -package modelarmor - -// [START modelarmor_update_template_with_labels] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/option" - "google.golang.org/protobuf/types/known/fieldmaskpb" -) - -// updateModelArmorTemplateLabels updates the labels of a Model Armor template. -// -// This method updates the labels of a Model Armor template. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the project. -// locationID string: The ID of the location. -// templateID string: The ID of the template. -// labels map[string]string: The updated labels. -// -// Returns: -// -// *modelarmorpb.Template: The updated template with new labels. -// error: Any error that occurred during update. -// -// Example: -// -// updatedTemplate, err := updateModelArmorTemplateLabels( -// os.Stdout, -// "my-project", -// "my-location", -// "my-template", -// map[string]string{ -// "key1": "value1", -// "key2": "value2", -// }, -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(updatedTemplate) -func updateModelArmorTemplateLabels(w io.Writer, projectID, locationID, templateID string, labels map[string]string) (*modelarmorpb.Template, error) { - ctx := context.Background() - - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), - ) - if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) - } - defer client.Close() - - // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) - template := &modelarmorpb.Template{ - Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID), - Labels: labels, - } - - // Prepare the request to update the template. - updateMask := &fieldmaskpb.FieldMask{ - Paths: []string{"labels"}, - } - - req := &modelarmorpb.UpdateTemplateRequest{ - Template: template, - UpdateMask: updateMask, - } - - // Update the template. - response, err := client.UpdateTemplate(ctx, req) - if err != nil { - return nil, fmt.Errorf("failed to update template: %v", err) - } - - fmt.Fprintf(w, "Updated Model Armor Template Labels: %s\n", response.Name) - - // [END modelarmor_update_template_with_labels] - - return response, nil -} diff --git a/modelarmor/update_template_metadata.go b/modelarmor/update_template_metadata.go deleted file mode 100644 index a23c721483..0000000000 --- a/modelarmor/update_template_metadata.go +++ /dev/null @@ -1,133 +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](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. - -// Sample code for updating the model armor template metadata. - -package modelarmor - -// [START modelarmor_update_template_metadata] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/option" -) - -// updateModelArmorTemplateMetadata updates the metadata of a Model Armor template. -// -// This method updates the metadata of a Model Armor template. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the project. -// locationID string: The ID of the location. -// templateID string: The ID of the template. -// -// Returns: -// -// *modelarmorpb.Template: The updated template with new metadata. -// error: Any error that occurred during update. -// -// Example: -// -// updatedTemplate, err := updateModelArmorTemplateMetadata( -// os.Stdout, -// "my-project", -// "my-location", -// "my-template", -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(updatedTemplate) -func updateModelArmorTemplateMetadata(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { - ctx := context.Background() - - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), - ) - if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) - } - defer client.Close() - - // Build the full resource path for the template. - templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) - template := &modelarmorpb.Template{ - Name: templateName, - FilterConfig: &modelarmorpb.FilterConfig{ - RaiSettings: &modelarmorpb.RaiFilterSettings{ - RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ - { - FilterType: modelarmorpb.RaiFilterType_DANGEROUS, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - { - FilterType: modelarmorpb.RaiFilterType_HARASSMENT, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, - }, - { - FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - { - FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - }, - }, - SdpSettings: &modelarmorpb.SdpFilterSettings{ - SdpConfiguration: &modelarmorpb.SdpFilterSettings_BasicConfig{ - BasicConfig: &modelarmorpb.SdpBasicConfig{ - FilterEnforcement: modelarmorpb.SdpBasicConfig_ENABLED, - }, - }, - }, - }, - // 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](https://cloud.google.com/security-command-center/docs/reference/model-armor/rest/v1/projects.locations.templates#templatemetadata) - TemplateMetadata: &modelarmorpb.Template_TemplateMetadata{ - IgnorePartialInvocationFailures: true, - LogSanitizeOperations: true, - }, - } - - // Prepare the request to update the template. - req := &modelarmorpb.UpdateTemplateRequest{ - Template: template, - } - - // Update the template. - response, err := client.UpdateTemplate(ctx, req) - if err != nil { - return nil, fmt.Errorf("failed to update template: %v", err) - } - - fmt.Fprintf(w, "Updated Model Armor Template Metadata: %s\n", response.Name) - - // [END modelarmor_update_template_metadata] - - return response, nil -} diff --git a/modelarmor/update_template_with_mask_configuration.go b/modelarmor/update_template_with_mask_configuration.go deleted file mode 100644 index 263a42b384..0000000000 --- a/modelarmor/update_template_with_mask_configuration.go +++ /dev/null @@ -1,136 +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](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. - -// Sample code for updating the model armor template with update mask. - -package modelarmor - -// [START modelarmor_update_template_with_mask_configuration] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/option" - "google.golang.org/protobuf/types/known/fieldmaskpb" -) - -// updateModelArmorTemplateWithMaskConfiguration updates a Model Armor template with mask configuration. -// -// This method updates a Model Armor template with mask configuration. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the project. -// locationID string: The ID of the location. -// templateID string: The ID of the template. -// -// Returns: -// -// *modelarmorpb.Template: The updated template with mask configuration. -// error: Any error that occurred during update. -// -// Example: -// -// updatedTemplate, err := updateModelArmorTemplateWithMaskConfiguration( -// os.Stdout, -// "my-project", -// "my-location", -// "my-template", -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(updatedTemplate) -func updateModelArmorTemplateWithMaskConfiguration(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { - ctx := context.Background() - - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), - ) - if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) - } - defer client.Close() - - // Build the full resource path for the template. - templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) - template := &modelarmorpb.Template{ - Name: templateName, - FilterConfig: &modelarmorpb.FilterConfig{ - RaiSettings: &modelarmorpb.RaiFilterSettings{ - RaiFilters: []*modelarmorpb.RaiFilterSettings_RaiFilter{ - { - FilterType: modelarmorpb.RaiFilterType_DANGEROUS, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - { - FilterType: modelarmorpb.RaiFilterType_HARASSMENT, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, - }, - { - FilterType: modelarmorpb.RaiFilterType_HATE_SPEECH, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - { - FilterType: modelarmorpb.RaiFilterType_SEXUALLY_EXPLICIT, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_HIGH, - }, - }, - }, - SdpSettings: &modelarmorpb.SdpFilterSettings{ - SdpConfiguration: &modelarmorpb.SdpFilterSettings_BasicConfig{ - BasicConfig: &modelarmorpb.SdpBasicConfig{ - FilterEnforcement: modelarmorpb.SdpBasicConfig_DISABLED, - }, - }, - }, - }, - } - - // 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](https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask) - updateMask := &fieldmaskpb.FieldMask{ - Paths: []string{"filter_config"}, - } - - // Prepare the request to update the template. - // If mask configuration is not provided, all provided fields will be overwritten. - req := &modelarmorpb.UpdateTemplateRequest{ - Template: template, - UpdateMask: updateMask, - } - - // Update the template. - response, err := client.UpdateTemplate(ctx, req) - if err != nil { - return nil, fmt.Errorf("failed to update template: %v", err) - } - - fmt.Fprintf(w, "Updated Model Armor Template: %s\n", response.Name) - - // [END modelarmor_update_template_with_mask_configuration] - - return response, nil -} From cfdbe57857adb08b1a077063291f308757bc5afa Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Mon, 14 Apr 2025 14:56:08 +0530 Subject: [PATCH 05/12] feat(modelarmor): resolve review comments and code refactored --- modelarmor/create_template.go | 36 ++++-------- modelarmor/create_template_with_labels.go | 39 +++---------- modelarmor/create_template_with_metadata.go | 39 +++---------- modelarmor/delete_template.go | 31 +++------- modelarmor/get_template.go | 38 ++++-------- modelarmor/go.mod | 1 - modelarmor/go.sum | 2 - modelarmor/modelarmor_test.go | 64 +++++++++------------ modelarmor/testdata/env/test.env | 2 - 9 files changed, 74 insertions(+), 178 deletions(-) delete mode 100644 modelarmor/testdata/env/test.env diff --git a/modelarmor/create_template.go b/modelarmor/create_template.go index c42c4583ee..d0e8627cec 100644 --- a/modelarmor/create_template.go +++ b/modelarmor/create_template.go @@ -38,33 +38,17 @@ import ( // projectID string: The ID of the Google Cloud project. // locationID string: The ID of the Google Cloud location. // templateID string: The ID of the template to create. -// -// Returns: -// -// *modelarmorpb.Template: The created template. -// error: Any error that occurred during template creation. -// -// Example: -// -// template, err := createModelArmorTemplate( -// os.Stdout, -// "my-project", -// "us-central1", -// "my-template", -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(template) -func createModelArmorTemplate(w io.Writer, projectID, location, templateID string) (*modelarmorpb.Template, error) { +func createModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error { ctx := context.Background() + // Create options for Model Armor client. + opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) // Create the Model Armor client. client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), + option.WithEndpoint(opts), ) if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, location, err) + return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err) } defer client.Close() @@ -85,7 +69,7 @@ func createModelArmorTemplate(w io.Writer, projectID, location, templateID strin // Prepare the request for creating the template. req := &modelarmorpb.CreateTemplateRequest{ - Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location), + Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, locationID), TemplateId: templateID, Template: template, } @@ -93,13 +77,13 @@ func createModelArmorTemplate(w io.Writer, projectID, location, templateID strin // Create the template. response, err := client.CreateTemplate(ctx, req) if err != nil { - return nil, fmt.Errorf("failed to create template: %v", err) + return fmt.Errorf("failed to create template: %w", err) } // Print the new template name using fmt.Fprintf with the io.Writer. fmt.Fprintf(w, "Created template: %s\n", response.Name) - // [END modelarmor_create_template] - - return response, nil + return err } + +// [END modelarmor_create_template] diff --git a/modelarmor/create_template_with_labels.go b/modelarmor/create_template_with_labels.go index 1982ec2072..dc0111ddf1 100644 --- a/modelarmor/create_template_with_labels.go +++ b/modelarmor/create_template_with_labels.go @@ -39,38 +39,17 @@ import ( // locationID string: The ID of the Google Cloud location. // templateID string: The ID of the template to create. // labels map[string]string: A map of custom labels to apply to the template. -// -// Returns: -// -// *modelarmorpb.Template: The created template. -// error: Any error that occurred during template creation. -// -// Example: -// -// labels := map[string]string{ -// "env": "dev", -// "team": "security", -// } -// template, err := createModelArmorTemplateWithLabels( -// os.Stdout, -// "my-project", -// "us-central1", -// "my-template", -// labels, -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(template) -func createModelArmorTemplateWithLabels(w io.Writer, projectID, locationID, templateID string, labels map[string]string) (*modelarmorpb.Template, error) { +func createModelArmorTemplateWithLabels(w io.Writer, projectID, locationID, templateID string, labels map[string]string) error { ctx := context.Background() + // Create options for Model Armor client. + opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) // Create the Model Armor client. client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + option.WithEndpoint(opts), ) if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) + return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err) } defer client.Close() @@ -107,13 +86,13 @@ func createModelArmorTemplateWithLabels(w io.Writer, projectID, locationID, temp // Create the template. response, err := client.CreateTemplate(ctx, req) if err != nil { - return nil, fmt.Errorf("failed to create template: %v", err) + return fmt.Errorf("failed to create template: %w", err) } // Print the new template name using fmt.Fprintf with the io.Writer. fmt.Fprintf(w, "Created Template with labels: %s\n", response.Name) - // [END modelarmor_create_template_with_labels] - - return response, nil + return err } + +// [END modelarmor_create_template_with_labels] diff --git a/modelarmor/create_template_with_metadata.go b/modelarmor/create_template_with_metadata.go index 230c889cb7..12e2211211 100644 --- a/modelarmor/create_template_with_metadata.go +++ b/modelarmor/create_template_with_metadata.go @@ -39,38 +39,17 @@ import ( // locationID string: The ID of the Google Cloud location. // templateID string: The ID of the template to create. // metadata *modelarmorpb.TemplateMetadata: The template metadata to apply. -// -// Returns: -// -// *modelarmorpb.Template: The created template. -// error: Any error that occurred during template creation. -// -// Example: -// -// metadata := &modelarmorpb.TemplateMetadata{ -// Description: "My template", -// Version: "1.0", -// } -// template, err := createModelArmorTemplateWithMetadata( -// os.Stdout, -// "my-project", -// "us-central1", -// "my-template", -// metadata, -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(template) -func createModelArmorTemplateWithMetadata(w io.Writer, projectID, locationID, templateID string) (*modelarmorpb.Template, error) { +func createModelArmorTemplateWithMetadata(w io.Writer, projectID, locationID, templateID string) error { ctx := context.Background() + // Create options for Model Armor client. + opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) // Create the Model Armor client. client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID)), + option.WithEndpoint(opts), ) if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, locationID, err) + return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err) } defer client.Close() @@ -113,13 +92,13 @@ func createModelArmorTemplateWithMetadata(w io.Writer, projectID, locationID, te // Create the template. response, err := client.CreateTemplate(ctx, req) if err != nil { - return nil, fmt.Errorf("failed to create template: %v", err) + return fmt.Errorf("failed to create template: %w", err) } // Print the new template name using fmt.Fprintf with the io.Writer. fmt.Fprintf(w, "Created Model Armor Template: %s\n", response.Name) - // [END modelarmor_create_template_with_metadata] - - return response, nil + return err } + +// [END modelarmor_create_template_with_metadata] diff --git a/modelarmor/delete_template.go b/modelarmor/delete_template.go index c58611de35..e1003b23c0 100644 --- a/modelarmor/delete_template.go +++ b/modelarmor/delete_template.go @@ -38,47 +38,34 @@ import ( // projectID string: The ID of the Google Cloud project. // locationID string: The ID of the Google Cloud location. // templateID string: The ID of the template to delete. -// -// Returns: -// -// error: Any error that occurred during template deletion. -// -// Example: -// -// err := deleteModelArmorTemplate( -// os.Stdout, -// "my-project", -// "us-central1", -// "my-template", -// ) -// if err != nil { -// log.Fatal(err) -// } -func deleteModelArmorTemplate(w io.Writer, projectID, location, templateID string) error { +func deleteModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error { ctx := context.Background() + // Create options for Model Armor client. + opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) // Create the Model Armor client. client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), + option.WithEndpoint(opts), ) if err != nil { - return fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, location, err) + return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err) } defer client.Close() // Build the request for deleting the template. req := &modelarmorpb.DeleteTemplateRequest{ - Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, location, templateID), + Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID), } // Delete the template. if err := client.DeleteTemplate(ctx, req); err != nil { - return fmt.Errorf("failed to delete template: %v", err) + return fmt.Errorf("failed to delete template: %w", err) } // Print the success message using fmt.Fprintf with the io.Writer. fmt.Fprintf(w, "Successfully deleted Model Armor template: %s\n", req.Name) - // [END modelarmor_delete_template] return nil } + +// [END modelarmor_delete_template] diff --git a/modelarmor/get_template.go b/modelarmor/get_template.go index 1df5efcdff..449dbfbf98 100644 --- a/modelarmor/get_template.go +++ b/modelarmor/get_template.go @@ -36,53 +36,37 @@ import ( // // w io.Writer: The writer to use for logging. // projectID string: The ID of the project. -// location string: The location of the template. +// locationID string: The location of the template. // templateID string: The ID of the template. -// -// Returns: -// -// *modelarmorpb.Template: The retrieved Model Armor template. -// error: Any error that occurred during retrieval. -// -// Example: -// -// template, err := getModelArmorTemplate( -// os.Stdout, -// "my-project", -// "my-location", -// "my-template", -// ) -// if err != nil { -// log.Fatal(err) -// } -// fmt.Println(template) -func getModelArmorTemplate(w io.Writer, projectID, location, templateID string) (*modelarmorpb.Template, error) { +func getModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error { ctx := context.Background() + // Create Options for the Model Armor Client + opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) // Create the Model Armor client. client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", location)), + option.WithEndpoint(opts), ) if err != nil { - return nil, fmt.Errorf("failed to create client for project %s, location %s: %v", projectID, location, err) + return fmt.Errorf("failed to create client for project %s, locationID %s: %w", projectID, locationID, err) } defer client.Close() // Initialize request arguments. req := &modelarmorpb.GetTemplateRequest{ - Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, location, templateID), + Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID), } // Get the template. response, err := client.GetTemplate(ctx, req) if err != nil { - return nil, fmt.Errorf("failed to get template: %v", err) + return fmt.Errorf("failed to get template: %w", err) } // Print the template name using fmt.Fprintf with the io.Writer. fmt.Fprintf(w, "Retrieved template: %s\n", response.Name) - // [END modelarmor_get_template] - - return response, nil + return err } + +// [END modelarmor_get_template] diff --git a/modelarmor/go.mod b/modelarmor/go.mod index 44782d3001..5902fd6658 100644 --- a/modelarmor/go.mod +++ b/modelarmor/go.mod @@ -6,7 +6,6 @@ require ( cloud.google.com/go/modelarmor v0.1.0 github.com/GoogleCloudPlatform/golang-samples v0.0.0-20250404170905-0aca11152736 github.com/google/uuid v1.6.0 - github.com/joho/godotenv v1.5.1 google.golang.org/api v0.226.0 google.golang.org/grpc v1.71.0 ) diff --git a/modelarmor/go.sum b/modelarmor/go.sum index 62dc411e92..9fc4a07037 100644 --- a/modelarmor/go.sum +++ b/modelarmor/go.sum @@ -67,8 +67,6 @@ github.com/googleapis/enterprise-certificate-proxy v0.3.5 h1:VgzTY2jogw3xt39CusE github.com/googleapis/enterprise-certificate-proxy v0.3.5/go.mod h1:MkHOF77EYAE7qfSuSS9PU6g4Nt4e11cnsDUowfwewLA= github.com/googleapis/gax-go/v2 v2.14.1 h1:hb0FFeiPaQskmvakKu5EbCbpntQn48jyHuvrkurSS/Q= github.com/googleapis/gax-go/v2 v2.14.1/go.mod h1:Hb/NubMaVM88SrNkvl8X/o8XWwDJEPqouaLeN2IUxoA= -github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= -github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo= github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10/go.mod h1:t/avpk3KcrXxUnYOhZhMXJlSEyie6gQbtLq5NM3loB8= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index e90959f449..184b104b1e 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -21,54 +21,52 @@ import ( "os" "strings" "testing" - + modelarmor "cloud.google.com/go/modelarmor/apiv1" modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" "github.com/GoogleCloudPlatform/golang-samples/internal/testutil" "github.com/google/uuid" - "github.com/joho/godotenv" "google.golang.org/api/option" grpccodes "google.golang.org/grpc/codes" grpcstatus "google.golang.org/grpc/status" - // modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" ) +// testLocation returns the region where the tests should run, +// based on the GOLANG_SAMPLES_LOCATION environment variable. +// Skips the test if the variable is not set. func testLocation(t *testing.T) string { t.Helper() - // Load the test.env file - err := godotenv.Load("./testdata/env/test.env") - if err != nil { - t.Fatalf(err.Error()) - } - v := os.Getenv("GOLANG_SAMPLES_LOCATION") if v == "" { - t.Skip("testIamUser: missing GOLANG_SAMPLES_LOCATION") + t.Skip("testLocation: missing GOLANG_SAMPLES_LOCATION") } return v } +// testClient creates a new Model Armor API client using the regional endpoint +// derived from the environment. It returns the client and the context. func testClient(t *testing.T) (*modelarmor.Client, context.Context) { t.Helper() ctx := context.Background() - locationId := testLocation(t) - //Endpoint to send the request to regional server + // Set the endpoint for the regional replica based on location client, err := modelarmor.NewClient(ctx, option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationId)), ) if err != nil { - t.Fatalf("failed to create client: %v", err) + t.Fatalf("testClient: failed to create client: %v", err) } return client, ctx } +// testCleanupTemplate deletes a given template by name if it exists. +// Ignores NotFound errors, which means the resource has already been deleted. func testCleanupTemplate(t *testing.T, templateName string) { t.Helper() @@ -78,68 +76,58 @@ func testCleanupTemplate(t *testing.T, templateName string) { t.Fatalf("testCleanupTemplate: failed to delete template: %v", err) } } - } +// TestCreateModelArmorTemplate tests the creation of a basic Model Armor template. +// Verifies that the output includes a success message after creation. func TestCreateModelArmorTemplate(t *testing.T) { tc := testutil.SystemTest(t) - + locationID := testLocation(t) templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) var b bytes.Buffer - if _, err := createModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID); err != nil { + if err := createModelArmorTemplate(&b, tc.ProjectID, locationID, templateID); err != nil { t.Fatal(err) } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID)) if got, want := b.String(), "Created template:"; !strings.Contains(got, want) { t.Errorf("createModelArmorTemplate: expected %q to contain %q", got, want) } } +// TestCreateModelArmorTemplateWithMetadata tests the creation of a template with metadata. +// Verifies the success message is printed after template creation. func TestCreateModelArmorTemplateWithMetadata(t *testing.T) { tc := testutil.SystemTest(t) - + locationID := testLocation(t) templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) var b bytes.Buffer - if _, err := createModelArmorTemplateWithMetadata(&b, tc.ProjectID, "us-central1", templateID); err != nil { + if err := createModelArmorTemplateWithMetadata(&b, tc.ProjectID, locationID, templateID); err != nil { t.Fatal(err) } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID)) if got, want := b.String(), "Created Model Armor Template:"; !strings.Contains(got, want) { t.Errorf("createModelArmorTemplateWithMetadata: expected %q to contain %q", got, want) } } +// TestCreateModelArmorTemplateWithLabels tests the creation of a template with labels. +// Verifies the output contains confirmation of successful template creation. func TestCreateModelArmorTemplateWithLabels(t *testing.T) { tc := testutil.SystemTest(t) - + locationID := testLocation(t) templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) var b bytes.Buffer - if _, err := createModelArmorTemplateWithLabels(&b, tc.ProjectID, "us-central1", templateID, map[string]string{"testkey": "testvalue"}); err != nil { + if err := createModelArmorTemplateWithLabels(&b, tc.ProjectID, locationID, templateID, map[string]string{"testkey": "testvalue"}); err != nil { t.Fatal(err) } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, "us-central1", templateID)) + defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID)) if got, want := b.String(), "Created Template with labels: "; !strings.Contains(got, want) { - fmt.Println("This is Got ", got) - fmt.Println("This is Want ", want) t.Errorf("createModelArmorTemplateWithLabels: expected %q to contain %q", got, want) - } else { - template, err := getModelArmorTemplate(&b, tc.ProjectID, "us-central1", templateID) - if err != nil { - t.Fatal(err) - } - - // Verify the labels - if len(template.Labels) != 1 { - t.Errorf("expected 1 label, got %d", len(template.Labels)) - } - if template.Labels["testkey"] != "testvalue" { - t.Errorf("expected label testkey to be testvalue, got %s", template.Labels["testkey"]) - } } } diff --git a/modelarmor/testdata/env/test.env b/modelarmor/testdata/env/test.env deleted file mode 100644 index 4a734b2e2f..0000000000 --- a/modelarmor/testdata/env/test.env +++ /dev/null @@ -1,2 +0,0 @@ -GOLANG_SAMPLES_ORGANIZATION_ID: 951890214235 -GOLANG_SAMPLES_FOLDER_ID: 695279264361 \ No newline at end of file From a0081693611fd1ee65c0912ddf7d91092da45b2b Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Mon, 14 Apr 2025 21:41:44 +0530 Subject: [PATCH 06/12] feat(modelarmor): refactor code --- modelarmor/create_template.go | 89 --------------------- modelarmor/create_template_with_labels.go | 17 ++-- modelarmor/create_template_with_metadata.go | 17 ++-- modelarmor/delete_template.go | 71 ---------------- modelarmor/get_template.go | 72 ----------------- modelarmor/modelarmor_test.go | 47 +++++++++-- 6 files changed, 56 insertions(+), 257 deletions(-) delete mode 100644 modelarmor/create_template.go delete mode 100644 modelarmor/delete_template.go delete mode 100644 modelarmor/get_template.go diff --git a/modelarmor/create_template.go b/modelarmor/create_template.go deleted file mode 100644 index d0e8627cec..0000000000 --- a/modelarmor/create_template.go +++ /dev/null @@ -1,89 +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. - -// Sample code for creating a new model armor template. - -package modelarmor - -// [START modelarmor_create_template] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/option" -) - -// createModelArmorTemplate creates a new Model Armor template. -// -// This method creates a new Model Armor template with the provided settings. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the Google Cloud project. -// locationID string: The ID of the Google Cloud location. -// templateID string: The ID of the template to create. -func createModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error { - ctx := context.Background() - - // Create options for Model Armor client. - opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(opts), - ) - if err != nil { - return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err) - } - defer client.Close() - - // 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](https://cloud.google.com/security-command-center/docs/key-concepts-model-armor#ma-filters) - template := &modelarmorpb.Template{ - FilterConfig: &modelarmorpb.FilterConfig{ - PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{ - FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED, - ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, - }, - MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{ - FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED, - }, - }, - } - - // Prepare the request for creating the template. - req := &modelarmorpb.CreateTemplateRequest{ - Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, locationID), - TemplateId: templateID, - Template: template, - } - - // Create the template. - response, err := client.CreateTemplate(ctx, req) - if err != nil { - return fmt.Errorf("failed to create template: %w", err) - } - - // Print the new template name using fmt.Fprintf with the io.Writer. - fmt.Fprintf(w, "Created template: %s\n", response.Name) - - return err -} - -// [END modelarmor_create_template] diff --git a/modelarmor/create_template_with_labels.go b/modelarmor/create_template_with_labels.go index dc0111ddf1..be2e08f998 100644 --- a/modelarmor/create_template_with_labels.go +++ b/modelarmor/create_template_with_labels.go @@ -28,17 +28,14 @@ import ( "google.golang.org/api/option" ) -// createModelArmorTemplateWithLabels creates a new Model Armor template with custom labels. +// createModelArmorTemplateWithLabels method creates a +// new Model Armor template with custom labels. // -// This method creates a new Model Armor template with custom labels. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the Google Cloud project. -// locationID string: The ID of the Google Cloud location. -// templateID string: The ID of the template to create. -// labels map[string]string: A map of custom labels to apply to the template. +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the Google Cloud project. +// locationID string: The ID of the Google Cloud location. +// templateID string: The ID of the template to create. +// labels map[string]string: A map of custom labels to apply to the template. func createModelArmorTemplateWithLabels(w io.Writer, projectID, locationID, templateID string, labels map[string]string) error { ctx := context.Background() diff --git a/modelarmor/create_template_with_metadata.go b/modelarmor/create_template_with_metadata.go index 12e2211211..7de61eb693 100644 --- a/modelarmor/create_template_with_metadata.go +++ b/modelarmor/create_template_with_metadata.go @@ -28,17 +28,14 @@ import ( "google.golang.org/api/option" ) -// createModelArmorTemplateWithMetadata creates a new Model Armor template with template metadata. +// createModelArmorTemplateWithMetadata method creates a +// new Model Armor template with template metadata. // -// This method creates a new Model Armor template with template metadata. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the Google Cloud project. -// locationID string: The ID of the Google Cloud location. -// templateID string: The ID of the template to create. -// metadata *modelarmorpb.TemplateMetadata: The template metadata to apply. +// w io.Writer: The writer to use for logging. +// projectID string: The ID of the Google Cloud project. +// locationID string: The ID of the Google Cloud location. +// templateID string: The ID of the template to create. +// metadata *modelarmorpb.TemplateMetadata: The template metadata to apply. func createModelArmorTemplateWithMetadata(w io.Writer, projectID, locationID, templateID string) error { ctx := context.Background() diff --git a/modelarmor/delete_template.go b/modelarmor/delete_template.go deleted file mode 100644 index e1003b23c0..0000000000 --- a/modelarmor/delete_template.go +++ /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. - -// Sample code for deleting a model armor template. - -package modelarmor - -// [START modelarmor_delete_template] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/option" -) - -// deleteModelArmorTemplate deletes a Model Armor template. -// -// This method deletes a Model Armor template with the provided ID. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the Google Cloud project. -// locationID string: The ID of the Google Cloud location. -// templateID string: The ID of the template to delete. -func deleteModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error { - ctx := context.Background() - - // Create options for Model Armor client. - opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(opts), - ) - if err != nil { - return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err) - } - defer client.Close() - - // Build the request for deleting the template. - req := &modelarmorpb.DeleteTemplateRequest{ - Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID), - } - - // Delete the template. - if err := client.DeleteTemplate(ctx, req); err != nil { - return fmt.Errorf("failed to delete template: %w", err) - } - - // Print the success message using fmt.Fprintf with the io.Writer. - fmt.Fprintf(w, "Successfully deleted Model Armor template: %s\n", req.Name) - - return nil -} - -// [END modelarmor_delete_template] diff --git a/modelarmor/get_template.go b/modelarmor/get_template.go deleted file mode 100644 index 449dbfbf98..0000000000 --- a/modelarmor/get_template.go +++ /dev/null @@ -1,72 +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. - -// Sample code for getting a model armor template. - -package modelarmor - -// [START modelarmor_get_template] - -import ( - "context" - "fmt" - "io" - - modelarmor "cloud.google.com/go/modelarmor/apiv1" - modelarmorpb "cloud.google.com/go/modelarmor/apiv1/modelarmorpb" - "google.golang.org/api/option" -) - -// getModelArmorTemplate gets a Model Armor template. -// -// This method retrieves a Model Armor template. -// -// Args: -// -// w io.Writer: The writer to use for logging. -// projectID string: The ID of the project. -// locationID string: The location of the template. -// templateID string: The ID of the template. -func getModelArmorTemplate(w io.Writer, projectID, locationID, templateID string) error { - ctx := context.Background() - - // Create Options for the Model Armor Client - opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) - // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(opts), - ) - if err != nil { - return fmt.Errorf("failed to create client for project %s, locationID %s: %w", projectID, locationID, err) - } - defer client.Close() - - // Initialize request arguments. - req := &modelarmorpb.GetTemplateRequest{ - Name: fmt.Sprintf("projects/%s/locations/%s/templates/%s", projectID, locationID, templateID), - } - - // Get the template. - response, err := client.GetTemplate(ctx, req) - if err != nil { - return fmt.Errorf("failed to get template: %w", err) - } - - // Print the template name using fmt.Fprintf with the io.Writer. - fmt.Fprintf(w, "Retrieved template: %s\n", response.Name) - - return err -} - -// [END modelarmor_get_template] diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index 184b104b1e..9fbd24dc53 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -65,6 +65,40 @@ func testClient(t *testing.T) (*modelarmor.Client, context.Context) { return client, ctx } +// testModelArmorTemplate creates a new ModelArmor template for use in tests. +// It returns the created template or an error. +func testModelArmorTemplate(t *testing.T, templateID string) (*modelarmorpb.Template, error) { + t.Helper() + tc := testutil.SystemTest(t) + locationID := testLocation(t) + client, ctx := testClient(t) + + template := &modelarmorpb.Template{ + FilterConfig: &modelarmorpb.FilterConfig{ + PiAndJailbreakFilterSettings: &modelarmorpb.PiAndJailbreakFilterSettings{ + FilterEnforcement: modelarmorpb.PiAndJailbreakFilterSettings_ENABLED, + ConfidenceLevel: modelarmorpb.DetectionConfidenceLevel_MEDIUM_AND_ABOVE, + }, + MaliciousUriFilterSettings: &modelarmorpb.MaliciousUriFilterSettings{ + FilterEnforcement: modelarmorpb.MaliciousUriFilterSettings_ENABLED, + }, + }, + } + + req := &modelarmorpb.CreateTemplateRequest{ + Parent: fmt.Sprintf("projects/%s/locations/%s", tc.ProjectID, locationID), + TemplateId: templateID, + Template: template, + } + + response, err := client.CreateTemplate(ctx, req) + if err != nil { + return nil, fmt.Errorf("failed to create template: %v", err) + } + + return response, err +} + // testCleanupTemplate deletes a given template by name if it exists. // Ignores NotFound errors, which means the resource has already been deleted. func testCleanupTemplate(t *testing.T, templateName string) { @@ -84,12 +118,13 @@ func TestCreateModelArmorTemplate(t *testing.T) { tc := testutil.SystemTest(t) locationID := testLocation(t) templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - + templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID) var b bytes.Buffer - if err := createModelArmorTemplate(&b, tc.ProjectID, locationID, templateID); err != nil { + if _, err := testModelArmorTemplate(t, templateID); err != nil { t.Fatal(err) } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID)) + + defer testCleanupTemplate(t, templateName) if got, want := b.String(), "Created template:"; !strings.Contains(got, want) { t.Errorf("createModelArmorTemplate: expected %q to contain %q", got, want) @@ -102,12 +137,13 @@ func TestCreateModelArmorTemplateWithMetadata(t *testing.T) { tc := testutil.SystemTest(t) locationID := testLocation(t) templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID) var b bytes.Buffer if err := createModelArmorTemplateWithMetadata(&b, tc.ProjectID, locationID, templateID); err != nil { t.Fatal(err) } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID)) + defer testCleanupTemplate(t, templateName) if got, want := b.String(), "Created Model Armor Template:"; !strings.Contains(got, want) { t.Errorf("createModelArmorTemplateWithMetadata: expected %q to contain %q", got, want) @@ -120,12 +156,13 @@ func TestCreateModelArmorTemplateWithLabels(t *testing.T) { tc := testutil.SystemTest(t) locationID := testLocation(t) templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) + templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID) var b bytes.Buffer if err := createModelArmorTemplateWithLabels(&b, tc.ProjectID, locationID, templateID, map[string]string{"testkey": "testvalue"}); err != nil { t.Fatal(err) } - defer testCleanupTemplate(t, fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID)) + defer testCleanupTemplate(t, templateName) if got, want := b.String(), "Created Template with labels: "; !strings.Contains(got, want) { t.Errorf("createModelArmorTemplateWithLabels: expected %q to contain %q", got, want) From cc2593855a505595472a5ccad6bc21406a5fa121 Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Mon, 14 Apr 2025 21:45:51 +0530 Subject: [PATCH 07/12] feat(modelarmor): code refactor --- modelarmor/modelarmor_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index 9fbd24dc53..b455a46687 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -54,10 +54,10 @@ func testClient(t *testing.T) (*modelarmor.Client, context.Context) { ctx := context.Background() locationId := testLocation(t) + // Set the endpoint for the regional replica based on location - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationId)), - ) + opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationId)) + client, err := modelarmor.NewClient(ctx,opts) if err != nil { t.Fatalf("testClient: failed to create client: %v", err) } From cec29eca8e97b520c68e0d67ca69c1518a1f39d8 Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Fri, 18 Apr 2025 14:32:08 +0530 Subject: [PATCH 08/12] feat(modelarmor): resolve conflicts --- modelarmor/modelarmor_test.go | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index c46cef6beb..306c3f36f2 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -120,10 +120,9 @@ func TestCreateModelArmorTemplate(t *testing.T) { templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID) var b bytes.Buffer - if _, err := testModelArmorTemplate(t, templateID); err != nil { + if err := createModelArmorTemplate(&b, tc.ProjectID, locationID, templateID); err != nil { t.Fatal(err) } - defer testCleanupTemplate(t, templateName) if got, want := b.String(), "Created template:"; !strings.Contains(got, want) { From 2e82ed00643eb29fd8429e33a02da23eaadb59e5 Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Fri, 18 Apr 2025 17:35:19 +0530 Subject: [PATCH 09/12] feat(modelarmor): resolve conflicts --- modelarmor/modelarmor_test.go | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index 306c3f36f2..53654c06cd 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -32,9 +32,9 @@ import ( grpcstatus "google.golang.org/grpc/status" ) -// testLocation returns the region where the tests should run, -// based on the GOLANG_SAMPLES_LOCATION environment variable. -// Skips the test if the variable is not set. +// testLocation retrieves the GOLANG_SAMPLES_LOCATION environment variable +// used to determine the region for running the test. +// Skips the test if the environment variable is not set. func testLocation(t *testing.T) string { t.Helper() @@ -46,18 +46,17 @@ func testLocation(t *testing.T) string { return v } -// testClient creates a new Model Armor API client using the regional endpoint -// derived from the environment. It returns the client and the context. +// testClient initializes and returns a new Model Armor API client and context +// targeting the endpoint based on the specified location. func testClient(t *testing.T) (*modelarmor.Client, context.Context) { t.Helper() ctx := context.Background() locationId := testLocation(t) - - // Set the endpoint for the regional replica based on location + // Create option for Model Armor client. opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationId)) - client, err := modelarmor.NewClient(ctx,opts) + client, err := modelarmor.NewClient(ctx, opts) if err != nil { t.Fatalf("testClient: failed to create client: %v", err) } @@ -106,21 +105,21 @@ func testCleanupTemplate(t *testing.T, templateName string) { client, ctx := testClient(t) if err := client.DeleteTemplate(ctx, &modelarmorpb.DeleteTemplateRequest{Name: templateName}); err != nil { + // Ignore NotFound errors (template may already be deleted) if terr, ok := grpcstatus.FromError(err); !ok || terr.Code() != grpccodes.NotFound { t.Fatalf("testCleanupTemplate: failed to delete template: %v", err) } } } -// TestCreateModelArmorTemplate tests the creation of a basic Model Armor template. -// Verifies that the output includes a success message after creation. +// TestCreateModelArmorTemplate verifies the creation of a Model Armor template. +// It ensures the output contains a confirmation message after creation. func TestCreateModelArmorTemplate(t *testing.T) { tc := testutil.SystemTest(t) - locationID := testLocation(t) templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) - templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID) + templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, testLocation(t), templateID) var b bytes.Buffer - if err := createModelArmorTemplate(&b, tc.ProjectID, locationID, templateID); err != nil { + if err := createModelArmorTemplate(&b, tc.ProjectID, testLocation(t), templateID); err != nil { t.Fatal(err) } defer testCleanupTemplate(t, templateName) @@ -168,7 +167,6 @@ func TestCreateModelArmorTemplateWithLabels(t *testing.T) { } } - // TestDeleteModelArmorTemplate verifies the deletion of a Model Armor template. // It ensures the output contains a confirmation message after deletion. func TestDeleteModelArmorTemplate(t *testing.T) { @@ -190,4 +188,4 @@ func TestDeleteModelArmorTemplate(t *testing.T) { if got, want := buf.String(), "Successfully deleted Model Armor template:"; !strings.Contains(got, want) { t.Errorf("deleteModelArmorTemplate: expected %q to contain %q", got, want) } -} \ No newline at end of file +} From 54133127f08bdd2b4b12ab39587724770f4bc9b8 Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Fri, 18 Apr 2025 17:36:09 +0530 Subject: [PATCH 10/12] feat(modelarmor): resolve conflicts --- modelarmor/modelarmor_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index 53654c06cd..963d9e1688 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -53,9 +53,9 @@ func testClient(t *testing.T) (*modelarmor.Client, context.Context) { ctx := context.Background() locationId := testLocation(t) - // Create option for Model Armor client. opts := option.WithEndpoint(fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationId)) + // Create a new client using the regional endpoint client, err := modelarmor.NewClient(ctx, opts) if err != nil { t.Fatalf("testClient: failed to create client: %v", err) From dcfb1640233e07c0a9d30f2078a36d283553658a Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Thu, 24 Apr 2025 18:13:26 +0530 Subject: [PATCH 11/12] feat(modelarmor): resolve comments --- modelarmor/create_template_with_labels.go | 7 +++---- modelarmor/create_template_with_metadata.go | 7 +++---- modelarmor/modelarmor_test.go | 18 +++++++++--------- 3 files changed, 15 insertions(+), 17 deletions(-) diff --git a/modelarmor/create_template_with_labels.go b/modelarmor/create_template_with_labels.go index be2e08f998..1ddadce8b7 100644 --- a/modelarmor/create_template_with_labels.go +++ b/modelarmor/create_template_with_labels.go @@ -40,11 +40,10 @@ func createModelArmorTemplateWithLabels(w io.Writer, projectID, locationID, temp ctx := context.Background() // Create options for Model Armor client. - opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) + endpoint := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) + opts := option.WithEndpoint(endpoint) // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(opts), - ) + client, err := modelarmor.NewClient(ctx,opts) if err != nil { return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err) } diff --git a/modelarmor/create_template_with_metadata.go b/modelarmor/create_template_with_metadata.go index 7de61eb693..c7873edd0b 100644 --- a/modelarmor/create_template_with_metadata.go +++ b/modelarmor/create_template_with_metadata.go @@ -40,11 +40,10 @@ func createModelArmorTemplateWithMetadata(w io.Writer, projectID, locationID, te ctx := context.Background() // Create options for Model Armor client. - opts := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) + endpoint := fmt.Sprintf("modelarmor.%s.rep.googleapis.com:443", locationID) + opts := option.WithEndpoint(endpoint) // Create the Model Armor client. - client, err := modelarmor.NewClient(ctx, - option.WithEndpoint(opts), - ) + client, err := modelarmor.NewClient(ctx,opts) if err != nil { return fmt.Errorf("failed to create client for project %s, location %s: %w", projectID, locationID, err) } diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index 9204eeea2a..d1e59aa38b 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -221,13 +221,13 @@ func TestCreateModelArmorTemplate(t *testing.T) { tc := testutil.SystemTest(t) templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, testLocation(t), templateID) - var b bytes.Buffer - if err := createModelArmorTemplate(&b, tc.ProjectID, testLocation(t), templateID); err != nil { + var buf bytes.Buffer + if err := createModelArmorTemplate(&buf, tc.ProjectID, testLocation(t), templateID); err != nil { t.Fatal(err) } defer testCleanupTemplate(t, templateName) - if got, want := b.String(), "Created template:"; !strings.Contains(got, want) { + if got, want := buf.String(), "Created template:"; !strings.Contains(got, want) { t.Errorf("createModelArmorTemplate: expected %q to contain %q", got, want) } } @@ -240,13 +240,13 @@ func TestCreateModelArmorTemplateWithMetadata(t *testing.T) { templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID) - var b bytes.Buffer - if err := createModelArmorTemplateWithMetadata(&b, tc.ProjectID, locationID, templateID); err != nil { + var buf bytes.Buffer + if err := createModelArmorTemplateWithMetadata(&buf, tc.ProjectID, locationID, templateID); err != nil { t.Fatal(err) } defer testCleanupTemplate(t, templateName) - if got, want := b.String(), "Created Model Armor Template:"; !strings.Contains(got, want) { + if got, want := buf.String(), "Created Model Armor Template:"; !strings.Contains(got, want) { t.Errorf("createModelArmorTemplateWithMetadata: expected %q to contain %q", got, want) } } @@ -259,13 +259,13 @@ func TestCreateModelArmorTemplateWithLabels(t *testing.T) { templateID := fmt.Sprintf("test-model-armor-%s", uuid.New().String()) templateName := fmt.Sprintf("projects/%s/locations/%s/templates/%s", tc.ProjectID, locationID, templateID) - var b bytes.Buffer - if err := createModelArmorTemplateWithLabels(&b, tc.ProjectID, locationID, templateID, map[string]string{"testkey": "testvalue"}); err != nil { + var buf bytes.Buffer + if err := createModelArmorTemplateWithLabels(&buf, tc.ProjectID, locationID, templateID, map[string]string{"testkey": "testvalue"}); err != nil { t.Fatal(err) } defer testCleanupTemplate(t, templateName) - if got, want := b.String(), "Created Template with labels: "; !strings.Contains(got, want) { + if got, want := buf.String(), "Created Template with labels: "; !strings.Contains(got, want) { t.Errorf("createModelArmorTemplateWithLabels: expected %q to contain %q", got, want) } } From abdee68c5a4e55fc9041853b8cd5dfed6d91515a Mon Sep 17 00:00:00 2001 From: Tirthrajsinh Zala Date: Fri, 25 Apr 2025 11:27:33 +0530 Subject: [PATCH 12/12] feat(modelarmor): resolve comments --- modelarmor/create_template_with_labels.go | 2 +- modelarmor/create_template_with_metadata.go | 2 +- modelarmor/modelarmor_test.go | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/modelarmor/create_template_with_labels.go b/modelarmor/create_template_with_labels.go index 1ddadce8b7..8065cb382e 100644 --- a/modelarmor/create_template_with_labels.go +++ b/modelarmor/create_template_with_labels.go @@ -88,7 +88,7 @@ func createModelArmorTemplateWithLabels(w io.Writer, projectID, locationID, temp // Print the new template name using fmt.Fprintf with the io.Writer. fmt.Fprintf(w, "Created Template with labels: %s\n", response.Name) - return err + return nil } // [END modelarmor_create_template_with_labels] diff --git a/modelarmor/create_template_with_metadata.go b/modelarmor/create_template_with_metadata.go index c7873edd0b..e698950dff 100644 --- a/modelarmor/create_template_with_metadata.go +++ b/modelarmor/create_template_with_metadata.go @@ -94,7 +94,7 @@ func createModelArmorTemplateWithMetadata(w io.Writer, projectID, locationID, te // Print the new template name using fmt.Fprintf with the io.Writer. fmt.Fprintf(w, "Created Model Armor Template: %s\n", response.Name) - return err + return nil } // [END modelarmor_create_template_with_metadata] diff --git a/modelarmor/modelarmor_test.go b/modelarmor/modelarmor_test.go index d1e59aa38b..f3efa5f6a2 100644 --- a/modelarmor/modelarmor_test.go +++ b/modelarmor/modelarmor_test.go @@ -98,7 +98,7 @@ func testModelArmorTemplate(t *testing.T, templateID string) (*modelarmorpb.Temp return nil, fmt.Errorf("failed to create template: %v", err) } - return response, err + return response, nil } // testCleanupTemplate deletes a given template by name if it exists.