Search in sources :

Example 6 with Assessment

use of com.google.recaptchaenterprise.v1.Assessment in project java-recaptchaenterprise by googleapis.

the class AnnotateAssessment method annotateAssessment.

/**
 * Pre-requisite: Create an assessment before annotating.
 *
 * <p>Annotate an assessment to provide feedback on the correctness of recaptcha prediction.
 *
 * @param projectID: GCloud Project id
 * @param assessmentId: Value of the 'name' field returned from the CreateAssessment call.
 */
public static void annotateAssessment(String projectID, String assessmentId) throws IOException {
    // clean up any remaining background resources.
    try (RecaptchaEnterpriseServiceClient client = RecaptchaEnterpriseServiceClient.create()) {
        // Build the annotation request.
        // For more info on when/how to annotate, see:
        // https://cloud.google.com/recaptcha-enterprise/docs/annotate-assessment#when_to_annotate
        AnnotateAssessmentRequest annotateAssessmentRequest = AnnotateAssessmentRequest.newBuilder().setName(AssessmentName.of(projectID, assessmentId).toString()).setAnnotation(Annotation.FRAUDULENT).addReasons(Reason.FAILED_TWO_FACTOR).build();
        // Empty response is sent back.
        AnnotateAssessmentResponse response = client.annotateAssessment(annotateAssessmentRequest);
        System.out.println("Annotated response sent successfully ! " + response);
    }
}
Also used : AnnotateAssessmentRequest(com.google.recaptchaenterprise.v1.AnnotateAssessmentRequest) AnnotateAssessmentResponse(com.google.recaptchaenterprise.v1.AnnotateAssessmentResponse) RecaptchaEnterpriseServiceClient(com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient)

Example 7 with Assessment

use of com.google.recaptchaenterprise.v1.Assessment in project Signal-Server by signalapp.

the class RecaptchaClient method verify.

public boolean verify(final String input, final String ip) {
    final String[] parts = parseInputToken(input);
    final String sitekey = parts[0];
    final String expectedAction = parts[1];
    final String token = parts[2];
    Event.Builder eventBuilder = Event.newBuilder().setSiteKey(sitekey).setToken(token).setUserIpAddress(ip);
    if (expectedAction != null) {
        eventBuilder.setExpectedAction(expectedAction);
    }
    final Event event = eventBuilder.build();
    final Assessment assessment = client.createAssessment(projectPath, Assessment.newBuilder().setEvent(event).build());
    Metrics.counter(ASSESSMENTS_COUNTER_NAME, "action", String.valueOf(expectedAction), "valid", String.valueOf(assessment.getTokenProperties().getValid())).increment();
    if (assessment.getTokenProperties().getValid()) {
        final float score = assessment.getRiskAnalysis().getScore();
        final DistributionSummary.Builder distributionSummaryBuilder = DistributionSummary.builder(SCORE_DISTRIBUTION_NAME).scale(100).maximumExpectedValue(100.0d).tags("action", String.valueOf(expectedAction));
        distributionSummaryBuilder.register(Metrics.globalRegistry).record(score);
        return score >= dynamicConfigurationManager.getConfiguration().getCaptchaConfiguration().getScoreFloor().floatValue();
    } else {
        return false;
    }
}
Also used : DistributionSummary(io.micrometer.core.instrument.DistributionSummary) Assessment(com.google.recaptchaenterprise.v1.Assessment) Event(com.google.recaptchaenterprise.v1.Event)

Example 8 with Assessment

use of com.google.recaptchaenterprise.v1.Assessment in project pomocua-ogloszenia by coi-gov-pl.

the class CaptchaValidator method validate.

public boolean validate(String recaptchaResponse) {
    if (!properties.isEnabled()) {
        log.debug("Skip captcha validation. To enable change 'app.captcha.enabled' property");
        return true;
    }
    if (!responseSanityCheck(recaptchaResponse)) {
        log.warn("Response contains invalid characters");
        return false;
    }
    ProjectName projectName = ProjectName.of(properties.getGoogleCloudProjectId());
    Event event = Event.newBuilder().setSiteKey(properties.getSiteKey()).setToken(recaptchaResponse).build();
    CreateAssessmentRequest createAssessmentRequest = CreateAssessmentRequest.newBuilder().setParent(projectName.toString()).setAssessment(Assessment.newBuilder().setEvent(event).build()).build();
    Assessment response = recaptchaClient.createAssessment(createAssessmentRequest);
    if (response == null) {
        log.warn("Empty response from reCaptcha");
        return false;
    }
    // Check if the token is valid.
    if (!response.getTokenProperties().getValid()) {
        String invalidTokenReason = response.getTokenProperties().getInvalidReason().name();
        log.debug("The CreateAssessment call failed because the token was: " + invalidTokenReason);
        return false;
    }
    float score = response.getScore();
    if (score < properties.getAcceptLevel()) {
        List<String> reasons = response.getReasonsList().stream().map(classificationReason -> classificationReason.getDescriptorForType().getFullName()).collect(Collectors.toList());
        log.debug("Validation failed. Score: " + score + ". Reasons: " + String.join(", ", reasons));
        return false;
    }
    log.debug("Validation OK - score: " + score);
    return true;
}
Also used : Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) CreateAssessmentRequest(com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest) Service(org.springframework.stereotype.Service) RequiredArgsConstructor(lombok.RequiredArgsConstructor) Assessment(com.google.recaptchaenterprise.v1beta1.Assessment) RecaptchaEnterpriseServiceV1Beta1Client(com.google.cloud.recaptchaenterprise.v1beta1.RecaptchaEnterpriseServiceV1Beta1Client) ProjectName(com.google.recaptchaenterprise.v1beta1.ProjectName) Pattern(java.util.regex.Pattern) Collectors(java.util.stream.Collectors) Event(com.google.recaptchaenterprise.v1beta1.Event) StringUtils(org.springframework.util.StringUtils) ProjectName(com.google.recaptchaenterprise.v1beta1.ProjectName) Assessment(com.google.recaptchaenterprise.v1beta1.Assessment) CreateAssessmentRequest(com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest) Event(com.google.recaptchaenterprise.v1beta1.Event)

Example 9 with Assessment

use of com.google.recaptchaenterprise.v1.Assessment in project pomocua-ogloszenia by coi-gov-pl.

the class CaptchaValidatorTest method validate_whenCaptchaStatusIsSuccessAndScoreNotAccepted_expectFalse.

@Test
void validate_whenCaptchaStatusIsSuccessAndScoreNotAccepted_expectFalse() {
    // given
    String recaptcha = "anytext";
    Assessment response = createAssessmentResponse(true, 0.3F);
    when(recaptchaClient.createAssessment(any(CreateAssessmentRequest.class))).thenReturn(response);
    // when
    boolean result = captchaValidator.validate(recaptcha);
    // then
    assertAll(() -> assertThat(result).isFalse(), () -> verify(recaptchaClient, times(1)).createAssessment(any(CreateAssessmentRequest.class)));
}
Also used : Assessment(com.google.recaptchaenterprise.v1beta1.Assessment) CreateAssessmentRequest(com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest) Test(org.junit.jupiter.api.Test)

Example 10 with Assessment

use of com.google.recaptchaenterprise.v1.Assessment in project pomocua-ogloszenia by coi-gov-pl.

the class CaptchaValidatorTest method validate_whenCaptchaStatusIsSuccessAndScoreAccepted_expectTrue.

@Test
void validate_whenCaptchaStatusIsSuccessAndScoreAccepted_expectTrue() {
    // given
    String recaptcha = "anytext";
    Assessment response = createAssessmentResponse(true, 111);
    when(recaptchaClient.createAssessment(any(CreateAssessmentRequest.class))).thenReturn(response);
    // when
    boolean result = captchaValidator.validate(recaptcha);
    // then
    assertAll(() -> assertThat(result).isTrue(), () -> verify(recaptchaClient, times(1)).createAssessment(any(CreateAssessmentRequest.class)));
}
Also used : Assessment(com.google.recaptchaenterprise.v1beta1.Assessment) CreateAssessmentRequest(com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest) Test(org.junit.jupiter.api.Test)

Aggregations

Test (org.junit.Test)10 Assessment (com.google.recaptchaenterprise.v1beta1.Assessment)8 Assessment (com.google.recaptchaenterprise.v1.Assessment)6 CreateAssessmentRequest (com.google.recaptchaenterprise.v1beta1.CreateAssessmentRequest)6 InvalidArgumentException (com.google.api.gax.rpc.InvalidArgumentException)5 AbstractMessage (com.google.protobuf.AbstractMessage)5 StatusRuntimeException (io.grpc.StatusRuntimeException)5 AccountDefenderAssessment (com.google.recaptchaenterprise.v1.AccountDefenderAssessment)4 AnnotateAssessmentRequest (com.google.recaptchaenterprise.v1.AnnotateAssessmentRequest)3 CreateAssessmentRequest (com.google.recaptchaenterprise.v1.CreateAssessmentRequest)3 ProjectName (com.google.recaptchaenterprise.v1beta1.ProjectName)3 Test (org.junit.jupiter.api.Test)3 RecaptchaEnterpriseServiceClient (com.google.cloud.recaptchaenterprise.v1.RecaptchaEnterpriseServiceClient)2 ByteString (com.google.protobuf.ByteString)2 AnnotateAssessmentResponse (com.google.recaptchaenterprise.v1.AnnotateAssessmentResponse)2 AssessmentName (com.google.recaptchaenterprise.v1.AssessmentName)2 Event (com.google.recaptchaenterprise.v1.Event)2 ProjectName (com.google.recaptchaenterprise.v1.ProjectName)2 ArrayList (java.util.ArrayList)2 RecaptchaEnterpriseServiceV1Beta1Client (com.google.cloud.recaptchaenterprise.v1beta1.RecaptchaEnterpriseServiceV1Beta1Client)1