def MakeSecureChannel(target): """Creates grpc secure channel. Args: target: str, The server address, for example: bigtableadmin.googleapis.com:443. Returns: grpc.secure channel. """ credentials = cred_store.Load() # ssl_channel_credentials() loads root certificates from # `grpc/_adapter/credentials/roots.pem`. transport_creds = grpc.ssl_channel_credentials() custom_metadata_plugin = _MetadataPlugin(credentials) auth_creds = grpc.metadata_call_credentials( custom_metadata_plugin, name='google_creds') channel_creds = grpc.composite_channel_credentials( transport_creds, auth_creds) channel_args = ( ('grpc.primary_user_agent', http.MakeUserAgentString(properties.VALUES.metrics.command_name.Get())), ) return grpc.secure_channel(target, channel_creds, options=channel_args)
def InitiateConnection(self): """Initiate the WebSocket connection.""" utils.CheckPythonVersion(self._ignore_certs) utils.ValidateParameters(self._tunnel_target) self._ca_certs = utils.CheckCACertsFile(self._ignore_certs) self._connect_url = utils.CreateWebSocketUrl(CONNECT_ENDPOINT, self._tunnel_target) headers = [ 'User-Agent: ' + http.MakeUserAgentString(), 'Sec-WebSocket-Protocol: ' + utils.SUBPROTOCOL_NAME ] if self._access_token: headers += ['Authorization: Bearer ' + self._access_token] log.info('Connecting to with URL %r', self._connect_url) self._websocket_errors = [] self._connection_sid = None if log.GetVerbosity() == logging.DEBUG: websocket.enableTrace(True) else: websocket_logger = logging.getLogger('websocket') websocket_logger.setLevel(logging.CRITICAL) self._websocket = websocket.WebSocketApp(self._connect_url, header=headers, on_error=self._OnError, on_close=self._OnClose, on_data=self._OnData) log.info('Starting WebSocket receive thread.') self._websocket_thread = threading.Thread( target=self._ReceiveFromWebSocket) self._websocket_thread.daemon = True self._websocket_thread.start()
def _StartNewWebSocket(self): """Start a new WebSocket and thread to listen for incoming data.""" headers = ['User-Agent: ' + http.MakeUserAgentString()] if self._get_access_token_callback: headers += [ 'Authorization: Bearer ' + self._get_access_token_callback() ] use_mtls = False if self._caa_config is not None: use_mtls = self._caa_config.use_client_certificate if self._connection_sid: url = utils.CreateWebSocketReconnectUrl(self._tunnel_target, self._connection_sid, self._total_bytes_received, use_mtls) log.info('Reconnecting with URL [%r]', url) else: url = utils.CreateWebSocketConnectUrl(self._tunnel_target, use_mtls) log.info('Connecting with URL [%r]', url) self._connect_msg_received = False self._websocket_helper = helper.IapTunnelWebSocketHelper( url, headers, self._ignore_certs, self._tunnel_target.proxy_info, self._OnData, self._OnClose, self._caa_config) self._websocket_helper.StartReceivingThread()
def _StartNewWebSocket(self): """Start a new WebSocket and thread to listen for incoming data.""" headers = [ 'User-Agent: ' + http.MakeUserAgentString(), 'Sec-WebSocket-Protocol: ' + utils.SUBPROTOCOL_NAME ] if self._get_access_token_callback: headers += [ 'Authorization: Bearer ' + self._get_access_token_callback() ] if self._connection_sid: url = utils.CreateWebSocketReconnectUrl(self._tunnel_target, self._connection_sid, self._total_bytes_received) log.info('Reconnecting with URL [%r]', url) else: url = utils.CreateWebSocketConnectUrl(self._tunnel_target) log.info('Connecting with URL [%r]', url) self._connect_msg_received = False self._websocket_helper = helper.IapTunnelWebSocketHelper( url, headers, self._ignore_certs, self._tunnel_target.proxy_info, self._OnData, self._OnClose) self._websocket_helper.StartReceivingThread()
def MakeRequest(url, command_path): """Gets the request object for the given URL. If the URL is for cloud storage and we get a 403, this will try to load the active credentials and use them to authenticate the download. Args: url: str, The URL to download. command_path: the command path to include in the User-Agent header if the URL is HTTP Raises: AuthenticationError: If this download requires authentication and there are no credentials or the credentials do not have access. Returns: urllib2.Request, The request. """ headers = { 'Cache-Control': 'no-cache', 'User-Agent': http.MakeUserAgentString(command_path) } try: if url.startswith(ComponentInstaller.GCS_BROWSER_DL_URL): url = url.replace(ComponentInstaller.GCS_BROWSER_DL_URL, ComponentInstaller.GCS_API_DL_URL, 1) req = urllib2.Request(url, headers=headers) return urlopen_with_cacerts.urlopen(req, timeout=TIMEOUT_IN_SEC) except urllib2.HTTPError as e: if e.code != 403 or not url.startswith(ComponentInstaller.GCS_API_DL_URL): raise e try: creds = store.Load() store.Refresh(creds) creds.apply(headers) except store.Error as e: # If we fail here, it is because there are no active credentials or the # credentials are bad. raise AuthenticationError( 'This component requires valid credentials to install.', e) try: # Retry the download using the credentials. req = urllib2.Request(url, headers=headers) return urlopen_with_cacerts.urlopen(req, timeout=TIMEOUT_IN_SEC) except urllib2.HTTPError as e: if e.code != 403: raise e # If we fail again with a 403, that means we used the credentials, but # they didn't have access to the resource. raise AuthenticationError("""\ Account [{account}] does not have permission to install this component. Please ensure that this account should have access or run: $ gcloud config set account ``ACCOUNT'' to choose another account.""".format( account=properties.VALUES.core.account.Get()), e)