<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Edi Wiraya on Medium]]></title>
        <description><![CDATA[Stories by Edi Wiraya on Medium]]></description>
        <link>https://medium.com/@lumen1e37?source=rss-aace3a9d5171------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*62qMZjc4315BxkU5QeTWLA.jpeg</url>
            <title>Stories by Edi Wiraya on Medium</title>
            <link>https://medium.com/@lumen1e37?source=rss-aace3a9d5171------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 06:09:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lumen1e37/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Generative AI app development using Vertex AI and Golang]]></title>
            <link>https://medium.com/google-cloud/generative-ai-app-development-using-vertex-ai-and-golang-cf315c7fa4e1?source=rss-aace3a9d5171------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf315c7fa4e1</guid>
            <category><![CDATA[vertex-ai]]></category>
            <category><![CDATA[palm-2]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-studio]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Edi Wiraya]]></dc:creator>
            <pubDate>Fri, 21 Jul 2023 19:20:07 GMT</pubDate>
            <atom:updated>2023-07-22T04:38:25.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/719/1*xbSiRyBZ4BnFUCoQ-DlgFQ.png" /></figure><p><a href="https://cloud.google.com/vertex-ai">Vertex AI</a> is a unified platform for managing and orchestrating machine learning (ML) workflows with a comprehensive set of tools and services that make it easy to build, train, and deploy ML models at scale. In this article, we are going to use Vertex AI pre-trained large language model PaLM 2 for Text (aka. <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/text">text-bison</a>) to create an outline for a scientific essay using your input topic and a predefined prompt. You can easily tweak it to fit other needs and explore the power of <a href="https://ai.google/discover/palm2/">PaLM 2</a> generative AI features.</p><p>Inspired by <a href="https://medium.com/google-cloud/deploying-a-google-cloud-generative-ai-app-in-a-website-with-cloud-run-7c8aa5db344">Deploying a Google Cloud Generative AI App in a Website with Cloud Run</a>, I write this article focusing on application development aspect in <a href="https://go.dev/">Go</a> (Golang) instead of commonly available Python examples.</p><h4>Prerequisites:</h4><ul><li>Google Cloud Platform (GCP) account. Signup for free <a href="https://cloud.google.com/free">here</a></li><li>Download and install <a href="https://cloud.google.com/sdk/docs/install-sdk">Cloud SDK</a></li><li><a href="https://go.dev/dl/">Go</a></li></ul><h4>Text Generation Model</h4><p>Before going to the code, we need to create a new prompt using <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/learn/generative-ai-studio">Generative AI Studio</a>.</p><p>Go to the <a href="https://console.cloud.google.com/">GCP Console</a> and choose Vertex AI in the Artificial Intelligence section. Choose Language at Generative AI Studio section, and Text Prompt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/677/1*2vJku_-bcP7JZgHNxAHbMg.png" /></figure><p>On the right pane, set Model to text-bison@001. Create the prompt, tweak Temperature, Token Limit, Top-K and Top-P parameters. You can add inputs and outputs to tune the model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AWA65HEBt8-oSgBp-TFV8Q.png" /></figure><p>The following prompt and parameters will be used for the code later:</p><p><strong>Prompt:<br></strong>Create an outline for a scientific essay. Include the maths, experimental possibilities, alternatives, benefit and risk.</p><p>Input: ${input}<br>Output:</p><p><strong>Parameters:<br></strong>Temperature (temperature): 0.8<br>Token Limit (maxOutputToken): 512<br>Top-K (topK): 40<br>Top-P (topP): 0.8</p><blockquote>Note: You can change to different model, prompt and parameters you like. This is just an example.</blockquote><h4>Setting up local development environment</h4><p>Make sure you have a <a href="https://cloud.google.com/free">GCP account</a>, a project, and <a href="https://cloud.google.com/sdk/docs/install-sdk">Cloud SDK</a> installed on your development machine. Use <a href="https://cloud.google.com/docs/authentication/provide-credentials-adc#local-dev">Application Default Credentials (ADC)</a> to store your credential locally. This credential will be automatically used when the code calls Vertex AI API.</p><pre>gcloud auth login<br>gcloud config set project ${YOUR_GCP_PROJECT}<br>gcloud services enable aiplatform.googleapis.com<br>gcloud auth application-default login</pre><p>You will be redirected to the browser to authenticate, copy/paste authorization code back to your gcloud CLI.</p><blockquote>Warning: ADC is for development only, you should use Service Account attached to GCP resource in production environment.</blockquote><h4>IAM Permission</h4><p>IAM permission aiplatform.endpoints.predict is required to make prompt requests. Role roles/aiplatform.user (Vertex AI User) is a predefined role with that permission, you need to grant this role to your GCP user or group.</p><blockquote>Note: Grant permission to the Service Account if your service is deployed to GCP.</blockquote><h4>Application Development</h4><p>There are multiple approach for the application to access Vertex AI API:</p><ol><li>Call the API directly<br>When using Generative AI Studio, go to button &lt;&gt;VIEW CODE. Generative AI Studio can generate Python, Python Colab and Curl. You can manually construct Go http call using the same Curl parameters. This is ok for development purpose but for production environment you need extra steps to extract Service Account and pass it as Authorization token.</li><li>Google Cloud AI Platform Go library<br>This is a full version of Vertex AI Platform library with a lot of features and models. Essentially a superset of what we need.<br><a href="https://cloud.google.com/go/docs/reference/cloud.google.com/go/aiplatform/latest/apiv1#cloud_google_com_go_aiplatform_apiv1_PredictionClient_Predict">Google Cloud Go documentation</a> <br><a href="https://pkg.go.dev/cloud.google.com/go/aiplatform/apiv1#PredictionClient.Predict">Go Library doc</a></li><li>Google Cloud AI Go library (Beta)<br>This library has Generative Language similar to Python version. It is still in Beta when writing this article, and subject to change.<br><a href="https://cloud.google.com/go/docs/reference/cloud.google.com/go/ai/latest/generativelanguage/apiv1beta2">Google Cloud Go documentation (v0.1.0 apiv1beta2)</a><br><a href="https://pkg.go.dev/cloud.google.com/go/ai/generativelanguage/apiv1beta2/generativelanguagepb#GenerateTextRequest">Go Library doc</a> (v0.1.0 rev Jul 10th 2023)</li></ol><p>Let’s go with Option #2, I plan to add Option #3 when v1 is ready.</p><p>Go ahead to initiate <strong>go.mod</strong> if you have not done so. We need to download a few dependencies:</p><pre>go mod init yourmodulename<br>go get cloud.google.com/go/aiplatform<br>go get google.golang.org/api<br>go get google.golang.org/protobuf</pre><p>We use the model, prompt and parameters we’ve defined earlier:</p><pre>package main<br><br>import (<br>   &quot;context&quot;<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>  <br>   aiplatform &quot;cloud.google.com/go/aiplatform/apiv1&quot;<br>   aiplatformpb &quot;cloud.google.com/go/aiplatform/apiv1/aiplatformpb&quot;<br>   &quot;google.golang.org/api/option&quot;<br>   &quot;google.golang.org/protobuf/types/known/structpb&quot;<br>)<br><br>const INPUT = &quot;warp drive&quot; // Input topic to generate the essay<br><br>func main() {<br>   ctx := context.Background()<br>  <br>   // As of Jul 2023, only available in us-central1<br>   c, err := aiplatform.NewPredictionClient(ctx, option.WithEndpoint(&quot;us-central1-aiplatform.googleapis.com:443&quot;))<br>   if err != nil {<br>      log.Fatalf(&quot;Error 1: %v&quot;, err)<br>   }<br>   defer c.Close()<br> <br>   params, err := structpb.NewValue(map[string]interface{}{<br>      &quot;temperature&quot;:     0.2,<br>      &quot;maxOutputTokens&quot;: 512,<br>      &quot;topK&quot;:            40,<br>      &quot;topP&quot;:            0.8,<br>   })<br>   if err != nil {<br>      log.Fatalf(&quot;Error 2: %v&quot;, err)<br>   }<br><br>   // Add input to the prompt<br>   instance, err := structpb.NewValue(map[string]interface{}{<br>      &quot;prompt&quot;: fmt.Sprintf(&quot;Create an outline for a scientific essay. Includes the maths, experimental possibilities, alternatives, benefit and risk. input: %s. output:&quot;, INPUT),<br>   })<br>   if err != nil {<br>      log.Fatalf(&quot;Error 3: %v&quot;, err)<br>   }<br>  <br>   req := &amp;aiplatformpb.PredictRequest{<br>      // Replace your-gcp-project to your GCP Project ID<br>      // Notice the model text-bison@001 at the end of the endpoint<br>      // If you want to use other model, change here<br>      Endpoint:   &quot;projects/your-gcp-project/locations/us-central1/publishers/google/models/text-bison@001&quot;,<br>      Instances:  []*structpb.Value{instance},<br>      Parameters: params,<br>   }<br>   resp, err := c.Predict(ctx, req)<br>   if err != nil {<br>      log.Fatalf(&quot;Error 4: %v&quot;, err)<br>   }<br>  <br>   respMap := resp.Predictions[0].GetStructValue().AsMap()<br>   fmt.Printf(&quot;resp: %v&quot;, respMap[&quot;content&quot;])<br>}</pre><p>Yup. That’s it!</p><p>To further explore, try PaLM for Chat <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/text-chat">chat-bison</a> for multi-turn conversation use cases. Code completion, take a look at <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/code-generation">code-bison</a>. And more Generative Model <a href="https://cloud.google.com/vertex-ai/docs/generative-ai/model-reference/overview">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf315c7fa4e1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/generative-ai-app-development-using-vertex-ai-and-golang-cf315c7fa4e1">Generative AI app development using Vertex AI and Golang</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC Service to Service on Cloud Run and Private Networking]]></title>
            <link>https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-and-private-networking-dfc40b0717c0?source=rss-aace3a9d5171------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfc40b0717c0</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <category><![CDATA[serverless-vpc-access]]></category>
            <category><![CDATA[google-cloud-run]]></category>
            <dc:creator><![CDATA[Edi Wiraya]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 09:44:42 GMT</pubDate>
            <atom:updated>2023-07-01T03:38:27.112Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 3</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*oHdvZDdfBJLdJRTH7NYY6A.png" /></figure><blockquote>This is <strong>Part 3</strong> of the article series.<br>Link to <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-132f3963d183"><strong>Part 1: gRPC service to service on Cloud Run</strong></a><br>Link to <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-b264799a7c09"><strong>Part 2: gRPC service to service on Cloud Run with Authentication</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/755/1*-ZT5bDzv-t3aAtsx4X5dsQ.png" /></figure><p><strong>Wait</strong>! I’m not interested in the story, just show me the code. <a href="https://github.com/edyw/cloudrun-grpc">https://github.com/edyw/cloudrun-grpc</a></p><pre>git clone https://github.com/edyw/cloudrun-grpc.git</pre><h3>Part 3: gRPC service to service on Cloud Run and Private Networking</h3><p>In <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-b264799a7c09"><strong>Part 2</strong></a>, we secured <em>go-contact</em> Cloud Run service with IAM Authorization, however the endpoint is still accessible from Internet because <em>go-contact</em> Cloud Run ingress is set all.</p><p>The objective is use private networking, we do not want the traffic to get out and return from the Internet. To achieve this, we set <em>go-contact</em> service ingress to internal.</p><p>In order for Cloud Run to reach another Cloud Run internally, we need a Serverless VPC Access connector to receive Cloud Run egress and route to the VPC network. The connector requires a dedicated /28 subnet for internal use.</p><p>In our case, egress from Cloud Run does not need to go to any services in the VPC network. So the traffic stay within a dedicated subnet for the connector, and route to target Cloud Run via Private Google Access (GPA). You need to enable GPA in the connector’s subnet configuration.</p><p>When creating the Serverless VPC Access connector, several firewall rules are automatically added, however you still need to application specific port in firewall rules in the VPC network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hTRaS37BLtU_a_uLM4gUkw.png" /></figure><p>With Serverless VPC Access connector, the traffic from Cloud Run can reach services in internal subnets eg. VM, GKE. However the opposite direction from services in VPC network to Cloud Run, you need to enable the subnet’s GPA.</p><blockquote><strong>Important</strong>: There are many ways, options, best practices to manage connectivity from Cloud Run to your private network, this is just one of them.</blockquote><p>Now, let’s start setting up our private networking:<br><strong>Step 3.1</strong> Configure <em>go-contact</em> service ingress to internal only<br><strong>Step 3.2</strong> Create VPC network and a subnet for Serverless VPC Access<br><strong>Step 3.3</strong> Create Serverless VPC Access connector<br><strong>Step 3.4</strong> Configure <em>go-api</em> and <em>node-api</em> to use the connector, set VPC egress to all-traffic<br><strong>Step 3.5</strong> Test end to end</p><h4><strong>Step 3.1</strong></h4><p><strong>Configure <em>go-contact</em> service ingress to internal only</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*ydNle1MW_5VfA1a0eYDpEQ.png" /></figure><p>In <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-b264799a7c09">Part 2</a>, we use deployed <em>go-contact</em> with default ingress, which allowed all traffic including Internet and internal. To restrict internal only traffic, we update the service with --ingress=internal:</p><pre>gcloud run services update go-contact \<br>  --region=${REGION}<br>  --ingress=internal</pre><p>At this stage, <em>go-contact</em> is no longer accessible by <em>go-api</em>, <em>node-api</em> or any clients from Internet.</p><h4>Step 3.2</h4><p><strong>Create VPC network and a subnet for Serverless VPC Access</strong></p><p>If you plan to use your existing VPC network, you need to add a dedicated subnet for Serverless VPC Access connector first, and enable Private Google Access (GPA) on your subnet.</p><p>For this article, I will create new VPC network <em>my-corp-net</em> and subnet <em>sva-subnet</em>:</p><pre>gcloud compute networks create my-corp-net \<br>  --subnet-mode=custom<br><br>gcloud compute networks subnets create sva-subnet \<br>  --network=my-corp-net \<br>  --range=192.168.64.0/28 \<br>  --region=${REGION} <br>  --enable-private-ip-google-access</pre><h4><strong>Step 3.3</strong></h4><p><strong>Create Serverless VPC Access connector</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/218/1*oZWZWpouULqiaQ2jNbavCg.png" /></figure><p>Let’s create the connector <em>sva-conn</em> using the new VPC network and subnet:</p><pre>gcloud compute networks vpc-access connectors create sva-conn \<br>  --region=${REGION} \<br>  --subnet=sva-subnet</pre><p>The connector is a Google Cloud managed service, internally it routes network traffic with minimum 2 VMs. You can optimize the connector with additional parameters, refer to this <a href="https://cloud.google.com/sdk/gcloud/reference/compute/networks/vpc-access/connectors/create">documentation</a>.</p><p>There will be multiple firewall rules added together with the connector, you can verify with Google Cloud Console or CLI gcloud compute networks get-effective-firewalls my-corp-net</p><h4><strong>Step 3.4</strong></h4><p><strong>Configure <em>go-api </em>and <em>node-api</em> to use the connector, set VPC egress to all-traffic</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*jQWFuTKnIbV2hjRxL9ILXw.png" /></figure><p>We have the connector ready, it can route traffic to our VPC network and to Cloud Run via GPA. Next we need to update both <em>go-api</em> and <em>node-api</em> services to use the connector <em>sva-conn</em>.</p><p>In addition, we need to set both Cloud Run VPC egress settings to route all-traffic to the connector too, by default it will route private-range-only which is private IP addresses (RFC1918) only. This is not what we want, because the address of <em>go-contact</em> service known by both services is not private IP address.</p><pre>gcloud run services update go-api \<br>  --region=asia-southeast1 \<br>  --vpc-connector=sva-conn \<br>  --vpc-egress=all-traffic</pre><h4><strong>Step 3.5</strong></h4><p><strong>Test end to end</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*mpqrJ4DrURc86gdNzViFZA.png" /></figure><p>The diagram above shows the complete flow from client (curl) all the way to <em>go-contact</em> and return the result back to the client.</p><p>Finally, let’s test this out:</p><pre>curl ${CLOUD_RUN_SERVICE_URL}/contact-auth/555-110022</pre><p>The same previous test, we expect the output: Mike F%</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfc40b0717c0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-and-private-networking-dfc40b0717c0">gRPC Service to Service on Cloud Run and Private Networking</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC Service to Service on Cloud Run with Authentication]]></title>
            <link>https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-b264799a7c09?source=rss-aace3a9d5171------2</link>
            <guid isPermaLink="false">https://medium.com/p/b264799a7c09</guid>
            <category><![CDATA[google-cloud-run]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Edi Wiraya]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 13:42:01 GMT</pubDate>
            <atom:updated>2023-06-23T09:52:13.136Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 2</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*oHdvZDdfBJLdJRTH7NYY6A.png" /></figure><blockquote>This is <strong>Part 2</strong> of the article series.</blockquote><blockquote>Link to <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-132f3963d183"><strong>Part 1: gRPC service to service on Cloud Run</strong></a><br>Link to <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-and-private-networking-dfc40b0717c0"><strong>Part 3</strong>: <strong>gRPC service to service on Cloud Run and private networking</strong></a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*bgXK9YkANR2snfZgHpfzOw.png" /></figure><p><strong>Wait</strong>! I’m not interested in the story, just show me the code. <a href="https://github.com/edyw/cloudrun-grpc">https://github.com/edyw/cloudrun-grpc</a></p><pre>git clone https://github.com/edyw/cloudrun-grpc.git</pre><h3>Part 2: gRPC service to service, with Cloud Run authentication enabled</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*LkblqPRizfJ9mJW1vdbtyg.png" /></figure><p>We want to secure gRPC service to service call, in this scenario we configure <em>go-contact </em>to authenticate and authorize both <em>go-api</em> and <em>node-api</em> services, making sure no other services or clients accessing the gRPC on <em>go-contact</em>.</p><p>Cloud Run has feature to enforce IAM users authorization, we will enable this on <em>go-contact</em> service and grant <strong>Cloud Run Invoker</strong> roles/run.invoker<br>to <em>go-api</em> and <em>node-api</em> using their IAM Service Account.</p><p>It is a security best practice to assign different Service Account to each Cloud Run, so we can selectively grant necessary access to each service.</p><p>Because calling <em>go-contact</em> gRPC service from <em>go-api</em> and <em>node-api</em> will not automatically include the credentials of the respective Cloud Run’s Service Account, we need to change the code to use gRPC and other libraries to extract the Service Account and attach it to gRPC call.</p><p>If you code half way and come here to copy/paste this part, go to <strong>Step 2.4</strong> for Go, <strong>Step 2.5</strong> for Node JS</p><p>For the rest of <strong>Part 2</strong> we will cover the these steps:</p><ul><li><strong>Step 2.1</strong> Change <em>go-contact</em> Cloud Run to enable authentication and test access</li><li><strong>Step 2.2</strong> Create Service Account for all Cloud Run services</li><li><strong>Step 2.3</strong> Grant <em>go-api</em> and <em>node-api</em> Service Account to access <em>go-contact</em> service</li><li><strong>Step 2.4</strong> Change Go code on <em>go-api </em>to add Service Account credentials</li><li><strong>Step 2.5</strong> Change Node JS code on <em>node-api</em> to add Service Account credentials</li><li><strong>Step 2.6</strong> Deploy the latest <em>go-api</em> and <em>node-api</em> with their Service Account</li><li><strong>Step 2.7 </strong>End to end test</li></ul><h4>Step 2.1</h4><p><strong>Change go-contact Cloud Run to enable authentication and test access</strong></p><p>In <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-132f3963d183"><strong>Part 1</strong></a>, we deployed Cloud Run service with --allow-unauthenticated parameter, this will add allUsers to roles/run.invoker. Let’s enable authentication by removing that IAM binding:</p><pre>// Set Project ID if you haven&#39;t done it<br>gcloud config set project ${PROJECT_ID}<br><br>gcloud run services remove-iam-policy-binding go-contact \<br>  --region=${REGION} \<br>  --member=allUsers \<br>  --role=roles/run.invoker</pre><p>Replace $REGION with your Cloud Run service region, eg. asia-southeast1. ${PROJECT_ID} is the Google Cloud project ID.</p><p>You can also do this through Google Cloud Console:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2wbhLB4S_T5Mvo3Wlx0lGQ.png" /></figure><p>If you still have <em>go-api</em> or <em>node-api</em> services from <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-132f3963d183"><strong>Part 1</strong></a>, you can test it out:</p><pre>curl ${CLOUD_RUN_SERVICE_URL}/contact/555-110022 </pre><p><em>go-api</em> should return: Service Unavailable% and <em>node-api</em> should return: {}%</p><p>Logs on the Cloud Run explains the reason, and it is expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*ZIeC1-kzPHTs1wJKENmjlA.png" /></figure><h4><strong>Step 2.2</strong></h4><p><strong>Create Service Account for all Cloud Run service</strong></p><p>In order to identify the callers, let’s create Service Accounts.</p><pre>gcloud iam service-accounts create sa-run-go-api<br>gcloud iam service-accounts create sa-run-node-api</pre><p>The Service Account is created in this format: ${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com. We will be using this naming convention as Service Account for the rest of article.</p><h4>Step 2.3</h4><p><strong>Grant <em>go-api</em> and <em>node-api</em> Service Account to access <em>go-contact</em> service</strong></p><pre>gcloud run services add-iam-policy-binding go-contact \<br>  --region=${REGION} \<br>  --member=serviceAccount:${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com \<br>  --role=roles/run.invoker</pre><p>${SA_NAME} is the Service Account name, sa-run-go-api and sa-run-node-api.</p><p>You need to do for each Service Account if you have both <em>go-api</em> and <em>node-api</em>.</p><h4>Step 2.4</h4><p><strong>Change Go code on <em>go-api </em>to add Service Account credentials</strong></p><p>We are going to create a new route to call <em>go-contact</em> with authentication, let’s name it GET /contact-auth/:phone</p><p>/go-api/<strong>main.go</strong></p><pre>...<br>func main() {<br>   r := gin.Default()<br>   r.GET(&quot;/contact/:phone&quot;, getContactHandler)<br>   r.GET(&quot;/contact-auth/:phone&quot;, getContactAuthHandler) // New route<br>   r.Run(&quot;:8081&quot;)<br>}<br>...</pre><p>The new handler function getContactAuthHandler will call the same getContact function from <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-132f3963d183"><strong>Part 1</strong></a>, but this time we need to use a context ctx with Service Account credentials.</p><p>/go-api/<strong>main.go</strong></p><pre>import {<br>   ...<br>   &quot;google.golang.org/api/idtoken&quot;<br>   grpcMetadata &quot;google.golang.org/grpc/metadata&quot;<br>   ...   <br>}<br><br>...<br>...<br><br>func getContactAuthHandler(c *gin.Context) {<br><br>   ctx, err := getAuthContext()<br>   if err != nil {<br>      log.Printf(&quot;%v&quot;, err)<br>      c.JSON(http.StatusInternalServerError, err)<br>      return<br>   }<br>  <br>   contactReply, err := getContact(c.Param(&quot;phone&quot;), ctx)<br>   if err != nil {<br>      log.Printf(&quot;%v&quot;, err)<br>      c.JSON(http.StatusInternalServerError, err)<br>   } else {<br>      log.Printf(&quot;%v&quot;, contactReply)<br>      c.JSON(http.StatusOK, contactReply)<br>   }<br>}<br><br>func getAuthContext() (context.Context, error) {<br>   ctx := context.Background()<br>   tokenSource, err := idtoken.NewTokenSource(ctx, &quot;https://&quot;+contactServerHost)<br>   if err != nil {<br>      return nil, err<br>   }<br>   token, err := tokenSource.Token()<br>   if err != nil {<br>      return nil, err<br>   }<br>   return grpcMetadata.AppendToOutgoingContext(ctx, &quot;authorization&quot;, &quot;Bearer &quot;+token.AccessToken), nil<br>  }<br><br>...<br>...</pre><p>getAuthContext() returns context with credentials from idtoken library. This library automatically gets Service Account credentials that the Cloud Run service is running, so in this case it is the credentials of sa-run-go-api@${PROJECT_ID}.iam.gserviceaccount.com, and we append it to the context as gRPC Metadata.</p><p>The rest of the process follows the same getContact function for unauthenticated version in <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-132f3963d183"><strong>Part 1</strong></a>.</p><p>For complete code: <a href="https://github.com/edyw/cloudrun-grpc">https://github.com/edyw/cloudrun-grpc</a></p><h4>Step 2.5</h4><p><strong>Change Node JS code on <em>node-api</em> to add Service Account credentials</strong></p><p>We are going to create a new route to call <em>go-contact</em> with authentication, let’s name it GET /contact-auth/:phone</p><p>/node-api/<strong>index.js</strong></p><pre>const express = require(&#39;express&#39;)<br>// import the new getContactAuthHandler we are going create next step<br>const { getContactHandler, getContactAuthHandler } = require(&#39;./contact-handler&#39;)<br><br>const app = express()<br>app.get(&#39;/contact/:phone&#39;, getContactHandler)<br>app.get(&#39;/contact-auth/:phone&#39;, getContactAuthHandler) // Add this route<br>app.listen(&#39;8082&#39;, () =&gt; {<br>    console.log(&#39;node-api listening..&#39;)<br>})</pre><p>/node-api/<strong>contact-handler.js</strong></p><pre>...<br>...<br><br>const getContactAuthHandler = async (req, res) =&gt; {<br>    // Prepare grpc metadata with Service Account credentials<br>    // from getIdTokenFromMetadataServer function<br>    var metadata = new grpc.Metadata();<br>    metadata.add(&#39;authorization&#39;, &#39;Bearer &#39; + await getIdTokenFromMetadataServer())<br><br>    // From here it is the same as Part 1, <br>    // with exception of additional metadata when calling getContact<br>    const client = new services.ContactClient(contactServerHost + &#39;:443&#39;, grpc.credentials.createSsl())<br>    const grpcReq = new messages.ContactRequest()<br>    grpcReq.setPhonenumber(req.params.phone)<br><br>    // Notice the metadata with Credentials when calling getContact<br>    client.getContact(grpcReq, metadata, (err, grpcReply) =&gt; {<br>        console.log(&#39;grpcReply: &#39; + JSON.stringify(grpcReply, &#39; &#39;, 2))<br>        res.send(grpcReply.getName())<br>    })<br>}<br><br><br>// Google Auth library fetch idtoken<br>const getIdTokenFromMetadataServer = async () =&gt; {<br>    const googleAuth = new GoogleAuth()<br>    const googleClient = await googleAuth.getClient()<br><br>    token = await googleClient.fetchIdToken(&#39;https://&#39; + contactServerHost)<br>    console.log(&#39;token: &#39; + JSON.stringify(token, &#39; &#39;, 2)) // For debug<br>    return token<br>}<br><br>module.exports = {<br>    getContactHandler,<br>    getContactAuthHandler // Export the new function <br>}</pre><p>Similar to Go version, getIdTokenFromMetadataServer uses Google Auth library to fetch idtoken which automatically identify the Service Account assigned to the Cloud Run. The token is stored to gRPC metadata variable, and pass it over to getContact gRPC call.</p><p>For complete code: <a href="https://github.com/edyw/cloudrun-grpc">https://github.com/edyw/cloudrun-grpc</a></p><h4>Step 2.6</h4><p><strong>Deploy the latest <em>go-api</em> and <em>node-api</em> with their Service Account</strong></p><p>Deploy <em>go-api</em>, execute this from main directory:</p><pre>docker build . -f ./go-api/Dockerfile --tag ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/go-api<br><br>docker push ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/go-api<br><br>gcloud run deploy go-api --image=${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/go-api \<br>  --region=${REGION} \<br>  --project=${PROJECT_ID} \<br>  --allow-unauthenticated \<br>  --port=8081 \<br>  --service-account=sa-run-go-api@${PROJECT_ID}.iam.gserviceaccount.com</pre><p>For <em>node-api</em>:</p><pre>docker build . -f ./node-api/Dockerfile --tag ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/node-api<br><br>docker push ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/node-api<br><br>gcloud run deploy node-api --image=${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/node-api \<br>  --region=${REGION} \<br>  --project=${PROJECT_ID} \<br>  --allow-unauthenticated \<br>  --port=8082 \<br>  --service-account=sa-run-node-api@${PROJECT_ID}.iam.gserviceaccount.com</pre><p>${REPO} is the Google Artifact Registry repository used to store container image. Refer to <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-132f3963d183"><strong>Part 1</strong></a> for the detail.</p><h4>Step 2.7</h4><p><strong>End to end test</strong></p><p>Final verification before testing it end to end. We check the Google Cloud Console.</p><p>Verify <em>go-contact </em>Cloud Run:</p><ul><li>Authentication: Require authentication</li><li>Permission: <strong>Cloud Run Invoker</strong> roles/run.invoker has both Service Accounts added</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4WTF3qYg0upkVNiLc0qdKg.png" /></figure><p>Verify <em>node-api</em> (do th same for<em> go-api</em>) Cloud Run:</p><ul><li>Service Account is set to sa-run-node-api@${PROJECT_ID}.iam.gserviceaccount.com</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pPBLaN4ZXsSHA_IYivEmnw.png" /></figure><p>Test the service using <em>go-api</em> or <em>node-api</em> Cloud Run Service URL with Service Account credentials:</p><pre>curl ${CLOUD_RUN_SERVICE_URL}/contact-auth/555-110022</pre><p>You should get: Mike F%</p><p>Test without Service Account credentials:</p><pre>curl ${CLOUD_RUN_SERVICE_URL}/contact/555-110022</pre><p>You should get: Service Unavailable% or {}%</p><p>Hooray!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b264799a7c09" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-b264799a7c09">gRPC Service to Service on Cloud Run with Authentication</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[gRPC Service to Service on Cloud Run]]></title>
            <link>https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-132f3963d183?source=rss-aace3a9d5171------2</link>
            <guid isPermaLink="false">https://medium.com/p/132f3963d183</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[grpc]]></category>
            <category><![CDATA[gcp-app-dev]]></category>
            <category><![CDATA[runcloud]]></category>
            <dc:creator><![CDATA[Edi Wiraya]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 03:13:22 GMT</pubDate>
            <atom:updated>2023-06-23T09:52:39.286Z</atom:updated>
            <content:encoded><![CDATA[<h4>Part 1</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/641/1*oHdvZDdfBJLdJRTH7NYY6A.png" /></figure><p>Service to service calls are common in the microservice world, some prefer REST others opt for gRPC. Both have advantages and disadvantages, but we won’t cover the comparison in this article. The focus is on <a href="https://grpc.io/">gRPC</a> implementation between services, how to deploy on <a href="https://cloud.google.com/run">Google Cloud Run</a>, leverage Google Cloud authentication feature, and private networking considerations.</p><p>This is a series of articles with 3 parts. Part 1 is a simple scenario, a good starting point to learn gRPC, get your hands dirty to code in <a href="https://go.dev/">Go</a> (and <a href="https://nodejs.org/en">Node JS</a>), and deploy to Cloud Run. Securing the service to service call with authentication using IAM authorization is the second part, and the last one is private networking to keep the network traffic internally in your VPC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*jR4qEiL-zU44vspAW0TJ-Q.png" /></figure><blockquote>Link to <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-b264799a7c09"><strong>Part 2: gRPC service to service on Cloud Run with Authentication</strong></a><br>Link to <a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-and-private-networking-dfc40b0717c0"><strong>Part 3</strong>: <strong>gRPC service to service on Cloud Run and private networking</strong></a></blockquote><p><strong>Wait</strong>! I’m not interested in the story, just show me the code. <a href="https://github.com/edyw/cloudrun-grpc">https://github.com/edyw/cloudrun-grpc</a></p><pre>git clone https://github.com/edyw/cloudrun-grpc.git</pre><h3>Part 1: gRPC service to service, open to Internet, SSL enabled, http/2, no authentication</h3><h4>Prerequisite:</h4><ul><li><a href="https://grpc.io/docs/protoc-installation/">Protocol Buffer Compiler</a> for generating protocol buffer and gRPC Go codes</li><li><a href="https://cloud.google.com/sdk/docs/install-sdk">Google gcloud CLI</a> and <a href="https://cloud.google.com/free">GCP account</a> for deploying Cloud Run</li><li><a href="https://docs.docker.com/get-docker/">Docker</a> for building container image</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/0*-iilXt1Y1jNrm3Ep" /></figure><p>Client calls Service A using http GET, Service A passes the request to Service B via gRPC. This is a simple implementation with no authentication, and both services are open to the Internet. The aim is to have a working service to service gRPC deployed to Cloud Run. Let’s go deeper to the next level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/0*qSaTL9NoDpSEC_lh" /></figure><p>Service A is implemented as go-api service, this is a Cloud Run service name as well as the directory used in the source code. go-api is a http server with GET /contact/:phone, it uses :phone parameter to construct gRPC request to Service B. Service B is implemented as go-contact service, it exposes data as defined in <strong>contact.proto</strong> and has remote procedure call GetContact.</p><p>We will go through these steps:<br><strong>Step 1.1</strong> Create <strong>contact.proto</strong> &amp; generate Go Protocol Buffer and gRPC files<br><strong>Step 1.2</strong> Develop <em>go-contact</em> (Service B) service<br><strong>Step 1.3</strong> Develop <em>go-api</em> (Service A) service<br><strong>Step 1.4</strong> Optional: Local test<br><strong>Step 1.5</strong> Configure and deploy to Cloud Run<br><strong>Step 1.6</strong> Test Cloud Run deployment</p><h4>Step 1.1</h4><p><strong>Create contact.proto file and generate Go Protocol Buffer and gRPC files</strong></p><p>/proto/<strong>contact.proto</strong></p><pre>syntax = &quot;proto3&quot;;<br><br>option go_package = &quot;cloudrun-grpc/go-contact/proto/contactpb&quot;;<br><br>package contact;<br><br>service Contact {<br>    rpc GetContact (ContactRequest) returns (ContactReply) {}<br>}<br><br>message ContactRequest {<br>    string phoneNumber = 1;<br>}<br><br>message ContactReply {<br>    string name = 1;<br>}</pre><p>A message ContactRequest has phone number as input, and returning messageContactReply with a name as output. GetContact is a remote procedure defined as part of Contact service.</p><p>We use the <a href="https://grpc.io/docs/protoc-installation/">Protocol Buffer Compiler</a> to generate Go pb and grpc codes to a new directory /go-contact/proto. /go-contact is the directory we will use later to develop the <em>go-contact</em>.</p><p>Execute this at /proto directory:</p><pre>protoc \<br>    --go_out=../go-contact/proto --go_opt=paths=source_relative \<br>    --go-grpc_out=../go-contact/proto --go-grpc_opt=paths=source_relative \<br>    contact.proto</pre><p>You should have 2 files generated:</p><p>/go-contact/proto/<strong>contact_grpc.pb.go</strong><br>/go-contact/proto/<strong>contact.pb.go</strong></p><h4>Step 1.2</h4><p><strong>Develop go-contact (Service B) service</strong></p><p>Create a <strong>go.mod</strong> file:</p><p>/<strong>go.mod</strong></p><pre>module cloudrun-grpc<br><br>go 1.20<br><br>require (<br>   github.com/gin-gonic/gin v1.9.1<br>   google.golang.org/api v0.125.0<br>   google.golang.org/grpc v1.55.0<br>   google.golang.org/protobuf v1.30.0<br>)</pre><p>Download dependencies:</p><pre>go mod download<br>go mod tidy</pre><p>Let’s write go-contact gRPC service</p><p>/go-contact/<strong>main.go</strong></p><pre>package main<br><br>import (<br>   contactpb &quot;cloudrun-grpc/go-contact/proto&quot;<br>   &quot;context&quot;<br>   &quot;fmt&quot;<br>   &quot;log&quot;<br>   &quot;net&quot;<br>  <br>   &quot;google.golang.org/grpc&quot;<br>)<br><br>var data = map[string]string{<br>   &quot;555-110022&quot;: &quot;Mike F&quot;,<br>   &quot;555-220033&quot;: &quot;Rob U&quot;,<br>   &quot;555-330044&quot;: &quot;Tanya C&quot;,<br>}<br><br>type ContactServer struct {<br>   contactpb.UnimplementedContactServer<br>}<br><br>func (s *ContactServer) GetContact(ctx context.Context, req *contactpb.ContactRequest) (*contactpb.ContactReply, error) {<br>   return &amp;contactpb.ContactReply{<br>      Name: data[req.GetPhoneNumber()],<br>   }, nil<br>}<br><br>func main() {<br>   l, err := net.Listen(&quot;tcp&quot;, fmt.Sprintf(&quot;:%d&quot;, 8080))<br>   if err != nil {<br>      log.Fatalf(&quot;%v&quot;, err) <br>   }<br>   s := grpc.NewServer()<br>   contactpb.RegisterContactServer(s, &amp;ContactServer{})<br>   log.Printf(&quot;ContactServer tcp/%v&quot;, l.Addr())<br>   if err := s.Serve(l); err != nil {<br>      log.Fatalf(&quot;%v&quot;, err)<br>   }<br>}</pre><p>GetContact returns ContactReply using a map[string]string to lookup the phone number as key, and return the name.</p><h4>Step 1.3</h4><p><strong>Develop go-api (Service A) service</strong></p><p>/go-api/<strong>main.go</strong></p><pre>package main<br><br>import (<br>   contactpb &quot;cloudrun-grpc/go-contact/proto&quot;<br>   &quot;context&quot;<br>   &quot;crypto/tls&quot;<br>   &quot;crypto/x509&quot;<br>   &quot;net/http&quot;<br>  <br>   &quot;log&quot;<br>  <br>   &quot;github.com/gin-gonic/gin&quot;<br>   &quot;google.golang.org/grpc&quot;<br>   &quot;google.golang.org/grpc/credentials&quot;<br>)<br><br>// TODO: After Cloud Run Service B deployed, replace this with its host name<br>const contactServerHost = &quot;replace-this-with-service-B-cloud-run-host&quot;<br><br>type ContactServer struct {<br>   contactpb.UnimplementedContactServer<br>}<br><br>func main() {<br>   r := gin.Default()<br>   r.GET(&quot;/contact/:phone&quot;, getContactHandler)<br>   r.Run(&quot;:8081&quot;)<br>}<br><br>func getContactHandler(c *gin.Context) {<br>   contactReply, err := getContact(c.Param(&quot;phone&quot;), context.Background())<br>   if err != nil {<br>      log.Printf(&quot;%v&quot;, err)<br>      c.JSON(http.StatusInternalServerError, err)<br>   } else {<br>      log.Printf(&quot;%v&quot;, contactReply)<br>      c.JSON(http.StatusOK, contactReply)<br>   }<br>}<br><br>func getContact(phone string, ctx context.Context) (*contactpb.ContactReply, error) {<br>   addr := contactServerHost + &quot;:443&quot;<br>  <br>   systemRoots, err := x509.SystemCertPool()<br>   if err != nil {<br>      return nil, err<br>   }<br>   cred := credentials.NewTLS(&amp;tls.Config{<br>      RootCAs: systemRoots,<br>   })<br>  <br>   // Initialize client connections outside handler in your implementation<br>   g, err := grpc.Dial(addr, grpc.WithAuthority(contactServerHost), grpc.WithTransportCredentials(cred))<br>   if err != nil {<br>      return nil, err<br>   }<br>   defer g.Close()<br>  <br>   cc := contactpb.NewContactClient(g)<br>  <br>   contactRequest := &amp;contactpb.ContactRequest{<br>      PhoneNumber: phone,<br>   }<br>   contactReply, err := cc.GetContact(ctx, contactRequest)<br>   if err != nil {<br>      return nil, err<br>   }<br>   return contactReply, nil<br>}</pre><p>main function is a http server to serve route /contact/:phone with handler function getContactHandler. Parameter :phone is passed to getContact along with the context.</p><p>Since TLS is by default enabled in Cloud Run, we need to create TLS configuration. If you come to this article to seek a quick copy paste SSL/TLS part, this is the snippet section.</p><pre>   ...<br>   systemRoots, err := x509.SystemCertPool()<br>   if err != nil {<br>      ...<br>   }<br>   cred := credentials.NewTLS(&amp;tls.Config{<br>      RootCAs: systemRoots,<br>   })<br>  <br>   g, err := grpc.Dial(addr, grpc.WithAuthority(contactServerHost), grpc.WithTransportCredentials(cred))<br>   ...</pre><p>Next we import go-contact/proto as contactpb and create the client using grpc client connection. Use the same contactpb to construct ContactRequest with the phone number to execute the remote procedure call.</p><blockquote><strong>Important</strong>: This is not a production grade code, nor best practice in coding. You should move out the client connection out and manage it elegantly across the service.</blockquote><h4>Step 1.4</h4><p><strong>Optional: Local test</strong></p><p>Run both services on your terminal. Temporarily change contactServerHost=&quot;localhost:8080&quot; and addr := contactServerHost + “:8080” for <em>go-api.</em></p><p><em>go-contact</em> listens to port 8080, and <em>go-api</em> listens to port 8081, you change change them as needed.</p><p>To test locally:</p><pre>curl localhost:8081/contact/555-110022</pre><p>If everything is going well, you should get the output: Mike F%</p><h4>Step 1.5</h4><p><strong>Configure and deploy to Cloud Run</strong></p><p>We need <strong>Dockerfile</strong> for both <em>go-contact</em> and <em>go-api</em></p><p>/go-contact/<strong>Dockerfile</strong></p><pre>FROM golang:1.20 as build<br><br>WORKDIR /app<br>COPY . ./<br>RUN go mod download<br>WORKDIR /app/go-contact<br><br>RUN CGO_ENABLED=0 GOARCH=amd64 go build -mod=readonly -v -o /app/server<br><br>FROM gcr.io/distroless/static:nonroot as runtime<br><br>COPY --chown=nonroot:nonroot --from=build /app/server /server<br><br>ENTRYPOINT [&quot;/server&quot;, &quot;-alsologtostderr&quot;]</pre><p>/go-api/<strong>Dockerfile</strong></p><pre>FROM golang:1.20 as build<br><br>WORKDIR /app<br>COPY . ./<br>WORKDIR /app/go-api<br>RUN go mod download<br><br>RUN CGO_ENABLED=0 GOARCH=amd64 go build -mod=readonly -v -o /app/server<br><br>FROM gcr.io/distroless/static:nonroot as runtime<br><br>COPY --chown=nonroot:nonroot --from=build /app/server /server<br>ENTRYPOINT [&quot;/server&quot;, &quot;-alsologtostderr&quot;]</pre><p>To set up your project using gcloud, replace ${PROJECT_ID} with your GCP Project ID:</p><pre>gcloud projects create ${PROJECT_ID}<br>gcloud config set project ${PROJECT_ID}</pre><p>Enable Cloud Run, Artifact Registry services:</p><pre>gcloud services enable run.googleapis.com<br>gcloud services enable artifactregistry.googleapis.com</pre><p>Cloud Run deployment requires image from Google Artifact Registry. We use Docker to build the image locally, push to Artifact Registry and use gcloud to deploy to Cloud Run using the Artifact Registry repository.</p><p>Create Artifact Registry repository:</p><pre>gcloud artifacts repositories create ${REPO} \<br>  --repository-format=docker \<br>  --location=${REGION}</pre><p>To deploy <em>go-contact</em>, execute the following commands from main directory.</p><pre>docker build . -f ./go-contact/Dockerfile --tag ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/go-contact<br><br>docker push ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/go-contact<br><br>gcloud run deploy go-contact --image=${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/go-contact \<br>--region=${REGION} \<br>--project=${PROJECT_ID} \<br>--allow-unauthenticated \<br>--use-http2</pre><p>Set the environment variables:<br>* PROJECT_ID: Google Cloud Project ID<br>* REGION: Region where you want to deploy Cloud Run. eg. asia-southeast1<br>* REPO: Google Artifact Registry Repository name</p><blockquote><strong>Important</strong>: For production deployment, create a Service Account for each Cloud Run service, and follow the least privileges principles.</blockquote><p>Once you have successfully deployed <em>go-contact</em> service, use the Cloud Run Service URL to replace contactServerHost=.. value in <em>go-api</em> /go-api/<strong>main.go</strong>. Set the addr port back to 8081 if you change it during the local test.</p><p>To deploy <em>go-api</em>, go to main directory and run:</p><pre>docker build . -f ./go-api/Dockerfile --tag ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/go-api<br><br>docker push ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/go-api<br><br>gcloud run deploy go-api --image=${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/go-api \<br>--region=${REGION} \<br>--project=${PROJECT_ID} \<br>--allow-unauthenticated \<br>--port=8081 </pre><p>You should have Cloud Run Service URL when it is successfully deployed.</p><h4>Step 1.6</h4><p><strong>Test Cloud Run deployment</strong></p><pre>curl ${CLOUD_RUN_SERVICE_URL}/contact/555-110022</pre><p>The output: Mike F%</p><p>Congratulations! You just deployed gRPC service to service on Cloud Run.</p><p>Up next: <br><a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-b264799a7c09"><strong>Part 2</strong></a> to explore how to secure your service with authentication.<br>Or you can continue with <strong>Part 1 Bonus</strong> to create Node JS version of Service A.</p><h3>Part 1 Bonus: Node JS to call go-contact</h3><h4>Prerequisite:</h4><ul><li>Protocol Buffer Compiler for Node JS: npm install -g grpc-tools</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*w0qMYClkuZx-YxRugOBuuA.png" /></figure><p>Let’s tweak Part 1 a little bit, we add another Cloud Run service called <em>node-api</em> (Service A1), it has the same feature as <em>go-api</em> (Service A) but this written in JavaScript.</p><h4>Step B.1</h4><p><strong>Setup Node JS</strong></p><p>Create new directory /node-api and generate <strong>package.json</strong> file using npm init. Download dependencies by running npm install at /node-api directory:</p><pre>npm install @grpc/grpc-js express google-auth-library google-protobuf</pre><h4>Step B.2</h4><p><strong>Generate Node JS Protocol Buffer and gRPC files</strong></p><p>Use the same /proto/<strong>contact.proto</strong> file to generate pb and grpc files for node. Run this from /proto directory:</p><pre>grpc_tools_node_protoc \<br>    --js_out=import_style=commonjs,binary:../node-api/proto \<br>    --grpc_out=grpc_js:../node-api/proto \<br>    contact.proto</pre><p>You should have these 2 files generated:<br>/node-api/proto/<strong>contact_grpc_pb.js</strong><br>/node-api/proto/<strong>contact_pb.js</strong></p><h4>Step B.3</h4><p><strong>Develop node-api (Service A1) service</strong></p><p>/node-api/<strong>index.js</strong></p><pre>const express = require(&#39;express&#39;)<br>const { getContactHandler } = require(&#39;./contact-handler&#39;)<br><br>const app = express()<br>app.get(&#39;/contact/:phone&#39;, getContactHandler)<br>app.listen(&#39;8082&#39;, () =&gt; {<br>    console.log(&#39;node-api listening..&#39;)<br>})</pre><p>/node-api/<strong>contact-handler.js</strong></p><pre>const grpc = require(&#39;@grpc/grpc-js&#39;)<br>const messages = require(&#39;./proto/contact_pb&#39;)<br>const services = require(&#39;./proto/contact_grpc_pb&#39;)<br><br>//TODO: Replace with go-contact Cloud Run Service URL<br>const contactServerHost = &#39;replace-with-go-contact-cloud-run-service-url&#39;<br><br>const getContactHandler = async (req, res) =&gt; {<br>    // Initialize client connections outside handler in your implementation<br>    const client = new services.ContactClient(contactServerHost + &#39;:443&#39;, grpc.credentials.createSsl())<br>    const grpcReq = new messages.ContactRequest()<br>    grpcReq.setPhonenumber(req.params.phone)<br><br>    client.getContact(grpcReq, (err, grpcReply) =&gt; {<br>        console.log(&#39;grpcReply: &#39; + JSON.stringify(grpcReply, &#39; &#39;, 2))<br>        res.send(grpcReply.getName())<br>    })<br>}<br><br>module.exports = {<br>    getContactHandler<br>}</pre><p>Make sure to replace contactServerHost with <em>go-contact</em> Cloud Run Service URL</p><p>/node-api/<strong>Dockerfile</strong></p><pre>FROM node:18-alpine<br><br>WORKDIR /app<br>COPY ./node-api/package*.json ./<br>RUN npm install<br>COPY ./node-api/. .<br><br>ENTRYPOINT [&quot;node&quot;, &quot;index.js&quot;]</pre><h4>Step B.4</h4><p><strong>Deploy and test node-api service</strong></p><p>From main directory execute:</p><pre>docker build . -f ./node-api/Dockerfile --tag ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/node-api<br><br>docker push ${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/node-api<br><br>gcloud run deploy node-api --image=${REGION}-docker.pkg.dev/${PROJECT_ID}/${REPO}/node-api \<br>--region=${REGION} \<br>--project=${PROJECT_ID} \<br>--allow-unauthenticated \<br>--port=8082</pre><p>Test the service using <em>node-api</em> Cloud Run Service URL</p><pre>curl ${CLOUD_RUN_SERVICE_URL}/contact/555-110022</pre><p>The same as <em>go-api</em>, this <em>node-api</em> service should return: Mike F%</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=132f3963d183" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/grpc-service-to-service-on-cloud-run-132f3963d183">gRPC Service to Service on Cloud Run</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Evaluating your GCP resource realtime]]></title>
            <link>https://medium.com/google-cloud/evaluating-your-gcp-resource-realtime-57a0f25d4587?source=rss-aace3a9d5171------2</link>
            <guid isPermaLink="false">https://medium.com/p/57a0f25d4587</guid>
            <category><![CDATA[cloud-compliance]]></category>
            <category><![CDATA[config-validator]]></category>
            <category><![CDATA[asset-inventory]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[policy-library]]></category>
            <dc:creator><![CDATA[Edi Wiraya]]></dc:creator>
            <pubDate>Wed, 03 May 2023 09:15:08 GMT</pubDate>
            <atom:updated>2023-06-28T06:19:20.226Z</atom:updated>
            <content:encoded><![CDATA[<h4>Cloud Native Compliance as Code</h4><h4>How to build a service to validate GCP resource from CAI Feed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5CC55v-svXa7kgWPYKay5w.png" /></figure><p>There are many ways to enforce cloud infrastructure compliance, Preventive Control targets Infrastructure as Code (IaC) CI/CD pipeline before it gets applied, this is good to stop upfront misconfigurations. <a href="https://medium.com/google-cloud/open-policy-agent-evaluate-infrastructure-score-8cdf13c7cc46"><strong>Open Policy Agent Evaluate Infrastructure Score</strong></a> is a good example.</p><p>Detective Control validates the resource after the changes are made. Why do we need this? Because there are situations when manual or external changes remain undetected if we only scan the IaC.</p><p>This article focuses on building <strong>Resource Validation</strong> <strong>service</strong>, a realtime Detective Control validator using Go library <a href="https://github.com/GoogleCloudPlatform/config-validator"><em>Config Validator</em></a> on <a href="https://cloud.google.com/run"><em>Cloud Run</em></a>.</p><p><a href="https://cloud.google.com/asset-inventory/docs/monitoring-asset-changes"><em>Cloud Asset Inventory Feed</em></a><em> (CAI Feed)</em> is used to detect resource changes and send them to <strong>Resource Validation service</strong> via <a href="https://cloud.google.com/pubsub/docs/overview"><em>Pub/Sub</em></a>. The following diagram shows the high level flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n6EBVg4OsObWl2EUlitEXw.png" /></figure><blockquote>If you just need to evaluate your existing GCP resources once, no continuous detection is required, consider a batch detective control approach from this article <a href="https://medium.com/google-cloud/evaluating-your-existing-gcp-resources-810ef901ed40"><em>Evaluating your existing GCP resources</em>.</a></blockquote><h3>Detecting resource change</h3><p><em>CAI Feed</em> is an asset monitoring with feature to notify GCP resource change to <em>Pub/Sub</em>.</p><p>Before configuring <em>CAI Feed</em>, create a <em>Pub/Sub Topic</em> first, you can create its <em>Push Subscription</em> later when you have the <strong>Resource Validation service</strong> on <em>Cloud Run</em> is ready.</p><p>Plan for what type of asset you want to monitor, generally for policy validation you want to monitor all assets. To create feed for all asset types:</p><pre>gcloud asset feeds create cai_feed_all \<br>  --project=${PROJECT_ID} \<br>  --content-type=resource \<br>  --asset-types=&quot;.*.googleapis.com.*&quot; \<br>  --pubsub-topic=&quot;projects/${PROJECT_ID}/topics/${PUBSUB_TOPIC}&quot;</pre><p>Replace ${…} with your <em>Project ID,</em> and <em>Pub/Sub Topic</em> you created ealier. At this stage, <em>Pub/Sub Topic</em> will receive the information when there is GCP resource change. Let’s create the validation service.</p><h3>Resource Validation service</h3><p>The purpose of this service is to evaluate your assets against <a href="https://github.com/GoogleCloudPlatform/policy-library"><em>Policy Library</em></a>. Reuse your <em>Policy Library</em> if you already implemented it for Preventive Control.</p><p>This service is designed to validate asset change detected by <em>CAI Feed</em>, and you can expand it for bulk assets validation but we won’t cover that in this article.</p><p>If you just want to test the service without going through the nitty gritty, skip to <strong>Deploying to Cloud Run</strong> or <strong>Testing on</strong> <strong>Local Machine</strong> or simply checking out the code <a href="https://github.com/edyw/gcp-resource-validator">here</a>.</p><h4>Design overview</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7w_EQvp_FeRQIBfpa5NHUQ.png" /></figure><p>Service initialization is started with a typical HTTP server and configured to listen to port 8080 as default <em>Cloud Run</em> serving port. <em>Policy Library</em> which consists of policy constraint, template, and rego files is loaded to memory during this initialization.</p><p>When the service is ready, it routes HTTP POST requests receving <em>Pub/Sub Message</em> format from the Push Subscription. Data payload in P<em>ub/Sub Message</em> is base64 encoded, and the structure is CAI <a href="https://cloud.google.com/asset-inventory/docs/monitoring-asset-changes#receiving_updates"><em>Temporal Asset</em></a>. It contains <a href="https://cloud.google.com/asset-inventory/docs/reference/rest/v1/Asset"><em>Asset</em></a><em> </em>and<em> PriorAsset</em>, we only need Asset which has the latest resource attributes to be evaluated.</p><p><em>Config Validator</em> is Go library to evaluates the GCP resources against the <em>Policy Library</em>, it accepts Asset as input and Asset Violations as output. Unfortunately the Asset required for <em>Config Validator </em>input, is not the same as CAI Asset, therefore we need to map necessary attributes before we can execute the evaluation.</p><p>At the of the process, you can choose to stream asset violations to console or persist it somewhere else eg. database.</p><h4>Coding — step by step</h4><p>Let’s deep dive into the code, starting with go.mod in your main directory.</p><p><strong><em>go.mod</em></strong></p><pre>module gcp-resource-validator<br><br>go 1.20<br><br>// Prevent otel dependencies from getting out of sync.<br>// Cannot be upgraded until k8s.io/component-base uses a more recent version of<br>// opentelemetry.<br>replace (<br>    cloud.google.com/go/asset =&gt; cloud.google.com/go/asset v1.11.0<br>    go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp =&gt; go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.20.0<br>    go.opentelemetry.io/otel =&gt; go.opentelemetry.io/otel v0.20.0<br>    go.opentelemetry.io/otel/metric =&gt; go.opentelemetry.io/otel/metric v0.20.0<br>    go.opentelemetry.io/otel/sdk =&gt; go.opentelemetry.io/otel/sdk v0.20.0<br>    go.opentelemetry.io/otel/trace =&gt; go.opentelemetry.io/otel/trace v0.20.0<br>    go.opentelemetry.io/proto/otlp =&gt; go.opentelemetry.io/proto/otlp v0.7.0<br>)<br><br>replace (<br>    cloud.google.com/go/asset =&gt; cloud.google.com/go/asset v1.11.0<br>)<br><br>require (<br>    cloud.google.com/go/asset v1.12.0<br>    cloud.google.com/go/pubsub v1.30.0<br>    github.com/GoogleCloudPlatform/config-validator v0.0.0-20230328162739-ff3a6b2846d9<br>    github.com/gin-gonic/gin v1.9.0<br>    google.golang.org/protobuf v1.30.0<br>)</pre><blockquote><strong>Note</strong>: as of April 2023 Config Validator must use some older opentelemetry and cloud asset dependencies. To overcome this, use ‘replace’ in your go.mod</blockquote><p>We have go.mod ready, to download dependencies:</p><pre>go mod download</pre><p>I use <a href="https://github.com/gin-gonic/gin">gin</a>, you can use your choice of http server. First initialize the server to listen to port 8080 and a POST route /validator. Create a new Validator to load <em>Policy Library</em> files. It is hardcoded and will be statically built to the container image, you should load the files from <em>Cloud Storage buckets</em> for production implementation.</p><p><strong><em>main.go</em></strong></p><pre>package main<br><br>import (<br>        &quot;log&quot;<br>        &quot;github.com/gin-gonic/gin&quot;<br>)<br><br>func main() {<br>        router := gin.Default()<br><br>        validator, err := NewValidator()<br>        if err != nil {<br>                log.Fatal(err)<br>        }<br><br>        router.POST(&quot;/validator&quot;)  // No handler yet<br>        router.Run(&quot;:8080&quot;)<br>}</pre><p><strong><em>validator.go</em></strong></p><pre>package main<br><br>import (<br>        &quot;log&quot;<br><br>        &quot;github.com/GoogleCloudPlatform/config-validator/pkg/gcv&quot;<br>)<br><br>type Validator struct {<br>        gcv *gcv.Validator<br>}<br><br>func NewValidator() (*Validator, error) {<br>        cv, err := gcv.NewValidator([]string{&quot;./policy-library/policies&quot;}, &quot;./policy-library/lib&quot;)<br>        if err != nil {<br>                return nil, err<br>        }<br>        return &amp;Validator{<br>                gcv: cv,<br>        }, nil<br>}</pre><p>If you have existing <em>Policy Library</em> files, copy the constraints and templates to ./policy-library/policies and the library files to ./policy-library/lib.</p><p>If you start new <em>Policy Library</em>, you can clone Policy Library from github:</p><pre>git clone https://github.com/GoogleCloudPlatform/policy-library</pre><p>Policy Library from github has no constraint added, we can create ./policy-library/constraints/gcp_storage_location.yamlto test the service later. This constraint will report violation with high severity if you have <em>Cloud Storage bucket</em> created not in allowlist, in this case asia-southeast1. This is optional step.</p><p><strong><em>gcp_storage_location.yaml</em></strong></p><pre>apiVersion: constraints.gatekeeper.sh/v1alpha1<br>kind: GCPStorageLocationConstraintV1<br>metadata:<br>  name: allow_some_storage_location<br>  annotations:<br>    description: Checks Cloud Storage bucket locations against allowed or disallowed<br>      locations.<br>    bundles.validator.forsetisecurity.org/healthcare-baseline-v1: security<br>spec:<br>  severity: high<br>  match:<br>    ancestries:<br>    - &quot;organizations/**&quot;<br>  parameters:<br>    mode: &quot;allowlist&quot;<br>    locations:<br>    - asia-southeast1<br>    exemptions: []</pre><p>The directory structure will look like this:</p><pre>go.mod<br>go.sum<br>main.go<br>validator.go<br>policy-library<br> +- policies<br> |   +- constraints<br> |   |   |- gcp_storage_location.yaml<br> |   |   |- ...<br> |   +- templates <br> |       |- ***.yaml<br> |       |- ...<br> +- lib<br>     |- ***.rego<br>     |- ...</pre><p>Now we have the service initialization part ready. You should be able to test running the server:</p><pre>go run gcp-resource-validator</pre><p>If everything is going well you will notice this at the console output last line:</p><pre>...<br>[GIN-debug] Listening and serving HTTP on :8080</pre><p>Ctrl-C to terminate the server.</p><blockquote><strong>Note</strong>: as of April 2023 if you use sample Policy Library here, there will be some warning message pertaining deprecated v1alpha1 constraint templates. You can safely ignore this.</blockquote><p>Next let’s add the route handler.</p><p><strong><em>main.go</em></strong></p><pre>        …<br>        router.POST(&quot;/validator&quot;, validator.Handler)<br>        …</pre><p><strong><em>validator.go</em></strong></p><pre>...<br><br>import (<br>        &quot;context&quot;<br>  <br>        ...<br>        ...<br>    <br><br>        &quot;cloud.google.com/go/asset/apiv1/assetpb&quot;<br>        &quot;cloud.google.com/go/pubsub&quot;<br>        cvassetpb &quot;github.com/GoogleCloudPlatform/config-validator/pkg/api/validator&quot;<br>        libCvAsset &quot;github.com/GoogleCloudPlatform/config-validator/pkg/asset&quot;<br>        &quot;github.com/gin-gonic/gin&quot;<br>        &quot;google.golang.org/protobuf/encoding/protojson&quot;<br>)<br><br>type pubsubMsg struct {<br>        Message pubsub.Message<br>}<br><br>...<br>...<br><br><br>func (v *Validator) Handler(c *gin.Context) {<br>        var msg pubsubMsg<br>        if err := c.ShouldBindJSON(&amp;msg); err != nil {<br>                log.Println(err)<br>                return<br>        }<br><br>        var tprAsset assetpb.TemporalAsset<br>        protoUm := protojson.UnmarshalOptions{<br>                AllowPartial:   true,<br>                DiscardUnknown: true,<br>        }<br><br>        if err := protoUm.Unmarshal([]byte(msg.Message.Data), &amp;tprAsset); err != nil {<br>                log.Println(err)<br>                return<br>        }<br><br>        cvAsset := &amp;cvassetpb.Asset{<br>                Name:         tprAsset.Asset.Name,<br>                AssetType:    tprAsset.Asset.AssetType,<br>                AncestryPath: libCvAsset.AncestryPath(tprAsset.Asset.Ancestors),<br>                Resource:     tprAsset.Asset.Resource,<br>                IamPolicy:    tprAsset.Asset.IamPolicy,<br>                OrgPolicy:    tprAsset.Asset.OrgPolicy,<br>        }<br><br>        log.Printf(&quot;Validating asset: %s\n&quot;, cvAsset.Name)<br>        violations, err := v.gcv.ReviewAsset(context.Background(), cvAsset)<br>        if err != nil {<br>                log.Println(err)<br>        }<br><br>        // process the output result here<br>        ...<br>        ... <br><br>}</pre><p>pubsubMsg wraps Google pubsub.Message, we use this struct to bind to HTTP Post request data, and extract the payload. <em>Unmarshal</em> the decoded payload to assetpb.TemporalAsset, and use its Asset (not PriorAsset) to map to <em>ConfigValidator</em> Asset. We are ready to execute ReviewAsset at this stage, and it will return list of violations as the output.</p><p>You can add final step to print the output to console, or insert to database. Complete code is available for your reference on the next section.</p><h3>Deploying to Cloud Run</h3><p>Prerequisite:</p><ul><li>Docker installed on your local machine</li><li>A repository on <em>Artifact Registry</em> or <em>Container Registry</em> on your GCP project</li><li>You have necessary access to your GCP project</li></ul><h4><strong>Clone the code</strong></h4><blockquote>The code is intended for demonstration only, not for production use.</blockquote><pre>git clone https://github.com/edyw/gcp-resource-validator.git</pre><h4><strong>Build and deploy</strong></h4><p>Build the image locally, tag and push to container repository. Replace ${…} with your setup.</p><pre>docker build --tag gcp-resource-validator .<br><br>docker tag gcp-resource-validator ${REGION}-docker.pkg.dev/${PROJECT}/${REPO_NAME}/gcp-resource-validator:latest<br>docker push ${REGION}-docker.pkg.dev/${PROJECT}/${REPO_NAME}/gcp-resource-validator:latest</pre><p>Deploy <em>Cloud Run</em> using the image from container repository.</p><pre>gcloud run deploy gcp-resource-validator \<br>--image ${REGION}-docker.pkg.dev/${PROJECT}/${REPO_NAME}/gcp-resource-validator \<br>--region=${REGION} \<br>--allow-unauthenticated \<br>--service-account=${CLOUD_RUN_SERVICE_ACCOUNT}</pre><blockquote><strong>Note</strong>: You should enable Cloud Run authentication and restrict ingress in production setup</blockquote><p>At the end of the deployment, you will have a <em>Service URL</em>: <a href="https://gcp-resource-validator-xxxxxxxxxx-as.a.run.app/">https://gcp-resource-validator-xxxxxxxxxx-as.a.run.app</a></p><h4><strong>Pub/Sub Push Subscription</strong></h4><p>Go to the <em>Pub/Sub Topic</em> created earlier, and use it to create a <em>Push Subscription</em> with the Cloud Run <em>Service URL</em> + /validator as the <em>Endpoint URL</em>.</p><h4><strong>End to end test</strong></h4><p>Trigger a change on your GCP resource to test the end to end flow. If you use the sample constraint <strong><em>gcp_storage_location.yaml, </em></strong>create a <em>Cloud Storage bucket</em> in location other than <em>asia-southeast1</em> to test the violation output. For simplicity, sample code streams the violations output to console, use <em>Cloud Logging</em> to check the result.</p><h3>Testing on Local Machine</h3><p>To test the service on your machine, follow these steps.</p><p>Clone the code and download dependencies:</p><pre>git clone https://github.com/edyw/gcp-resource-validator.git<br>go mod download</pre><p>Run the server:</p><pre>go run gcp-resource-validator</pre><p>You should see this from the server last line:</p><pre>...<br>[GIN-debug] Listening and serving HTTP on :8080</pre><p>The sample code use this constraint <strong><em>gcp_storage_location.yaml</em></strong> located in directory ./policy-library/policies/constraints/ to evaluate if the location of<em> Cloud Storage bucket</em> is in <em>allowlist</em> (<em>asia-southeast1)</em>.</p><p>To test this, use <em>TemporalAsset</em> data wrapped as <em>Pub/Sub Message </em>payload. In ./test-asset directory, <strong><em>storage_location_us_msg.json</em></strong> and <strong><em>storage_location_sg_msg.json</em></strong> are json formatted Pub/Sub Message, the <em>TemporalAsset</em> payload is base64 encoded, you can refer to <strong><em>storage_location_us.txt</em></strong> and <strong><em>storage_location_sg.txt</em></strong> for decoded version.</p><p>Let’s test <strong><em>storage_location_us_msg.json</em></strong>, open another terminal:</p><pre>curl -X POST localhost:8080/validator -d @./test-asset/storage_location_us_msg.json</pre><p>You should this output from 1st terminal:</p><pre>Validating asset: //storage.googleapis.com/bucket-test-1<br>Violation 1 (high-GCPStorageLocationConstraintV1.allow_some_storage_location): //storage.googleapis.com/bucket-test-1 is in a disallowed location.</pre><p>Next test <strong><em>storage_location_sg_msg.json</em></strong>:</p><pre>curl -X POST localhost:8080/validator -d @./test-asset/storage_location_sg_msg.json</pre><p>No violation detected, the bucket is created in <em>allowlist</em> region.</p><pre>Validating asset: //storage.googleapis.com/bucket-test-1<br>No violation detected</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57a0f25d4587" width="1" height="1" alt=""><hr><p><a href="https://medium.com/google-cloud/evaluating-your-gcp-resource-realtime-57a0f25d4587">Evaluating your GCP resource realtime</a> was originally published in <a href="https://medium.com/google-cloud">Google Cloud - Community</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>