Пример #1
0
def get_metrics(project_id: str, recaptcha_site_key: str) -> None:
    """Get metrics specific to a recaptcha site key.
        E.g: score bucket count for a key or number of
        times the checkbox key failed/ passed etc.,
    Args:
    project_id: Google Cloud Project ID.
    recaptcha_site_key: Specify the site key to get metrics.
    """

    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    metrics_name = f"projects/{project_id}/keys/{recaptcha_site_key}/metrics"
    request = recaptchaenterprise_v1.GetMetricsRequest()
    request.name = metrics_name

    response = client.get_metrics(request)

    # Retrieve the metrics you want from the key.
    # If the site key is checkbox type: then use response.challenge_metrics
    # instead of response.score_metrics
    for day_metric in response.score_metrics:
        # Each 'day_metric' is in the granularity of one day.
        score_bucket_count = day_metric.overall_metrics.score_buckets
        print(score_bucket_count)

    print(
        f"Retrieved the bucket count for score based key: {recaptcha_site_key}"
    )
Пример #2
0
def create_assessment(token):
  client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

  # Set the properties of the event to be tracked.
  event = recaptchaenterprise_v1.Event()
  event.site_key = get_secret('RECAPTCHA_SECRET_KEY')
  if not event.site_key:
    return 1.0
  event.token = token

  assessment = recaptchaenterprise_v1.Assessment()
  assessment.event = event

  # Build the assessment request.
  request = recaptchaenterprise_v1.CreateAssessmentRequest()
  request.assessment = assessment
  if os.environ.get('ENV') == 'PROD':
    request.parent = 'projects/' + os.environ.get('GOOGLE_CLOUD_PROJECT')
  else:
    request.parent = 'projects/cubingusa-org'

  response = client.create_assessment(request)

  # Check if the token is valid.
  if not response.token_properties.valid:
    print('Invalid token: ' + str(response.token_properties.invalid_reason))
    return 0.0

  return response.risk_analysis.score
Пример #3
0
def create_site_key(project_id: str, domain_name: str) -> str:
    """Create reCAPTCHA Site key which binds a domain name to a unique key.
    Args:
    project_id : GCloud Project ID.
    domain_name: Specify the domain name in which the reCAPTCHA should be activated.
    """
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Set the type of the reCAPTCHA to be displayed.
    # For different types, see: https://cloud.google.com/recaptcha-enterprise/docs/keys
    web_settings = recaptchaenterprise_v1.WebKeySettings()
    web_settings.allowed_domains.append(domain_name)
    web_settings.allow_amp_traffic = False
    web_settings.integration_type = web_settings.IntegrationType.SCORE

    key = recaptchaenterprise_v1.Key()
    key.display_name = "any descriptive name for the key"
    key.web_settings = web_settings

    # Create the request.
    request = recaptchaenterprise_v1.CreateKeyRequest()
    request.parent = f"projects/{project_id}"
    request.key = key

    # Get the name of the created reCAPTCHA site key.
    response = client.create_key(request)
    recaptcha_site_key = response.name.rsplit("/", maxsplit=1)[1]
    print("reCAPTCHA Site key created successfully. Site Key: " +
          recaptcha_site_key)
    return recaptcha_site_key
Пример #4
0
def check_google_recaptcha(token, assessment):
    """
    :param token: xxxxxxxxxx
    :return: boolean
    """
    CREDENTIALS = service_account.Credentials.from_service_account_file(
        f'/usr/src/app/recaptcha.json')
    project_id = "resources-practice"
    recaptcha_site_key = "6Ld6zg0cAAAAAE5gKfFd3nk_Y7Q7b8m-VSbuagTX"
    assessment_name = assessment
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient(
        credentials=CREDENTIALS)
    event = recaptchaenterprise_v1.Event()
    event.site_key = recaptcha_site_key
    event.token = token

    assessment = recaptchaenterprise_v1.Assessment()
    assessment.event = event
    assessment.name = assessment_name
    project_name = f'projects/{project_id}'

    request = recaptchaenterprise_v1.CreateAssessmentRequest()
    print(f"assessment: {assessment}")
    request.assessment = assessment
    request.parent = project_name

    response = client.create_assessment(request)
    print(f"response: {response}")
    return response.token_properties.valid
def create_assessment(
    project_id: str, recaptcha_site_key: str, token: str, recaptcha_action: str
) -> Assessment:
    """Create an assessment to analyze the risk of a UI action.
    Args:
        project_id: GCloud Project ID
        recaptcha_site_key: Site key obtained by registering a domain/app to use recaptcha services.
        token: The token obtained from the client on passing the recaptchaSiteKey.
        recaptcha_action: Action name corresponding to the token.
    """

    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Set the properties of the event to be tracked.
    event = recaptchaenterprise_v1.Event()
    event.site_key = recaptcha_site_key
    event.token = token

    assessment = recaptchaenterprise_v1.Assessment()
    assessment.event = event

    project_name = f"projects/{project_id}"

    # Build the assessment request.
    request = recaptchaenterprise_v1.CreateAssessmentRequest()
    request.assessment = assessment
    request.parent = project_name

    response = client.create_assessment(request)

    # Check if the token is valid.
    if not response.token_properties.valid:
        print(
            "The CreateAssessment call failed because the token was "
            + "invalid for for the following reasons: "
            + str(response.token_properties.invalid_reason)
        )
        return

    # Check if the expected action was executed.
    if response.token_properties.action != recaptcha_action:
        print(
            "The action attribute in your reCAPTCHA tag does"
            + "not match the action you are expecting to score"
        )
        return
    else:
        # Get the risk score and the reason(s)
        # For more information on interpreting the assessment,
        # see: https://cloud.google.com/recaptcha-enterprise/docs/interpret-assessment
        for reason in response.risk_analysis.reasons:
            print(reason)
        print(
            "The reCAPTCHA score for this token is: "
            + str(response.risk_analysis.score)
        )
        # Get the assessment name (id). Use this to annotate the assessment.
        assessment_name = client.parse_assessment_path(response.name).get("assessment")
        print(f"Assessment name: {assessment_name}")
    return response
Пример #6
0
def sample_delete_key():
    # Create a client
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Initialize request argument(s)
    request = recaptchaenterprise_v1.DeleteKeyRequest(name="name_value", )

    # Make the request
    client.delete_key(request=request)
Пример #7
0
def sample_migrate_key():
    # Create a client
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Initialize request argument(s)
    request = recaptchaenterprise_v1.MigrateKeyRequest(name="name_value", )

    # Make the request
    response = client.migrate_key(request=request)

    # Handle the response
    print(response)
Пример #8
0
def sample_get_metrics():
    # Create a client
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Initialize request argument(s)
    request = recaptchaenterprise_v1.GetMetricsRequest(name="name_value", )

    # Make the request
    response = client.get_metrics(request=request)

    # Handle the response
    print(response)
Пример #9
0
def sample_list_keys():
    # Create a client
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Initialize request argument(s)
    request = recaptchaenterprise_v1.ListKeysRequest(parent="parent_value", )

    # Make the request
    page_result = client.list_keys(request=request)

    # Handle the response
    for response in page_result:
        print(response)
def sample_annotate_assessment():
    # Create a client
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Initialize request argument(s)
    request = recaptchaenterprise_v1.AnnotateAssessmentRequest(
        name="name_value", )

    # Make the request
    response = client.annotate_assessment(request=request)

    # Handle the response
    print(response)
def sample_update_key():
    # Create a client
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Initialize request argument(s)
    key = recaptchaenterprise_v1.Key()
    key.web_settings.integration_type = "INVISIBLE"

    request = recaptchaenterprise_v1.UpdateKeyRequest(key=key, )

    # Make the request
    response = client.update_key(request=request)

    # Handle the response
    print(response)
def sample_list_related_account_group_memberships():
    # Create a client
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Initialize request argument(s)
    request = recaptchaenterprise_v1.ListRelatedAccountGroupMembershipsRequest(
        parent="parent_value", )

    # Make the request
    page_result = client.list_related_account_group_memberships(
        request=request)

    # Handle the response
    for response in page_result:
        print(response)
def update_site_key(project_id: str, recaptcha_site_key: str,
                    domain_name: str) -> None:
    """
    Update the properties of the given site key present under the project id.

    Args:
    project_id: GCloud Project ID.
    recaptcha_site_key: Specify the site key.
    domain_name: Specify the domain name for which the settings should be updated.
    """

    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Construct the key details.
    key_name = f"projects/{project_id}/keys/{recaptcha_site_key}"

    # Set the name and the new settings for the key.
    web_settings = recaptchaenterprise_v1.WebKeySettings()
    web_settings.allow_amp_traffic = True
    web_settings.allowed_domains.append(domain_name)

    key = recaptchaenterprise_v1.Key()
    key.display_name = "any descriptive name for the key"
    key.name = key_name
    key.web_settings = web_settings

    update_key_request = recaptchaenterprise_v1.UpdateKeyRequest()
    update_key_request.key = key
    client.update_key(update_key_request)

    time.sleep(5)

    # Retrieve the key and check if the property is updated.
    get_key_request = recaptchaenterprise_v1.GetKeyRequest()
    get_key_request.name = key_name
    response = client.get_key(get_key_request)
    web_settings = response.web_settings

    # Get the changed property.
    if not web_settings.allow_amp_traffic:
        print(
            "Error! reCAPTCHA Site key property hasn't been updated. Please try again !"
        )
    else:
        print("reCAPTCHA Site key successfully updated ! ")
Пример #14
0
def list_site_keys(project_id: str) -> ListKeysPager:
    """List all keys present under the given project ID.

    Args:
    project_id: GCloud Project ID.
    """

    project_name = f"projects/{project_id}"

    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Set the project id to list the keys present in it.
    request = recaptchaenterprise_v1.ListKeysRequest()
    request.parent = project_name

    response = client.list_keys(request)
    print("Listing reCAPTCHA site keys: ")
    for i, key in enumerate(response):
        print(f"{str(i)}. {key.name}")

    return response
Пример #15
0
def annotate_assessment(project_id: str, assessment_id: str) -> None:
    """Pre-requisite: Create an assessment before annotating.
        Annotate an assessment to provide feedback on the correctness of recaptcha prediction.
    Args:
        project_id: Google Cloud Project ID
        assessment_id: Value of the 'name' field returned from the create_assessment() call.
    """

    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    assessment_name = f"projects/{project_id}/assessments/{assessment_id}"
    # 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
    request = recaptchaenterprise_v1.AnnotateAssessmentRequest()
    request.name = assessment_name
    request.annotation = request.Annotation.FRAUDULENT
    request.reasons = [request.Reason.FAILED_TWO_FACTOR]

    # Empty response is sent back.
    client.annotate_assessment(request)
    print("Annotated response sent successfully ! ")
Пример #16
0
def test_assessment(capsys: CaptureFixture, recaptcha_site_key: str,
                    browser: WebDriver) -> None:
    # Get token.
    token, action = get_token(recaptcha_site_key, browser)
    # Create assessment.
    assessment_response = assess_token(recaptcha_site_key,
                                       token=token,
                                       action=action)
    score = str(assessment_response.risk_analysis.score)
    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()
    # Parse the assessment_response.name which is of the format:
    # {'project': 'my-project-id', 'assessment': 'assessment-id'}
    assessment_name = client.parse_assessment_path(
        assessment_response.name).get("assessment")
    assert assessment_name != ""
    set_score(browser, score)

    # Annotate assessment.
    annotate_assessment(project_id=GOOGLE_CLOUD_PROJECT,
                        assessment_id=assessment_name)
    out, _ = capsys.readouterr()
    assert re.search("Annotated response sent successfully !", out)
Пример #17
0
def migrate_site_key(project_id: str, recaptcha_site_key: str) -> None:
    """Migrate a key from reCAPTCHA (non-Enterprise) to reCAPTCHA Enterprise.
        If you created the key using Admin console: https://www.google.com/recaptcha/admin/site,
        then use this API to migrate to reCAPTCHA Enterprise.
        For more info, see: https://cloud.google.com/recaptcha-enterprise/docs/migrate-recaptcha
    Args:
    project_id: Google Cloud Project ID.
    recaptcha_site_key: Specify the site key to migrate.
    """

    client = recaptchaenterprise_v1.RecaptchaEnterpriseServiceClient()

    # Specify the key name to migrate.
    name = f"projects/{project_id}/keys/{recaptcha_site_key}"
    request = recaptchaenterprise_v1.MigrateKeyRequest()
    request.name = name

    response = client.migrate_key(request)
    # To verify if the site key has been migrated, use 'list_site_keys' to check if the
    # key is present.
    for key in list_site_keys(project_id):
        if key.name == response.name:
            print(f"Key migrated successfully: {recaptcha_site_key}")