async def test_call_with_credentials(self): call_credentials = grpc.composite_call_credentials( grpc.access_token_call_credentials("abc"), grpc.access_token_call_credentials("def"), ) call = self._stub.UnaryCall(messages_pb2.SimpleRequest(), credentials=call_credentials) response = await call self.assertIsInstance(response, messages_pb2.SimpleResponse)
async def test_passing_credentials_fails_over_insecure_channel(self): call_credentials = grpc.composite_call_credentials( grpc.access_token_call_credentials("abc"), grpc.access_token_call_credentials("def"), ) with self.assertRaisesRegex( aio.UsageError, "Call credentials are only valid on secure channels"): self._stub.UnaryCall(messages_pb2.SimpleRequest(), credentials=call_credentials)
def test_call_credentials_composition(self): first = grpc.access_token_call_credentials('abc') second = grpc.access_token_call_credentials('def') third = grpc.access_token_call_credentials('ghi') first_and_second = grpc.composite_call_credentials(first, second) first_second_and_third = grpc.composite_call_credentials( first, second, third) self.assertIsInstance(first_and_second, grpc.CallCredentials) self.assertIsInstance(first_second_and_third, grpc.CallCredentials)
def main(): assert TOKEN != '', 'You need to set TOKEN. To obtain your token visit https://cryptomood.com/business/products/sentiment-analysis-api/.' # Create credentials for use with an secured channel credentials = grpc.ssl_channel_credentials( open(PATH_TO_CERT_FILE, 'rb').read()) call_credentials = grpc.access_token_call_credentials(TOKEN) credentials = grpc.composite_channel_credentials(credentials, call_credentials) channel = grpc.secure_channel(SERVER_ADDRESS, credentials) # create stub stub = types_pb2_grpc.SentimentsStub(channel) # create request req = types_pb2.AggregationCandleFilter( resolution='M1', assets_filter=types_pb2.AssetsFilter(assets=['BTC'], all_assets=False)) # Response-streaming RPC candle_stream = stub.SubscribeSocialSentiment(req) for candle in candle_stream: # attributes are same as defined in proto messages print(candle.id, candle.a)
def create_channel(args): call_credentials = None channel = None if args.token: log.debug("Adding CallCredentials with token %s" % args.token) call_credentials = grpc.access_token_call_credentials(args.token) if args.secure: log.debug("Creating secure gRPC channel") root_certificates = None certificate_chain = None private_key = None if args.rootCerts: log.debug("Adding root certs") root_certificates = open(args.rootCerts, 'rb').read() if args.certChain: log.debug("Adding cert chain") certificate_chain = open(args.certChain, 'rb').read() if args.privateKey: log.debug("Adding private key") private_key = open(args.privateKey, 'rb').read() channel_credentials = grpc.ssl_channel_credentials(root_certificates=root_certificates, private_key=private_key, certificate_chain=certificate_chain) if call_credentials is not None: channel_credentials = grpc.composite_channel_credentials(channel_credentials, call_credentials) channel = grpc.secure_channel(args.serverUrl, credentials=channel_credentials) else: log.debug("Creating insecure gRPC channel") channel = grpc.insecure_channel(args.serverUrl) return channel
def main(): assert TOKEN != '', 'You need to set TOKEN. To obtain your token visit https://cryptomood.com/business/products/sentiment-analysis-api/.' # Create credentials for use with an secured channel credentials = grpc.ssl_channel_credentials(open(PATH_TO_CERT_FILE, 'rb').read()) call_credentials = grpc.access_token_call_credentials(TOKEN) credentials = grpc.composite_channel_credentials(credentials, call_credentials) channel = grpc.secure_channel(SERVER_ADDRESS, credentials) # create stub stub = types_pb2_grpc.HistoricDataStub(channel) # create timeframe now = time.time() seconds = int(now) to_time = timestamp_pb2.Timestamp(seconds=seconds) from_time = timestamp_pb2.Timestamp(seconds=to_time.seconds - int(86400 / 4)) # last 6 hours # in our case we have to use kwarg because `from` is # is recognized as python keyword so there would syntax be error # if you want get value you have to use getattr() historic_request_kwargs = { 'from': from_time, 'to': to_time, 'filter': types_pb2.AssetsFilter(assets=['BTC', 'ETH'], all_assets=False)} req = types_pb2.HistoricRequest(**historic_request_kwargs) article_stream = stub.HistoricArticles(req) for article in article_stream: print(article.base.id, article.base.title)
def main(args): # read the file containing a session token to authenticate with token = args.token_file.read().strip() # create the header object for the token callCreds = grpc.access_token_call_credentials(token) # if using a self-signed certificate (should be provided as arg) if args.cert_file: # create the channel using the self-signed cert cert = args.cert_file.read() channelCreds = grpc.ssl_channel_credentials(root_certificates=cert) else: # otherwise default to checking against CAs channelCreds = grpc.ssl_channel_credentials() # create channel settings (auth + TLS) connCreds = grpc.composite_channel_credentials(channelCreds, callCreds) # initialize a connection to the server using our connection settings (auth + TLS) with grpc.secure_channel(args.server, connCreds) as channel: # create the Python stub for the inventory API # this is essentially the client, but Python gRPC refers to them as "stubs" # because they call into the gRPC C API stub = services.DeviceServiceStub(channel) if args.hostname: get_device_with_filter(stub, args.serial, args.hostname) else: get_device_by_serial(stub, args.serial)
def get_homegraph(self): """Returns the entire Google Home Foyer V2 service""" if self.homegraph is None or self._has_expired(self.homegraph_date, HOMEGRAPH_DURATION): LOGGER.debug( "There is no stored homegraph, or it has expired, getting a new one..." ) log_prefix = "[GRPC]" access_token = self.get_access_token() if not access_token: LOGGER.debug("%s Unable to obtain access token.", log_prefix) return None try: LOGGER.debug("%s Creating SSL channel credentials...", log_prefix) scc = grpc.ssl_channel_credentials(root_certificates=None) LOGGER.debug("%s Creating access token call credentials...", log_prefix) tok = grpc.access_token_call_credentials(access_token) LOGGER.debug("%s Compositing channel credentials...", log_prefix) channel_credentials = grpc.composite_channel_credentials( scc, tok) LOGGER.debug( "%s Establishing secure channel with " "the Google Home Foyer API...", log_prefix, ) with grpc.secure_channel(GOOGLE_HOME_FOYER_API, channel_credentials) as channel: LOGGER.debug( "%s Getting channels StructuresServiceStub...", log_prefix) rpc_service = v1_pb2_grpc.StructuresServiceStub(channel) LOGGER.debug("%s Getting HomeGraph request...", log_prefix) request = v1_pb2.GetHomeGraphRequest(string1="", num2="") LOGGER.debug("%s Fetching HomeGraph...", log_prefix) response = rpc_service.GetHomeGraph(request) LOGGER.debug("%s Storing obtained HomeGraph...", log_prefix) self.homegraph = response self.homegraph_date = datetime.now() except grpc.RpcError as rpc_error: LOGGER.debug("%s Got an RpcError", log_prefix) if (rpc_error.code().name # pylint: disable=no-member == "UNAUTHENTICATED"): LOGGER.warning( "%s The access token has expired. Getting a new one.", log_prefix, ) self.invalidate_access_token() return self.get_homegraph() LOGGER.error( "%s Received unknown RPC error: code=%s message=%s", log_prefix, rpc_error.code(), # pylint: disable=no-member rpc_error.details(), # pylint: disable=no-member ) return self.homegraph
def main(args): # read the file containing a session token to authenticate with token = args.token_file.read().strip() # create the header object for the token callCreds = grpc.access_token_call_credentials(token) # if using a self-signed certificate (should be provided as arg) if args.cert_file: cert = args.cert_file.read() channelCreds = grpc.ssl_channel_credentials(root_certificates=cert) else: # otherwise default to checking against CAs channelCreds = grpc.ssl_channel_credentials() connCreds = grpc.composite_channel_credentials(channelCreds, callCreds) # create a stream request subscribe = services.EventStreamRequest() # create a filter model event_filter = models.Event() if args.event_type: event_filter.event_type.value = args.event_type if args.severity: # enum with val 0 is always unset event_filter.severity = SEVERITIES.index(args.severity) + 1 subscribe.partial_eq_filter.append(event_filter) # initialize a connection to the server using our connection settings (auth + TLS) with grpc.secure_channel(args.server, connCreds) as channel: event_stub = services.EventServiceStub(channel) for resp in event_stub.Subscribe(subscribe, timeout=RPC_TIMEOUT): print(resp.value) print("\n")
def main(): assert TOKEN != '', 'You need to set TOKEN. To obtain your token visit https://cryptomood.com/business/products/sentiment-analysis-api/.' # Create credentials for use with an secured channel credentials = grpc.ssl_channel_credentials(open(PATH_TO_CERT_FILE, 'rb').read()) call_credentials = grpc.access_token_call_credentials(TOKEN) credentials = grpc.composite_channel_credentials(credentials, call_credentials) channel = grpc.secure_channel(SERVER_ADDRESS, credentials) # create stub stub = types_pb2_grpc.SentimentsStub(channel) # create timeframe now = time.time() seconds = int(now) to_time = timestamp_pb2.Timestamp(seconds=seconds - int(86400 / 6)) from_time = timestamp_pb2.Timestamp(seconds=to_time.seconds - int(2 * 86400)) # last two days # in our case we have to use kwarg because `from` is # is recognized as python keyword so there would syntax be error # if you want get value you have to use getattr()} sentiment_historic_request_kwargs = { 'from': from_time, 'to': to_time, 'resolution': 'D1', 'asset': 'BTC' } req = types_pb2.SentimentHistoricRequest(**sentiment_historic_request_kwargs) candle_stream = stub.HistoricSocialSentiment(req) for candle in candle_stream: print(candle.id, candle.a)
def main(args): # read the file containing a session token to authenticate with token = args.token_file.read().strip() # create the header object for the token callCreds = grpc.access_token_call_credentials(token) # if using a self-signed certificate (should be provided as arg) if args.cert_file: # create the channel using the self-signed cert cert = args.cert_file.read() channelCreds = grpc.ssl_channel_credentials(root_certificates=cert) else: # otherwise default to checking against CAs channelCreds = grpc.ssl_channel_credentials() connCreds = grpc.composite_channel_credentials(channelCreds, callCreds) if args.tag_value: tag_value = args.tag_value if args.tag_name: tag_name = args.tag_name # initialize a connection to the server using our connection settings (auth + TLS) with grpc.secure_channel(args.server, connCreds) as channel: tag_stub = services.InterfaceTagConfigServiceStub(channel) req = services.InterfaceTagConfigSetRequest( value=models.InterfaceTagConfig( key=models.TagKey(label=wrappers.StringValue(value=tag_name), value=wrappers.StringValue( value=tag_value)))) tag_stub.Set(req, timeout=RPC_TIMEOUT)
def blockstream_v2(): credentials = grpc.access_token_call_credentials( token_for_api_key(sys.argv[1])) channel = grpc.secure_channel( 'bsc.streamingfast.io:443', credentials=grpc.composite_channel_credentials( grpc.ssl_channel_credentials(), credentials)) return bstream_pb2_grpc.BlockStreamV2Stub(channel)
async def test_async_generator_secure_channel(self): async def request_generator(): for _ in range(self._STREAM_ITERATIONS): yield _STREAM_OUTPUT_REQUEST_ONE_RESPONSE call_credentials = grpc.composite_call_credentials( grpc.access_token_call_credentials("abc"), grpc.access_token_call_credentials("def"), ) call = self._stub.FullDuplexCall(request_generator(), credentials=call_credentials) async for response in call: self.assertEqual(_RESPONSE_PAYLOAD_SIZE, len(response.payload.body)) self.assertEqual(await call.code(), grpc.StatusCode.OK)
def client(endpoint): credentials = grpc.access_token_call_credentials( token_for_api_key(sys.argv[1])) channel = grpc.secure_channel( endpoint, credentials=grpc.composite_channel_credentials( grpc.ssl_channel_credentials(), credentials)) return graphql_pb2_grpc.GraphQLStub(channel)
def create_client(token, endpoint): channel = grpc.secure_channel( endpoint, credentials=grpc.composite_channel_credentials( grpc.ssl_channel_credentials(), grpc.access_token_call_credentials(token))) return graphql_pb2_grpc.GraphQLStub(channel)
def stub(): credentials = grpc.access_token_call_credentials( token_for_api_key(sys.argv[1])) channel = grpc.secure_channel( 'mainnet.eos.dfuse.io:443', credentials=grpc.composite_channel_credentials( grpc.ssl_channel_credentials(), credentials)) return graphql_pb2_grpc.GraphQLStub(channel)
def calculate_request(self, first_number: int, second_number: int): calculate_request = calculate_pb2.CalculateRequest(first_number=first_number, second_number=second_number) auth_credentials = grpc.access_token_call_credentials("Token auth") metadata = [("auth", "toEterdcken")] response = self.stub.calculate(calculate_request, credentials=auth_credentials, metadata=metadata) return json_format.MessageToDict(response, including_default_value_fields=True)
def grpc_authorized_channel(my_channel_ssl_credentials, create_channel): """ Channel with authorization header passed """ grpc_channel_credentials = grpc.access_token_call_credentials("some_token") composite_credentials = grpc.composite_channel_credentials( my_channel_ssl_credentials, grpc_channel_credentials) with create_channel(composite_credentials) as channel: yield channel
def test_channel_credentials_composition(self): first_call_credentials = grpc.access_token_call_credentials('abc') second_call_credentials = grpc.access_token_call_credentials('def') third_call_credentials = grpc.access_token_call_credentials('ghi') channel_credentials = grpc.ssl_channel_credentials() channel_and_first = grpc.composite_channel_credentials( channel_credentials, first_call_credentials) channel_first_and_second = grpc.composite_channel_credentials( channel_credentials, first_call_credentials, second_call_credentials) channel_first_second_and_third = grpc.composite_channel_credentials( channel_credentials, first_call_credentials, second_call_credentials, third_call_credentials) self.assertIsInstance(channel_and_first, grpc.ChannelCredentials) self.assertIsInstance(channel_first_and_second, grpc.ChannelCredentials) self.assertIsInstance( channel_first_second_and_third, grpc.ChannelCredentials)
def _get_credentials(self): token_call_credentials = grpc.access_token_call_credentials(self.auth.token) ssl_channel_credentials = grpc.ssl_channel_credentials(self.certificate) composite_credentials = grpc.composite_channel_credentials( ssl_channel_credentials, token_call_credentials ) return composite_credentials
def _create_grpc_channel(self) -> grpc.aio.Channel: """ Creates a grpc channel for this connection. """ if self._channel_fn: return self._channel_fn(self.url) creds = grpc.ssl_channel_credentials() if self._direct: tok = grpc.access_token_call_credentials(self.token) creds = grpc.composite_channel_credentials(creds, tok) return grpc.aio.secure_channel(self.url, creds)
def __init__(self, url: str, client_id: str, client_secret: str, audience: str): self.url = url self.client_id = client_id self.client_secret = client_secret self.audience = audience self.access_token = self.get_access_token(url, client_id, client_secret, audience) token_credentials = grpc.access_token_call_credentials(self.access_token) ssl_credentials = grpc.ssl_channel_credentials() self.grpc_credentials = grpc.composite_channel_credentials(ssl_credentials, token_credentials)
async def test_unary_stream_async_generator_secure(self): request = messages_pb2.StreamingOutputCallRequest() request.response_parameters.extend( messages_pb2.ResponseParameters(size=_RESPONSE_PAYLOAD_SIZE, ) for _ in range(_NUM_STREAM_RESPONSES)) call_credentials = grpc.composite_call_credentials( grpc.access_token_call_credentials("abc"), grpc.access_token_call_credentials("def"), ) call = self._stub.StreamingOutputCall(request, credentials=call_credentials) async for response in call: self.assertIsInstance(response, messages_pb2.StreamingOutputCallResponse) self.assertEqual(len(response.payload.body), _RESPONSE_PAYLOAD_SIZE) self.assertEqual(await call.code(), grpc.StatusCode.OK)
def connect_user(token): channel = grpc.secure_channel( 'grpc.netograph.io:443', grpc.composite_channel_credentials( grpc.ssl_channel_credentials(), grpc.access_token_call_credentials(token), ), options=common_options, ) return user_pb2_grpc.UserStub(channel)
def connect_dset(token): channel = grpc.secure_channel( 'grpc.netograph.io:443', grpc.composite_channel_credentials( grpc.ssl_channel_credentials(), grpc.access_token_call_credentials(token), ), options=[ ('grpc.ssl_target_name_override', "grpc.netograph.io"), ]) return dset_pb2_grpc.DsetStub(channel)
def get_channel(address, cafile, token, opts=None): if cafile == '': return grpc.insecure_channel(address, opts) else: with open(cafile, 'rb') as f: capem = f.read() creds = grpc.ssl_channel_credentials(root_certificates=capem) if token != '': auth = grpc.access_token_call_credentials(token) return grpc.secure_channel(address, grpc.composite_channel_credentials(creds, auth), opts) else: return grpc.secure_channel(address, creds, opts)
def run(): insecure = os.getenv('INSECURE', 'false').lower() == 'true' credentials = grpc.composite_channel_credentials( grpc.local_channel_credentials() if insecure else grpc.ssl_channel_credentials(), grpc.access_token_call_credentials(os.environ['TOKEN']), ) channel = grpc.secure_channel('localhost:8000', credentials) client = EchoServiceStub(channel) response = client.Echo(EchoRequest(message='hello world')) print("got echo response: " + response.message)
def main(args): token = args.token_file.read().strip() callCreds = grpc.access_token_call_credentials(token) if args.cert_file: cert = args.cert_file.read() channelCreds = grpc.ssl_channel_credentials(root_certificates=cert) else: channelCreds = grpc.ssl_channel_credentials() connCreds = grpc.composite_channel_credentials(channelCreds, callCreds) get_all_req = services.EventStreamRequest() if args.end and not args.start: raise ValueError("--start must be specified when --end is specified") if args.start: if args.start.isdigit(): get_all_req.time.start.FromNanoseconds(int(args.start)) else: get_all_req.time.start.FromJsonString(args.start) # set end to current time in case end is not specified get_all_req.time.end.GetCurrentTime() if args.end: if args.end.isdigit(): get_all_req.time.end.FromNanoseconds(int(args.end)) else: get_all_req.time.end.FromJsonString(args.end) event_filter = models.Event() if args.event_type: event_filter.event_type.value = args.event_type if args.severity: # enum with val 0 is always unset event_filter.severity = SEVERITIES.index(args.severity) + 1 get_all_req.partial_eq_filter.append(event_filter) print(f"selecting events that match the filter {get_all_req}") with grpc.secure_channel(args.server, connCreds) as channel: event_stub = services.EventServiceStub(channel) event_ack_stub = services.EventAnnotationConfigServiceStub(channel) for resp in event_stub.GetAll(get_all_req, timeout=RPC_TIMEOUT): print(f"{resp}") if args.ack and not resp.value.ack.ack.value: print("acking event") req = services.EventAnnotationConfigSetRequest( value=models.EventAnnotationConfig(key=resp.value.key, )) req.value.ack.value = True event_ack_stub.Set(req, timeout=RPC_TIMEOUT)
def create_client(endpoint): dfuse_api_key = os.environ.get("DFUSE_API_KEY") if dfuse_api_key == None: raise Exception( "you must specify a DFUSE_API_KEY environment variable") channel = grpc.secure_channel( endpoint, credentials=grpc.composite_channel_credentials( grpc.ssl_channel_credentials(), grpc.access_token_call_credentials(get_token(dfuse_api_key)))) return graphql_pb2_grpc.GraphQLStub(channel)
def get_devices(self) -> list: # Get Access Token token = self.token_dispener.dispense() # Get Devices on Network creds = grpc.access_token_call_credentials(token) ssl = grpc.ssl_channel_credentials() composite = grpc.composite_channel_credentials(ssl, creds) channel = grpc.secure_channel('googlehomefoyer-pa.googleapis.com:443', composite) service = StructuresServiceStub(channel) grpc_res = service.GetHomeGraph(GetHomeGraphRequest()) return grpc_res.home.devices
def _stub(args): target = '{}:{}'.format(args.server_host, args.server_port) if args.test_case == 'oauth2_auth_token': google_credentials, unused_project_id = google_auth.default( scopes=[args.oauth_scope]) google_credentials.refresh(google_auth.transport.requests.Request()) call_credentials = grpc.access_token_call_credentials( google_credentials.token) elif args.test_case == 'compute_engine_creds': google_credentials, unused_project_id = google_auth.default( scopes=[args.oauth_scope]) call_credentials = grpc.metadata_call_credentials( google_auth.transport.grpc.AuthMetadataPlugin( credentials=google_credentials, request=google_auth.transport.requests.Request())) elif args.test_case == 'jwt_token_creds': google_credentials = google_auth_jwt.OnDemandCredentials.from_service_account_file( os.environ[google_auth.environment_vars.CREDENTIALS]) call_credentials = grpc.metadata_call_credentials( google_auth.transport.grpc.AuthMetadataPlugin( credentials=google_credentials, request=None)) else: call_credentials = None if args.use_tls: if args.use_test_ca: root_certificates = resources.test_root_certificates() else: root_certificates = None # will load default roots. channel_credentials = grpc.ssl_channel_credentials(root_certificates) if call_credentials is not None: channel_credentials = grpc.composite_channel_credentials( channel_credentials, call_credentials) channel_opts = None if args.server_host_override: channel_opts = (( 'grpc.ssl_target_name_override', args.server_host_override, ),) channel = grpc.secure_channel(target, channel_credentials, channel_opts) else: channel = grpc.insecure_channel(target) if args.test_case == "unimplemented_service": return test_pb2_grpc.UnimplementedServiceStub(channel) else: return test_pb2_grpc.TestServiceStub(channel)
def _stub(args): target = '{}:{}'.format(args.server_host, args.server_port) if args.test_case == 'oauth2_auth_token': google_credentials = _application_default_credentials() scoped_credentials = google_credentials.create_scoped( [args.oauth_scope]) access_token = scoped_credentials.get_access_token().access_token call_credentials = grpc.access_token_call_credentials(access_token) elif args.test_case == 'compute_engine_creds': google_credentials = _application_default_credentials() scoped_credentials = google_credentials.create_scoped( [args.oauth_scope]) # TODO(https://github.com/grpc/grpc/issues/6799): Eliminate this last # remaining use of the Beta API. call_credentials = implementations.google_call_credentials( scoped_credentials) elif args.test_case == 'jwt_token_creds': google_credentials = _application_default_credentials() # TODO(https://github.com/grpc/grpc/issues/6799): Eliminate this last # remaining use of the Beta API. call_credentials = implementations.google_call_credentials( google_credentials) else: call_credentials = None if args.use_tls: if args.use_test_ca: root_certificates = resources.test_root_certificates() else: root_certificates = None # will load default roots. channel_credentials = grpc.ssl_channel_credentials(root_certificates) if call_credentials is not None: channel_credentials = grpc.composite_channel_credentials( channel_credentials, call_credentials) channel = grpc.secure_channel(target, channel_credentials, (( 'grpc.ssl_target_name_override', args.server_host_override,),)) else: channel = grpc.insecure_channel(target) if args.test_case == "unimplemented_service": return test_pb2.UnimplementedServiceStub(channel) else: return test_pb2.TestServiceStub(channel)