コード例 #1
0
def get_access_token(verification_code):
  """Get the access token from verification code.

    See: https://developers.google.com/identity/protocols/OAuth2InstalledApp
  """
  client_id = db_config.get_value('reproduce_tool_client_id')
  if not client_id:
    raise helpers.UnauthorizedException('Client id not configured.')

  client_secret = db_config.get_value('reproduce_tool_client_secret')
  if not client_secret:
    raise helpers.UnauthorizedException('Client secret not configured.')

  response = requests.post(
      'https://www.googleapis.com/oauth2/v4/token',
      headers={'Content-Type': 'application/x-www-form-urlencoded'},
      data={
          'code': verification_code,
          'client_id': client_id,
          'client_secret': client_secret,
          'redirect_uri': 'urn:ietf:wg:oauth:2.0:oob',
          'grant_type': 'authorization_code'
      })

  if response.status_code != 200:
    raise helpers.UnauthorizedException('Invalid verification code (%s): %s' %
                                        (verification_code, response.text))

  try:
    data = json.loads(response.text)
    return data['access_token']
  except (KeyError, ValueError):
    raise helpers.EarlyExitException(
        'Parsing the JSON response body failed: %s' % response.text, 500)
コード例 #2
0
def get_email_and_access_token(authorization):
    """Get user email from the request.

    See: https://developers.google.com/identity/protocols/OAuth2InstalledApp
  """
    if authorization.startswith(VERIFICATION_CODE_PREFIX):
        verification_code = authorization.split(' ')[1]
        access_token = get_access_token(verification_code)
        authorization = BEARER_PREFIX + access_token

    if not authorization.startswith(BEARER_PREFIX):
        raise helpers.UnauthorizedException(
            'The Authorization header is invalid. It should have been started with'
            " '%s'." % BEARER_PREFIX)

    access_token = authorization.split(' ')[1]

    response = requests.get('https://www.googleapis.com/oauth2/v3/tokeninfo',
                            params={'access_token': access_token})
    if response.status_code != 200:
        raise helpers.UnauthorizedException(
            'Failed to authorize. The Authorization header (%s) might be invalid.'
            % authorization)

    try:
        data = json.loads(response.text)

        # Whitelist service accounts. They have different client IDs (or aud).
        # Therefore, we check against their email directly.
        if data.get('email_verified') and data.get('email') in _auth_config(
        ).get('whitelisted_oauth_emails', default=[]):
            return data['email'], authorization

        # Validate that this is an explicitly whitelisted client ID, or the client
        # ID for the reproduce tool.
        whitelisted_client_ids = _auth_config().get(
            'whitelisted_oauth_client_ids', default=[])
        reproduce_tool_client_id = db_config.get_value(
            'reproduce_tool_client_id')
        if reproduce_tool_client_id:
            whitelisted_client_ids += [reproduce_tool_client_id]
        if data.get('aud') not in whitelisted_client_ids:
            raise helpers.UnauthorizedException(
                "The access token doesn't belong to one of the allowed OAuth clients"
                ': %s.' % response.text)

        if not data.get('email_verified'):
            raise helpers.UnauthorizedException(
                'The email (%s) is not verified: %s.' %
                (data.get('email'), response.text))

        return data['email'], authorization
    except (KeyError, ValueError) as e:
        raise helpers.EarlyExitException(
            'Parsing the JSON response body failed: %s' % response.text,
            500) from e
コード例 #3
0
  def wrapper(self):
    """Wrapper."""
    try:
      bearer_token = request.headers.get('Authorization', '')
      if not bearer_token.startswith(BEARER_PREFIX):
        raise helpers.UnauthorizedException('Missing or invalid bearer token.')

      token = bearer_token.split(' ')[1]
      claim = id_token.verify_oauth2_token(token, google_requests.Request())
    except google.auth.exceptions.GoogleAuthError as e:
      raise helpers.UnauthorizedException('Invalid ID token.') from e

    if (not claim.get('email_verified') or
        claim.get('email') != utils.service_account_email()):
      raise helpers.UnauthorizedException('Invalid ID token.')

    message = pubsub.raw_message_to_message(json.loads(request.data.decode()))
    return func(self, message)
コード例 #4
0
def check_access_and_get_testcase(testcase_id):
  """Check the failed attempt count and get the testcase."""
  if not helpers.get_user_email():
    raise helpers.UnauthorizedException()

  if not testcase_id:
    raise helpers.EarlyExitException('No test case specified!', 404)

  try:
    testcase = data_handler.get_testcase_by_id(testcase_id)
  except errors.InvalidTestcaseError:
    raise helpers.EarlyExitException('Invalid test case!', 404)

  if not can_user_access_testcase(testcase):
    raise helpers.AccessDeniedException()

  return testcase