def generate_authorization_provider(tenant_id): # Creates an AuthorizationProvider instance based on the environment. if using_cloud_sim: provider = ExampleAuthorizationProvider(tenant_id) elif using_service: if principal == 'user principal': if credentials_file is None: raise IllegalArgumentException( 'Must specify the credentials file path.') provider = SignatureProvider(config_file=credentials_file) elif principal == 'instance principal': if isinstance(endpoint, str): region = Regions.from_region_id(endpoint) else: region = endpoint provider = SignatureProvider.create_with_instance_principal( region=region) elif principal == 'resource principal': provider = SignatureProvider.create_with_resource_principal() else: raise IllegalArgumentException('Must specify the principal.') elif using_on_prem: if user_name is None and password is None: provider = StoreAccessTokenProvider() else: if user_name is None or password is None: raise IllegalArgumentException( 'Please set both the user_name and password.') provider = StoreAccessTokenProvider(user_name, password) else: raise IllegalArgumentException('Please set the test server.') return provider
def testAccessTokenProviderGetAuthStringWithIllegalRequest(self): config = oci.config.from_file(file_location=fake_credentials_file) provider = oci.signer.Signer( config['tenancy'], config['user'], config['fingerprint'], config['key_file'], config.get('pass_phrase'), config.get('key_content')) self.token_provider = SignatureProvider(provider) self.assertRaises(IllegalArgumentException, self.token_provider.get_authorization_string, 'IllegalRequest')
def testAccessTokenProviderGetRegion(self): # no region config = oci.config.from_file(file_location=fake_credentials_file) provider = oci.signer.Signer(config['tenancy'], config['user'], config['fingerprint'], config['key_file'], config.get('pass_phrase'), config.get('key_content')) self.token_provider = SignatureProvider(provider) self.assertIsNone(self.token_provider.get_region()) self.token_provider.close() # region get from provider parameter of constructor provider.region = config['region'] self.token_provider = SignatureProvider(provider) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) self.token_provider.close() # region get from config_file parameter of constructor self.token_provider = SignatureProvider( config_file=fake_credentials_file) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) self.token_provider.close() # region from region parameter of constructor self.token_provider = SignatureProvider( tenant_id='ocid1.tenancy.oc1..tenancy', user_id='ocid1.user.oc1..user', fingerprint='fingerprint', private_key=fake_key_file, region=Regions.US_ASHBURN_1, duration_seconds=5, refresh_ahead=1) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1)
def testNoSQLHandleConfigIllegalInit(self): # illegal endpoint self.assertRaises(IllegalArgumentException, NoSQLHandleConfig, {'IllegalEndpoint': endpoint}) # illegal provider self.assertRaises(IllegalArgumentException, NoSQLHandleConfig, endpoint, provider='IllegalProvider') # no endpoint and provider self.assertRaises(IllegalArgumentException, NoSQLHandleConfig) # only StoreAccessTokenProvider self.assertRaises(IllegalArgumentException, NoSQLHandleConfig, None, StoreAccessTokenProvider()) # only SignatureProvider without region provider = SignatureProvider( tenant_id='ocid1.tenancy.oc1..tenancy', user_id='ocid1.user.oc1..user', fingerprint='fingerprint', private_key=fake_key_file) self.assertRaises(IllegalArgumentException, NoSQLHandleConfig, None, provider) provider.close() # both endpoint and provider, region not match provider = SignatureProvider( tenant_id='ocid1.tenancy.oc1..tenancy', user_id='ocid1.user.oc1..user', fingerprint='fingerprint', private_key=fake_key_file, region=Regions.US_ASHBURN_1) self.assertRaises(IllegalArgumentException, NoSQLHandleConfig, 'us-phoenix-1', provider) provider.close()
def create_handler(oci_config, log_handler): """Create the handle used to perform OCI NoSQL operations on tables. """ sigprov = SignatureProvider(tenant_id=oci_config['tenancy'], user_id=oci_config['user'], private_key=oci_config['key_file'], fingerprint=oci_config['fingerprint']) nosql_handle_config = NoSQLHandleConfig(Regions.SA_SAOPAULO_1) nosql_handle_config.set_authorization_provider(sigprov) nosql_handle_config.set_default_compartment(oci_config['compartment']) nosql_handle_config.set_logger(log_handler) nosql_handle = NoSQLHandle(nosql_handle_config) sigprov.close() return nosql_handle
def testAccessTokenProviderGetAuthStringWithConfigFile(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file, duration_seconds=5, refresh_ahead=1) self.assertRaises( IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request))
def generate_authorization_provider(tenant_id): if is_cloudsim(): authorization_provider = InsecureAuthorizationProvider(tenant_id) elif is_dev_pod() or is_minicloud(): authorization_provider = TestSignatureProvider(tenant_id) elif is_prod_pod(): if iam_principal() == 'user principal': if credentials_file is None: raise IllegalArgumentException( 'Must specify the credentials file path.') authorization_provider = SignatureProvider( config_file=credentials_file) elif iam_principal() == 'instance principal': if isinstance(endpoint, str): region = Regions.from_region_id(endpoint) else: region = endpoint if region is None: authorization_provider = ( SignatureProvider.create_with_instance_principal()) else: authorization_provider = ( SignatureProvider.create_with_instance_principal( region=region)) elif iam_principal() == 'resource principals': authorization_provider = ( SignatureProvider.create_with_resource_principal()) else: raise IllegalArgumentException('Must specify the principal.') elif is_onprem(): if user_name is None and password is None: authorization_provider = StoreAccessTokenProvider() else: if user_name is None or password is None: raise IllegalArgumentException( 'Please set both the user_name and password.') authorization_provider = StoreAccessTokenProvider( user_name, password) else: raise IllegalArgumentException('Please set the test server.') return authorization_provider
def testInstancePrincipalGetAuthString(self): signer = ( oci.auth.signers.InstancePrincipalsSecurityTokenSigner()) self.token_provider = SignatureProvider( signer, duration_seconds=5, refresh_ahead=1) self.assertRaises( IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request))
def testAccessTokenProviderGetAuthStringWithoutConfigFile(self): self.token_provider = SignatureProvider( tenant_id='ocid1.tenancy.oc1..tenancy', user_id='ocid1.user.oc1..user', fingerprint='fingerprint', private_key=fake_key_file, duration_seconds=5, refresh_ahead=1) self.assertRaises( IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request))
def testAccessTokenProviderGetAuthStringWithConfigFile(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file, duration_seconds=5, refresh_ahead=1) self.assertRaises(IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # # Exercise concurrent refresh schedule. The refresh might be # scheduled by NoSQLHandle.get_authorization_string or the refresh # task itself. Start two threads to call the common # SignatureProvider.get_signature_details_internal simultaneously # that would schedule a refresh to simulate this case. # latch = TestSignatureProvider.CountDownLatch(1) threads = list() for i in range(2): t = TestSignatureProvider.TestThread(self, latch) t.start() threads.append(t) latch.count_down() for t in threads: t.join()
def handler(ctx, data: io.BytesIO = None): return_citizens = [] try: provider = SignatureProvider( tenant_id='Your Tenant OCID', user_id='Your User OCID', private_key='location of Pem file', fingerprint='The fingerprint for your key pair goes here', pass_phrase='The pass phrase for your key goes here') compartment = 'Your Compartment Name Goes Here' config = NoSQLHandleConfig(Regions.US_ASHBURN_1, provider) config.set_default_compartment(compartment) logger = logging.getLogger('Citizens') logger.setLevel(logging.WARNING) config.set_logger(logger) handle = NoSQLHandle(config) table_name = 'Citizens' ## Prepare select statement# statement = 'select * from ' + table_name request = PrepareRequest().set_statement(statement) prepared_result = handle.prepare(request) ## Query, using the prepared statement# request = QueryRequest().set_prepared_statement(prepared_result) while True: result = handle.query(request) for r in result.get_results(): return_citizens.append(dict(r)) if request.is_done(): break except (Exception, ValueError) as ex: logging.getLogger().info('error parsing json payload: ' + str(ex)) logging.getLogger().info("Inside OCI function") return response.Response(ctx, response_data=json.dumps(return_citizens), headers={"Content-Type": "application/json"})
def testInstancePrincipalGetRegion(self): self.token_provider = ( SignatureProvider.create_with_instance_principal( region=Regions.US_ASHBURN_1)) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1)
class TestSignatureProvider(unittest.TestCase): if found: def setUp(self): self.base = 'http://localhost:' + str(8000) self._generate_credentials_file() self.token_provider = None # Not matter which request. self.request = TableRequest() self.handle_config = NoSQLHandleConfig(self.base) def tearDown(self): remove(fake_credentials_file) if self.token_provider is not None: self.token_provider.close() self.token_provider = None def testAccessTokenProviderIllegalInit(self): # illegal provider self.assertRaises(IllegalArgumentException, SignatureProvider, 'IllegalProvider') # illegal config_file self.assertRaises( IllegalArgumentException, SignatureProvider, config_file={'config_file': fake_credentials_file}) # illegal profile_name self.assertRaises(IllegalArgumentException, SignatureProvider, profile_name={'profile_name': 'DEFAULT'}) # illegal tenant_id self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id={}, user_id='user', fingerprint='fingerprint', private_key='key') self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='', user_id='user', fingerprint='fingerprint', private_key='key') # illegal user_id self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id={}, fingerprint='fingerprint', private_key='key') self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='', fingerprint='fingerprint', private_key='key') # illegal fingerprint self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint={}, private_key='key') self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='', private_key='key') # illegal private_key self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key={}) self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key='') # illegal pass phrase self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key='key', pass_phrase={}) self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key='key', pass_phrase='') # illegal region self.assertRaises(IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key='key', pass_phrase={}, region='IllegalRegion') # illegal cache duration seconds self.assertRaises(IllegalArgumentException, SignatureProvider, duration_seconds='IllegalDurationSeconds') self.assertRaises(IllegalArgumentException, SignatureProvider, duration_seconds=0) self.assertRaises(IllegalArgumentException, SignatureProvider, duration_seconds=-1) self.assertRaises(IllegalArgumentException, SignatureProvider, duration_seconds=301) # illegal refresh ahead self.assertRaises(IllegalArgumentException, SignatureProvider, refresh_ahead='IllegalRefreshAhead') self.assertRaises(IllegalArgumentException, SignatureProvider, refresh_ahead=0) self.assertRaises(IllegalArgumentException, SignatureProvider, refresh_ahead=-1) def testAccessTokenProviderSetIllegalLogger(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file) self.assertRaises(IllegalArgumentException, self.token_provider.set_logger, 'IllegalLogger') def testAccessTokenProviderGetAuthStringWithIllegalRequest(self): config = oci.config.from_file(file_location=fake_credentials_file) provider = oci.signer.Signer(config['tenancy'], config['user'], config['fingerprint'], config['key_file'], config.get('pass_phrase'), config.get('key_content')) self.token_provider = SignatureProvider(provider) self.assertRaises(IllegalArgumentException, self.token_provider.get_authorization_string, 'IllegalRequest') def testAccessTokenProviderGets(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file) self.assertIsNone(self.token_provider.get_logger()) def testAccessTokenProviderGetAuthStringWithConfigFile(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file, duration_seconds=5, refresh_ahead=1) self.assertRaises(IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # # Exercise concurrent refresh schedule. The refresh might be # scheduled by NoSQLHandle.get_authorization_string or the refresh # task itself. Start two threads to call the common # SignatureProvider.get_signature_details_internal simultaneously # that would schedule a refresh to simulate this case. # latch = TestSignatureProvider.CountDownLatch(1) threads = list() for i in range(2): t = TestSignatureProvider.TestThread(self, latch) t.start() threads.append(t) latch.count_down() for t in threads: t.join() def testAccessTokenProviderGetAuthStringWithoutConfigFile(self): self.token_provider = SignatureProvider( tenant_id='ocid1.tenancy.oc1..tenancy', user_id='ocid1.user.oc1..user', fingerprint='fingerprint', private_key=fake_key_file, duration_seconds=5, refresh_ahead=1) self.assertRaises(IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request)) def testAccessTokenProviderGetRegion(self): # no region config = oci.config.from_file(file_location=fake_credentials_file) provider = oci.signer.Signer(config['tenancy'], config['user'], config['fingerprint'], config['key_file'], config.get('pass_phrase'), config.get('key_content')) self.token_provider = SignatureProvider(provider) self.assertIsNone(self.token_provider.get_region()) self.token_provider.close() # region get from provider parameter of constructor provider.region = config['region'] self.token_provider = SignatureProvider(provider) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) self.token_provider.close() # region get from config_file parameter of constructor self.token_provider = SignatureProvider( config_file=fake_credentials_file) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) self.token_provider.close() # region from region parameter of constructor self.token_provider = SignatureProvider( tenant_id='ocid1.tenancy.oc1..tenancy', user_id='ocid1.user.oc1..user', fingerprint='fingerprint', private_key=fake_key_file, region=Regions.US_ASHBURN_1, duration_seconds=5, refresh_ahead=1) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) if iam_principal() == 'instance principal': def testInstancePrincipalGetAuthString(self): signer = ( oci.auth.signers.InstancePrincipalsSecurityTokenSigner()) self.token_provider = SignatureProvider(signer, duration_seconds=5, refresh_ahead=1) self.assertRaises(IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request)) def testInstancePrincipalGetRegion(self): self.token_provider = ( SignatureProvider.create_with_instance_principal( region=Regions.US_ASHBURN_1)) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) @staticmethod def _generate_credentials_file(): # Generate credentials file if path.exists(fake_credentials_file): remove(fake_credentials_file) with open(fake_credentials_file, 'w') as cred_file: cred_file.write('[DEFAULT]\n') cred_file.write('tenancy=ocid1.tenancy.oc1..tenancy\n') cred_file.write('user=ocid1.user.oc1..user\n') cred_file.write('fingerprint=fingerprint\n') cred_file.write('key_file=' + fake_key_file + '\n') cred_file.write('region=us-ashburn-1\n') class CountDownLatch(object): def __init__(self, count): self._count = count self._lock = Condition() def count_down(self): self._lock.acquire() self._count -= 1 if self._count <= 0: self._lock.notifyAll() self._lock.release() def wait(self, wait_secs=None): self._lock.acquire() if wait_secs is not None: self._lock.wait(wait_secs) else: while self._count > 0: self._lock.wait() self._lock.release() def get_count(self): self._lock.acquire() count = self._count self._lock.release() return count class TestThread(Thread): def __init__(self, outer, latch): super(TestSignatureProvider.TestThread, self).__init__() self._outer = outer self._latch = latch def run(self): self._latch.wait() self._outer.assertIsNotNone(self._outer.token_provider. get_signature_details_internal())
def testAccessTokenProviderGets(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file) self.assertIsNone(self.token_provider.get_logger())
def testAccessTokenProviderSetIllegalLogger(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file) self.assertRaises(IllegalArgumentException, self.token_provider.set_logger, 'IllegalLogger')
# # Creates an instance from SignatureProvider class that is used to authenticate # and authorize access to Oracle NoSQL service. # # For more information, check the SDK documentation at the link below: # https://nosql-python-sdk.readthedocs.io/en/latest/api/borneo.iam.SignatureProvider.html # # #---------------------------------------------------------------------------- # This Git repository belongs to my ([email protected]) studies about # Oracle NoSQL. To known more, check the blog post (pt-br): # # https://blogs.oracle.com/lad-cloud-experts/pt/introducao-ao-oracle-nosql-database-cloud-parte-1 # https://blogs.oracle.com/lad-cloud-experts/pt/introducao-ao-oracle-nosql-database-cloud-parte-2 # --------------------------------------------------------------------------- from borneo.iam import SignatureProvider # create AuthorizationProvider at_provider = SignatureProvider(tenant_id='<your-tenancy-id>', user_id='<your-user-id>', private_key='<path-to-your-private-key-file>', fingerprint='<fingerprint-of-your-public-key>') at_provider.close()
import oci from borneo.iam import SignatureProvider from borneo import NoSQLHandle, NoSQLHandleConfig, Regions, PutRequest, QueryRequest from werkzeug.security import generate_password_hash ## OCI oci_config_file = '../fotogal/oci_config/oci.conf' oci_private_key = '../fotogal/oci_config/oci_api_key.pem' oci_compartment_ocid = 'ocid1.compartment.oc1..aaaaaaaaro7baesjtceeuntyqxajzotsthm4bg46bwumacmbltuhw6gvb2mq' oci_config = oci.config.from_file(oci_config_file, 'DEFAULT') oci_config['key_file'] = oci_private_key ## OCI NoSQL nosql_sig_prov = SignatureProvider(tenant_id=oci_config['tenancy'], user_id=oci_config['user'], private_key=oci_config['key_file'], fingerprint=oci_config['fingerprint']) nosql_config = NoSQLHandleConfig( Regions.SA_SAOPAULO_1).set_authorization_provider( nosql_sig_prov).set_default_compartment(oci_compartment_ocid) nosql_handler = NoSQLHandle(nosql_config) ## OCI Object Storage object_storage = oci.object_storage.ObjectStorageClient(oci_config) def return_random_string(): RANDOM_STR_LENGTH = 50 ts = datetime.datetime.now().strftime('%s')
class TestSignatureProvider(unittest.TestCase): if found: def setUp(self): self.base = 'http://localhost:' + str(8000) self._generate_credentials_file() self.token_provider = None # Not matter which request. self.request = TableRequest() self.handle_config = NoSQLHandleConfig(self.base) def tearDown(self): remove(fake_credentials_file) if self.token_provider is not None: self.token_provider.close() self.token_provider = None def testAccessTokenProviderIllegalInit(self): # illegal provider self.assertRaises(IllegalArgumentException, SignatureProvider, 'IllegalProvider') # illegal config_file self.assertRaises( IllegalArgumentException, SignatureProvider, config_file={'config_file': fake_credentials_file}) # illegal profile_name self.assertRaises(IllegalArgumentException, SignatureProvider, profile_name={'profile_name': 'DEFAULT'}) # illegal tenant_id self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id={}, user_id='user', fingerprint='fingerprint', private_key='key') self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='', user_id='user', fingerprint='fingerprint', private_key='key') # illegal user_id self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id={}, fingerprint='fingerprint', private_key='key') self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='', fingerprint='fingerprint', private_key='key') # illegal fingerprint self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint={}, private_key='key') self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='', private_key='key') # illegal private_key self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key={}) self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key='') # illegal pass phrase self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key='key', pass_phrase={}) self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key='key', pass_phrase='') # illegal region self.assertRaises( IllegalArgumentException, SignatureProvider, tenant_id='tenant', user_id='user', fingerprint='fingerprint', private_key='key', pass_phrase={}, region='IllegalRegion') # illegal cache duration seconds self.assertRaises(IllegalArgumentException, SignatureProvider, duration_seconds='IllegalDurationSeconds') self.assertRaises(IllegalArgumentException, SignatureProvider, duration_seconds=0) self.assertRaises(IllegalArgumentException, SignatureProvider, duration_seconds=-1) self.assertRaises(IllegalArgumentException, SignatureProvider, duration_seconds=301) # illegal refresh ahead self.assertRaises(IllegalArgumentException, SignatureProvider, refresh_ahead='IllegalRefreshAhead') self.assertRaises(IllegalArgumentException, SignatureProvider, refresh_ahead=0) self.assertRaises(IllegalArgumentException, SignatureProvider, refresh_ahead=-1) def testAccessTokenProviderSetIllegalLogger(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file) self.assertRaises(IllegalArgumentException, self.token_provider.set_logger, 'IllegalLogger') def testAccessTokenProviderGetAuthStringWithIllegalRequest(self): config = oci.config.from_file(file_location=fake_credentials_file) provider = oci.signer.Signer( config['tenancy'], config['user'], config['fingerprint'], config['key_file'], config.get('pass_phrase'), config.get('key_content')) self.token_provider = SignatureProvider(provider) self.assertRaises(IllegalArgumentException, self.token_provider.get_authorization_string, 'IllegalRequest') def testAccessTokenProviderGets(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file) self.assertIsNone(self.token_provider.get_logger()) def testAccessTokenProviderGetAuthStringWithConfigFile(self): self.token_provider = SignatureProvider( config_file=fake_credentials_file, duration_seconds=5, refresh_ahead=1) self.assertRaises( IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request)) def testAccessTokenProviderGetAuthStringWithoutConfigFile(self): self.token_provider = SignatureProvider( tenant_id='ocid1.tenancy.oc1..tenancy', user_id='ocid1.user.oc1..user', fingerprint='fingerprint', private_key=fake_key_file, duration_seconds=5, refresh_ahead=1) self.assertRaises( IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request)) def testAccessTokenProviderGetRegion(self): # no region config = oci.config.from_file(file_location=fake_credentials_file) provider = oci.signer.Signer( config['tenancy'], config['user'], config['fingerprint'], config['key_file'], config.get('pass_phrase'), config.get('key_content')) self.token_provider = SignatureProvider(provider) self.assertIsNone(self.token_provider.get_region()) self.token_provider.close() # region get from provider parameter of constructor provider.region = config['region'] self.token_provider = SignatureProvider(provider) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) self.token_provider.close() # region get from config_file parameter of constructor self.token_provider = SignatureProvider( config_file=fake_credentials_file) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) self.token_provider.close() # region from region parameter of constructor self.token_provider = SignatureProvider( tenant_id='ocid1.tenancy.oc1..tenancy', user_id='ocid1.user.oc1..user', fingerprint='fingerprint', private_key=fake_key_file, region=Regions.US_ASHBURN_1, duration_seconds=5, refresh_ahead=1) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) if iam_principal() == 'instance principal': def testInstancePrincipalGetAuthString(self): signer = ( oci.auth.signers.InstancePrincipalsSecurityTokenSigner()) self.token_provider = SignatureProvider( signer, duration_seconds=5, refresh_ahead=1) self.assertRaises( IllegalArgumentException, self.token_provider.get_authorization_string, self.request) self.token_provider.set_service_url(self.handle_config) auth_string = self.token_provider.get_authorization_string( self.request) # Cache duration is about 5s, string should be the same. self.assertEqual( auth_string, self.token_provider.get_authorization_string(self.request)) # Wait for the refresh to complete. sleep(5) # The new signature string should be cached. self.assertNotEqual( auth_string, self.token_provider.get_authorization_string(self.request)) def testInstancePrincipalGetRegion(self): self.token_provider = ( SignatureProvider.create_with_instance_principal( region=Regions.US_ASHBURN_1)) self.assertEqual(self.token_provider.get_region(), Regions.US_ASHBURN_1) @staticmethod def _generate_credentials_file(): # Generate credentials file if path.exists(fake_credentials_file): remove(fake_credentials_file) with open(fake_credentials_file, 'w') as cred_file: cred_file.write('[DEFAULT]\n') cred_file.write('tenancy=ocid1.tenancy.oc1..tenancy\n') cred_file.write('user=ocid1.user.oc1..user\n') cred_file.write('fingerprint=fingerprint\n') cred_file.write('key_file=' + fake_key_file + '\n') cred_file.write('region=us-ashburn-1\n')
# #---------------------------------------------------------------------------- # This Git repository belongs to my ([email protected]) studies about # Oracle NoSQL. To known more, check the blog post (pt-br): # # https://blogs.oracle.com/lad-cloud-experts/pt/introducao-ao-oracle-nosql-database-cloud-parte-1 # https://blogs.oracle.com/lad-cloud-experts/pt/introducao-ao-oracle-nosql-database-cloud-parte-2 # --------------------------------------------------------------------------- from borneo.iam import SignatureProvider from borneo import NoSQLHandleConfig, NoSQLHandle, Regions from borneo import Consistency, QueryRequest # create and close AuthorizationProvider at_provider = SignatureProvider(config_file='~/.oci/config') at_provider.close() # create handle config using a desired region as endpoint and set a # default compartment. handle_config = NoSQLHandleConfig(Regions.SA_SAOPAULO_1) handle_config.set_authorization_provider(at_provider) handle_config.set_default_compartment('<your-compartment-id>') # create the handle. nosql_handle = NoSQLHandle(handle_config) query = """ SELECT propriedades, valor, frete_gratis FROM produtos
def testNoSQLHandleEndpointConfig(self): # set only the host as endpoint config = get_simple_handle_config(tenant_id, 'ndcs.com') self._check_service_url(config, 'https', 'ndcs.com', 443) # set protocol://host as endpoint config = get_simple_handle_config(tenant_id, 'Http://ndcs.com') self._check_service_url(config, 'http', 'ndcs.com', 8080) config = get_simple_handle_config(tenant_id, 'https://ndcs.com') self._check_service_url(config, 'https', 'ndcs.com', 443) # set protocol:host as endpoint config = get_simple_handle_config(tenant_id, 'Http:ndcs.com') self._check_service_url(config, 'http', 'ndcs.com', 8080) config = get_simple_handle_config(tenant_id, 'https:ndcs.com') self._check_service_url(config, 'https', 'ndcs.com', 443) # set host:port as endpoint config = get_simple_handle_config(tenant_id, 'localhost:80') self._check_service_url(config, 'http', 'localhost', 80) config = get_simple_handle_config(tenant_id, 'localhost:443') self._check_service_url(config, 'https', 'localhost', 443) # set protocol://host:port as endpoint config = get_simple_handle_config(tenant_id, 'HTTPS://ndcs.com:8080') self._check_service_url(config, 'https', 'ndcs.com', 8080) # set protocol:host:port as endpoint config = get_simple_handle_config(tenant_id, 'Http:ndcs.com:443') self._check_service_url(config, 'http', 'ndcs.com', 443) # set a Region's id 'us-AshBURN-1' as endpoint. config = get_simple_handle_config(tenant_id, 'us-AshBURN-1') self._check_service_url( config, 'https', 'nosql.us-ashburn-1.oci.oraclecloud.com', 443) # set a Region's id 'US-LangLEY-1' as endpoint. config = get_simple_handle_config(tenant_id, 'US-LangLEY-1') self._check_service_url( config, 'https', 'nosql.us-langley-1.oci.oraclegovcloud.com', 443) # set a Region's id 'UK-GOV-LONDON-1' as endpoint. config = get_simple_handle_config(tenant_id, 'UK-GOV-LONDON-1') self._check_service_url( config, 'https', 'nosql.uk-gov-london-1.oci.oraclegovcloud.uk', 443) # set a Region's id 'Ap-CHiyODA-1' as endpoint. config = get_simple_handle_config(tenant_id, 'Ap-CHiyODA-1') self._check_service_url( config, 'https', 'nosql.ap-chiyoda-1.oci.oraclecloud8.com', 443) # set a Region Regions.US_ASHBURN_1 as endpoint. config = get_simple_handle_config(tenant_id, Regions.US_ASHBURN_1) self._check_service_url( config, 'https', 'nosql.us-ashburn-1.oci.oraclecloud.com', 443) # set a Region Regions.US_LANGLEY_1 as endpoint. config = get_simple_handle_config(tenant_id, Regions.US_LANGLEY_1) self._check_service_url( config, 'https', 'nosql.us-langley-1.oci.oraclegovcloud.com', 443) # set a Region Regions.UK_GOV_LONDON_1 as endpoint. config = get_simple_handle_config(tenant_id, Regions.UK_GOV_LONDON_1) self._check_service_url( config, 'https', 'nosql.uk-gov-london-1.oci.oraclegovcloud.uk', 443) # set a Region Regions.AP_CHIYODA_1 as endpoint. config = get_simple_handle_config(tenant_id, Regions.AP_CHIYODA_1) self._check_service_url( config, 'https', 'nosql.ap-chiyoda-1.oci.oraclecloud8.com', 443) # set a provider with region provider = SignatureProvider( tenant_id='ocid1.tenancy.oc1..tenancy', user_id='ocid1.user.oc1..user', fingerprint='fingerprint', private_key=fake_key_file, region=Regions.US_ASHBURN_1) config = NoSQLHandleConfig(provider=provider) self._check_service_url( config, 'https', 'nosql.us-ashburn-1.oci.oraclecloud.com', 443) self.assertEqual(config.get_region(), Regions.US_ASHBURN_1) # set a endpoint and provider with region config = NoSQLHandleConfig('us-ashburn-1', provider) self._check_service_url( config, 'https', 'nosql.us-ashburn-1.oci.oraclecloud.com', 443) self.assertEqual(config.get_region(), Regions.US_ASHBURN_1) provider.close()