Skip to content

feat: add reCAPTCHA verdict to auth blocking functions #166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/firebase_functions/identity_fn.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,9 @@ class AdditionalUserInfo:
is_new_user: bool
"""A boolean indicating if the user is new or not."""

recaptcha_score: float | None
"""The user's reCAPTCHA score, if available."""


@_dataclasses.dataclass(frozen=True)
class Credential:
Expand Down Expand Up @@ -282,6 +285,12 @@ class AuthBlockingEvent:
The time the event was triggered."""


RecaptchaActionOptions = _typing.Literal["ALLOW", "BLOCK"]
"""
The reCAPTCHA action options.
"""


class BeforeCreateResponse(_typing.TypedDict, total=False):
"""
The handler response type for 'before_user_created' blocking events.
Expand All @@ -302,6 +311,8 @@ class BeforeCreateResponse(_typing.TypedDict, total=False):
custom_claims: dict[str, _typing.Any] | None
"""The user's custom claims object if available."""

recaptcha_action_override: RecaptchaActionOptions | None


class BeforeSignInResponse(BeforeCreateResponse, total=False):
"""
Expand Down
2 changes: 1 addition & 1 deletion src/firebase_functions/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
class LogSeverity(str, _enum.Enum):
"""
`LogSeverity` indicates the detailed severity of the log entry. See
`LogSeverity <https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#logseverity>`_.
`LogSeverity <https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#logseverity>`.
"""

DEBUG = "DEBUG"
Expand Down
35 changes: 28 additions & 7 deletions src/firebase_functions/private/_identity_fn.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,7 @@ def _additional_user_info_from_token_data(token_data: dict[str, _typing.Any]):
profile=profile,
username=username,
is_new_user=is_new_user,
recaptcha_score=token_data.get("recaptcha_score"),
)


Expand Down Expand Up @@ -302,9 +303,35 @@ def _validate_auth_response(
auth_response_dict["customClaims"] = auth_response["custom_claims"]
if "session_claims" in auth_response_keys:
auth_response_dict["sessionClaims"] = auth_response["session_claims"]
if "recaptcha_action_override" in auth_response_keys:
auth_response_dict["recaptchaActionOverride"] = auth_response[
"recaptcha_action_override"]
return auth_response_dict


def _generate_response_payload(
auth_response_dict: dict[str, _typing.Any] | None
) -> dict[str, _typing.Any]:
if not auth_response_dict:
return {}

formatted_auth_response = auth_response_dict.copy()
recaptcha_action_override = formatted_auth_response.pop(
"recaptchaActionOverride", None)
result = {}
update_mask = ",".join(formatted_auth_response.keys())

if len(update_mask) != 0:
result["userRecord"] = {
**formatted_auth_response, "updateMask": update_mask
}

if recaptcha_action_override is not None:
result["recaptchaActionOverride"] = recaptcha_action_override

return result


def before_operation_handler(
func: _typing.Callable,
event_type: str,
Expand All @@ -329,13 +356,7 @@ def before_operation_handler(
if not auth_response:
return _jsonify({})
auth_response_dict = _validate_auth_response(event_type, auth_response)
update_mask = ",".join(auth_response_dict.keys())
result = {
"userRecord": {
**auth_response_dict,
"updateMask": update_mask,
}
}
result = _generate_response_payload(auth_response_dict)
return _jsonify(result)
# Disable broad exceptions lint since we want to handle all exceptions.
# pylint: disable=broad-except
Expand Down