Skip to content

Commit b0f1a32

Browse files
docs(samples): added annotate assessment sample and refactored tests. (#635)
* docs(samples): added annotate assessment sample and refactored tests. * 🦉 Updates from OwlBot See https://github.com/googleapis/repo-automation-bots/blob/main/packages/owl-bot/README.md * docs(samples): refactored variable name. Co-authored-by: Owl Bot <gcf-owl-bot[bot]@users.noreply.github.com>
1 parent 4045426 commit b0f1a32

File tree

4 files changed

+138
-23
lines changed

4 files changed

+138
-23
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
* Copyright 2021 Google LLC
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package recaptcha;
18+
19+
// [START recaptcha_enterprise_annotate_assessment]
20+
21+
import com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient;
22+
import com.google.recaptchaenterprise.v1.AnnotateAssessmentRequest;
23+
import com.google.recaptchaenterprise.v1.AnnotateAssessmentRequest.Annotation;
24+
import com.google.recaptchaenterprise.v1.AnnotateAssessmentRequest.Reason;
25+
import com.google.recaptchaenterprise.v1.AnnotateAssessmentResponse;
26+
import com.google.recaptchaenterprise.v1.AssessmentName;
27+
import java.io.IOException;
28+
29+
public class AnnotateAssessment {
30+
31+
public static void main(String[] args) throws IOException {
32+
// TODO(developer): Replace these variables before running the sample.
33+
String projectID = "project-id";
34+
String assessmentId = "assessment-id";
35+
annotateAssessment(projectID, assessmentId);
36+
}
37+
38+
/**
39+
* Pre-requisite: Create an assessment before annotating.
40+
*
41+
* <p>Annotate an assessment to provide feedback on the correctness of recaptcha prediction.
42+
*
43+
* @param projectID: GCloud Project id
44+
* @param assessmentId: Value of the 'name' field returned from the CreateAssessment call.
45+
*/
46+
public static void annotateAssessment(String projectID, String assessmentId) throws IOException {
47+
// Initialize client that will be used to send requests. This client only needs to be created
48+
// once, and can be reused for multiple requests. After completing all of your requests, call
49+
// the `client.close()` method on the client to safely
50+
// clean up any remaining background resources.
51+
try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {
52+
// Build the annotation request.
53+
// For more info on when/how to annotate, see:
54+
// https://cloud.google.com/recaptcha-enterprise/docs/annotate-assessment#when_to_annotate
55+
AnnotateAssessmentRequest annotateAssessmentRequest =
56+
AnnotateAssessmentRequest.newBuilder()
57+
.setName(AssessmentName.of(projectID, assessmentId).toString())
58+
.setAnnotation(Annotation.FRAUDULENT)
59+
.addReasons(Reason.FAILED_TWO_FACTOR)
60+
.build();
61+
62+
// Empty response is sent back.
63+
AnnotateAssessmentResponse response = client.annotateAssessment(annotateAssessmentRequest);
64+
System.out.println("Annotated response sent successfully ! " + response);
65+
}
66+
}
67+
}
68+
// [END recaptcha_enterprise_annotate_assessment]

recaptcha_enterprise/cloud-client/src/main/java/recaptcha/CreateAssessment.java

+9-4
Original file line numberDiff line numberDiff line change
@@ -89,15 +89,20 @@ public static void createAssessment(
8989
return;
9090
}
9191

92-
// Get the risk score and the reason(s).
92+
// Get the reason(s) and the risk score.
9393
// For more information on interpreting the assessment,
9494
// see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
95-
float recaptchaScore = response.getRiskAnalysis().getScore();
96-
System.out.println("The reCAPTCHA score is: " + recaptchaScore);
97-
9895
for (ClassificationReason reason : response.getRiskAnalysis().getReasonsList()) {
9996
System.out.println(reason);
10097
}
98+
99+
float recaptchaScore = response.getRiskAnalysis().getScore();
100+
System.out.println("The reCAPTCHA score is: " + recaptchaScore);
101+
102+
// Get the assessment name (id). Use this to annotate the assessment.
103+
String assessmentName = response.getName();
104+
System.out.println(
105+
"Assessment name: " + assessmentName.substring(assessmentName.lastIndexOf("/") + 1));
101106
}
102107
}
103108
}

recaptcha_enterprise/cloud-client/src/main/java/recaptcha/UpdateSiteKey.java

+1
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ public static void updateSiteKey(String projectID, String recaptchaSiteKeyID, St
6060
UpdateKeyRequest.newBuilder()
6161
.setKey(
6262
Key.newBuilder()
63+
.setDisplayName("any descriptive name for the key")
6364
.setName(KeyName.of(projectID, recaptchaSiteKeyID).toString())
6465
.setWebSettings(
6566
WebKeySettings.newBuilder()

recaptcha_enterprise/cloud-client/src/test/java/app/SnippetsIT.java

+60-19
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,12 @@
2424
import java.io.IOException;
2525
import java.io.PrintStream;
2626
import java.net.URI;
27+
import java.time.Duration;
2728
import java.util.concurrent.ExecutionException;
2829
import java.util.concurrent.TimeUnit;
2930
import java.util.concurrent.TimeoutException;
3031
import org.json.JSONException;
32+
import org.json.JSONObject;
3133
import org.junit.After;
3234
import org.junit.AfterClass;
3335
import org.junit.Assert;
@@ -47,6 +49,7 @@
4749
import org.springframework.boot.web.server.LocalServerPort;
4850
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
4951
import org.springframework.web.util.UriComponentsBuilder;
52+
import recaptcha.AnnotateAssessment;
5053

5154
@RunWith(SpringJUnit4ClassRunner.class)
5255
@EnableAutoConfiguration
@@ -55,6 +58,7 @@ public class SnippetsIT {
5558

5659
private static final String PROJECT_ID = System.getenv("GOOGLE_CLOUD_PROJECT");
5760
private static final String DOMAIN_NAME = "localhost";
61+
private static String ASSESSMENT_NAME = "";
5862
private static String RECAPTCHA_SITE_KEY_1 = "recaptcha-site-key1";
5963
private static String RECAPTCHA_SITE_KEY_2 = "recaptcha-site-key2";
6064
private static WebDriver browser;
@@ -69,7 +73,7 @@ public static void requireEnvVar(String envVarName) {
6973
}
7074

7175
@BeforeClass
72-
public static void setUp() throws IOException, InterruptedException {
76+
public static void setUp() throws IOException, InterruptedException, JSONException {
7377
requireEnvVar("GOOGLE_APPLICATION_CREDENTIALS");
7478
requireEnvVar("GOOGLE_CLOUD_PROJECT");
7579

@@ -144,11 +148,59 @@ public void testDeleteSiteKey()
144148
}
145149

146150
@Test
147-
public void testCreateAssessment() throws IOException, JSONException, InterruptedException {
151+
public void testCreateAnnotateAssessment()
152+
throws JSONException, IOException, InterruptedException {
153+
// Create an assessment.
154+
String testURL = "http://localhost:" + randomServerPort + "/";
155+
JSONObject createAssessmentResult = createAssessment(testURL);
156+
ASSESSMENT_NAME = createAssessmentResult.getString("assessmentName");
157+
// Verify that the assessment name has been modified post the assessment creation.
158+
assertThat(ASSESSMENT_NAME).isNotEmpty();
159+
160+
// Annotate the assessment.
161+
AnnotateAssessment.annotateAssessment(PROJECT_ID, ASSESSMENT_NAME);
162+
assertThat(stdOut.toString()).contains("Annotated response sent successfully ! ");
163+
}
164+
165+
public JSONObject createAssessment(String testURL)
166+
throws IOException, JSONException, InterruptedException {
167+
168+
// Setup the automated browser test and retrieve the token and action.
169+
JSONObject tokenActionPair = initiateBrowserTest(testURL);
170+
171+
// Send the token for analysis. The analysis score ranges from 0.0 to 1.0
172+
recaptcha.CreateAssessment.createAssessment(
173+
PROJECT_ID,
174+
RECAPTCHA_SITE_KEY_1,
175+
tokenActionPair.getString("token"),
176+
tokenActionPair.getString("action"));
177+
178+
// Analyse the response.
179+
String response = stdOut.toString();
180+
assertThat(response).contains("Assessment name: ");
181+
assertThat(response).contains("The reCAPTCHA score is: ");
182+
float recaptchaScore = 0;
183+
String assessmentName = "";
184+
for (String line : response.split("\n")) {
185+
if (line.contains("The reCAPTCHA score is: ")) {
186+
recaptchaScore = Float.parseFloat(substr(line));
187+
} else if (line.contains("Assessment name: ")) {
188+
assessmentName = substr(line);
189+
}
190+
}
191+
192+
// Set the score.
193+
browser.findElement(By.cssSelector("#assessment")).sendKeys(String.valueOf(recaptchaScore));
194+
return new JSONObject()
195+
.put("recaptchaScore", recaptchaScore)
196+
.put("assessmentName", assessmentName);
197+
}
198+
199+
public JSONObject initiateBrowserTest(String testURL)
200+
throws IOException, JSONException, InterruptedException {
148201
// Construct the URL to call for validating the assessment.
149-
String assessURL = "http://localhost:" + randomServerPort + "/";
150202
URI url =
151-
UriComponentsBuilder.fromUriString(assessURL)
203+
UriComponentsBuilder.fromUriString(testURL)
152204
.queryParam("recaptchaSiteKey", RECAPTCHA_SITE_KEY_1)
153205
.build()
154206
.encode()
@@ -158,7 +210,7 @@ public void testCreateAssessment() throws IOException, JSONException, Interrupte
158210

159211
// Wait until the page is loaded.
160212
JavascriptExecutor js = (JavascriptExecutor) browser;
161-
new WebDriverWait(browser, 10)
213+
new WebDriverWait(browser, Duration.ofSeconds(10))
162214
.until(webDriver -> js.executeScript("return document.readyState").equals("complete"));
163215

164216
// Pass the values to be entered.
@@ -175,21 +227,10 @@ public void testCreateAssessment() throws IOException, JSONException, Interrupte
175227
String token = element.getAttribute("data-token");
176228
String action = element.getAttribute("data-action");
177229

178-
// The obtained token must be further analyzed to get the score.
179-
float recaptchaScore = assessToken(token, action);
180-
181-
// Set the score.
182-
browser.findElement(By.cssSelector("#assessment")).sendKeys(String.valueOf(recaptchaScore));
183-
return;
230+
return new JSONObject().put("token", token).put("action", action);
184231
}
185232

186-
public float assessToken(String token, String action) throws IOException {
187-
// Send the token for analysis. The analysis score ranges from 0.0 to 1.0
188-
recaptcha.CreateAssessment.createAssessment(PROJECT_ID, RECAPTCHA_SITE_KEY_1, token, action);
189-
String response = stdOut.toString();
190-
assertThat(response).contains("The reCAPTCHA score is: ");
191-
float recaptchaScore =
192-
Float.parseFloat(response.substring(response.lastIndexOf(":") + 1).trim());
193-
return recaptchaScore;
233+
public String substr(String line) {
234+
return line.substring((line.lastIndexOf(":") + 1)).trim();
194235
}
195236
}

0 commit comments

Comments
 (0)