Ejemplo n.º 1
0
 def test_create_http_sets_default_values_on_http(self):
   http = transport.create_http()
   self.assertIsNone(http.cache)
   self.assertIsNone(http.timeout)
   self.assertEqual(http.tls_minimum_version,
                    transport.GC_Values[transport.GC_TLS_MIN_VERSION])
   self.assertEqual(http.tls_maximum_version,
                    transport.GC_Values[transport.GC_TLS_MAX_VERSION])
   self.assertEqual(http.ca_certs, transport.GC_Values[transport.GC_CA_FILE])
Ejemplo n.º 2
0
    def revoke(self, http=None):
        """Revokes this credential's access token with the server.

    Args:
      http: httplib2.Http compatible object for use as a transport. If no http
        is provided, a default will be used.
    """
        with self._lock:
            if http is None:
                http = transport.create_http()
            params = urlencode({'token': self.refresh_token})
            revoke_uri = f'{Credentials._REVOKE_TOKEN_BASE_URI}?{params}'
            http.request(revoke_uri, 'GET')
Ejemplo n.º 3
0
def shorten_url(long_url, httpc=None):
    if not httpc:
        httpc = transport.create_http(timeout=10)
    headers = {'Content-Type': 'application/json', 'User-Agent': GAM_INFO}
    try:
        payload = json.dumps({'long_url': long_url})
        resp, content = httpc.request(URL_SHORTENER_ENDPOINT,
                                      'POST',
                                      payload,
                                      headers=headers)
    except:
        return long_url
    if resp.status != 200:
        return long_url
    try:
        if isinstance(content, bytes):
            content = content.decode()
        return json.loads(content).get('short_url', long_url)
    except:
        return long_url
Ejemplo n.º 4
0
 def test_create_http_sets_cache_timeout(self):
     http = transport.create_http(timeout=1234)
     self.assertEqual(http.timeout, 1234)
Ejemplo n.º 5
0
 def test_create_http_sets_cache(self):
     fake_cache = {}
     http = transport.create_http(cache=fake_cache)
     self.assertEqual(http.cache, fake_cache)
Ejemplo n.º 6
0
 def test_create_http_sets_tls_max_version(self):
     http = transport.create_http(override_max_tls='TLSv1_3')
     self.assertEqual(http.tls_maximum_version, 'TLSv1_3')
Ejemplo n.º 7
0
def update():
    verif = build()
    a_domain = sys.argv[3]
    verificationMethod = sys.argv[4].upper()
    if verificationMethod == 'CNAME':
        verificationMethod = 'DNS_CNAME'
    elif verificationMethod in ['TXT', 'TEXT']:
        verificationMethod = 'DNS_TXT'
    if verificationMethod in ['DNS_TXT', 'DNS_CNAME']:
        verify_type = 'INET_DOMAIN'
        identifier = a_domain
    else:
        verify_type = 'SITE'
        identifier = f'http://{a_domain}/'
    body = {
        'site': {
            'type': verify_type,
            'identifier': identifier
        },
        'verificationMethod': verificationMethod
    }
    try:
        verify_result = gapi.call(
            verif.webResource(),
            'insert',
            throw_reasons=[gapi_errors.ErrorReason.BAD_REQUEST],
            verificationMethod=verificationMethod,
            body=body)
    except gapi_errors.GapiBadRequestError as e:
        print(f'ERROR: {str(e)}')
        verify_data = gapi.call(verif.webResource(), 'getToken', body=body)
        print(f'Method:  {verify_data["method"]}')
        print(f'Expected Token:      {verify_data["token"]}')
        if verify_data['method'] in ['DNS_CNAME', 'DNS_TXT']:
            simplehttp = transport.create_http()
            base_url = 'https://dns.google/resolve?'
            query_params = {}
            if verify_data['method'] == 'DNS_CNAME':
                cname_token = verify_data['token']
                cname_list = cname_token.split(' ')
                cname_subdomain = cname_list[0]
                query_params['name'] = f'{cname_subdomain}.{a_domain}'
                query_params['type'] = 'cname'
            else:
                query_params['name'] = a_domain
                query_params['type'] = 'txt'
            full_url = base_url + urlencode(query_params)
            (_, c) = simplehttp.request(full_url, 'GET')
            result = json.loads(c)
            status = result['Status']
            if status == 0 and 'Answer' in result:
                answers = result['Answer']
                if verify_data['method'] == 'DNS_CNAME':
                    answer = answers[0]['data']
                else:
                    answer = 'no matching record found'
                    for possible_answer in answers:
                        possible_answer['data'] = possible_answer['data'].strip(
                            '"')
                        if possible_answer['data'].startswith(
                                'google-site-verification'):
                            answer = possible_answer['data']
                            break
                        print(
                            f'Unrelated TXT record: {possible_answer["data"]}')
                print(f'Found DNS Record: {answer}')
            elif status == 0:
                controlflow.system_error_exit(1, 'DNS record not found')
            else:
                controlflow.system_error_exit(
                    status,
                    DNS_ERROR_CODES_MAP.get(status, f'Unknown error {status}'))
        return
    print('SUCCESS!')
    print(f'Verified:  {verify_result["site"]["identifier"]}')
    print(f'ID:  {verify_result["id"]}')
    print(f'Type: {verify_result["site"]["type"]}')
    print('All Owners:')
    try:
        for owner in verify_result['owners']:
            print(f' {owner}')
    except KeyError:
        pass
    print()
    print(
        f'You can now add {a_domain} or it\'s subdomains as secondary or domain aliases of the {GC_Values[GC_DOMAIN]} Google Workspace Account.'
    )
Ejemplo n.º 8
0
def call(service,
         function,
         silent_errors=False,
         soft_errors=False,
         throw_reasons=None,
         retry_reasons=None,
         **kwargs):
    """Executes a single request on a Google service function.

  Args:
    service: A Google service object for the desired API.
    function: String, The name of a service request method to execute.
    silent_errors: Bool, If True, error messages are suppressed when
      encountered.
    soft_errors: Bool, If True, writes non-fatal errors to stderr.
    throw_reasons: A list of Google HTTP error reason strings indicating the
      errors generated by this request should be re-thrown. All other HTTP
      errors are consumed.
    retry_reasons: A list of Google HTTP error reason strings indicating which
      error should be retried, using exponential backoff techniques, when the
      error reason is encountered.
    **kwargs: Additional params to pass to the request method.

  Returns:
    A response object for the corresponding Google API call.
  """
    if throw_reasons is None:
        throw_reasons = []
    if retry_reasons is None:
        retry_reasons = []

    method = getattr(service, function)
    retries = 10
    parameters = dict(
        list(kwargs.items()) + list(GM_Globals[GM_EXTRA_ARGS_DICT].items()))
    for n in range(1, retries + 1):
        try:
            return method(**parameters).execute()
        except googleapiclient.errors.HttpError as e:
            http_status, reason, message = errors.get_gapi_error_detail(
                e,
                soft_errors=soft_errors,
                silent_errors=silent_errors,
                retry_on_http_error=n < 3)
            if http_status == -1:
                # The error detail indicated that we should retry this request
                # We'll refresh credentials and make another pass
                service._http.credentials.refresh(transport.create_http())
                continue
            if http_status == 0:
                return None

            is_known_error_reason = reason in [
                r.value for r in errors.ErrorReason
            ]
            if is_known_error_reason and errors.ErrorReason(
                    reason) in throw_reasons:
                if errors.ErrorReason(
                        reason) in errors.ERROR_REASON_TO_EXCEPTION:
                    raise errors.ERROR_REASON_TO_EXCEPTION[errors.ErrorReason(
                        reason)](message)
                raise e
            if (n != retries) and (is_known_error_reason and errors.ErrorReason(
                    reason) in errors.DEFAULT_RETRY_REASONS + retry_reasons):
                controlflow.wait_on_failure(n, retries, reason)
                continue
            if soft_errors:
                display.print_error(
                    f'{http_status}: {message} - {reason}{["", ": Giving up."][n > 1]}'
                )
                return None
            controlflow.system_error_exit(
                int(http_status), f'{http_status}: {message} - {reason}')
        except google.auth.exceptions.RefreshError as e:
            handle_oauth_token_error(
                e, soft_errors or
                errors.ErrorReason.SERVICE_NOT_AVAILABLE in throw_reasons)
            if errors.ErrorReason.SERVICE_NOT_AVAILABLE in throw_reasons:
                raise errors.GapiServiceNotAvailableError(str(e))
            display.print_error(
                f'User {GM_Globals[GM_CURRENT_API_USER]}: {str(e)}')
            return None
        except ValueError as e:
            if hasattr(service._http,
                       'cache') and service._http.cache is not None:
                service._http.cache = None
                continue
            controlflow.system_error_exit(4, str(e))
        except (httplib2.ServerNotFoundError, RuntimeError) as e:
            if n != retries:
                service._http.connections = {}
                controlflow.wait_on_failure(n, retries, str(e))
                continue
            controlflow.system_error_exit(4, str(e))
        except TypeError as e:
            controlflow.system_error_exit(4, str(e))