def test_to_json_and_from_json(self): credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) json = credentials.to_json() credentials_from_json = Credentials.new_from_json(json) self.assertEqual(credentials.access_token, credentials_from_json.access_token)
def test_to_from_json(self): c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b']) json = c.to_json() c2 = Credentials.new_from_json(json) self.assertEqual(c.access_token, c2.access_token)
def test_get_access_token(self): m = mox.Mox() httplib2_response = m.CreateMock(object) httplib2_response.status = 200 httplib2_request = m.CreateMock(object) httplib2_request.__call__( ('http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire?scope=dummy_scope' )).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}')) m.ReplayAll() credentials = AppAssertionCredentials(['dummy_scope']) http = httplib2.Http() http.request = httplib2_request token = credentials.get_access_token(http=http) self.assertEqual('this-is-a-token', token.access_token) self.assertEqual(None, token.expires_in) m.UnsetStubs() m.VerifyAll()
def test_fail_refresh(self): m = mox.Mox() httplib2_response = m.CreateMock(object) httplib2_response.status = 400 httplib2_request = m.CreateMock(object) httplib2_request.__call__( ('http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire' '?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb' )).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}')) m.ReplayAll() c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b']) try: c._refresh(httplib2_request) self.fail('Should have raised exception on 400') except AccessTokenRefreshError: pass m.UnsetStubs() m.VerifyAll()
def test_get_access_token(self): m = mox.Mox() httplib2_response = m.CreateMock(object) httplib2_response.status = 200 httplib2_request = m.CreateMock(object) httplib2_request.__call__( ('http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire?scope=dummy_scope')).AndReturn( (httplib2_response, '{"accessToken": "this-is-a-token"}')) m.ReplayAll() credentials = AppAssertionCredentials(['dummy_scope']) http = httplib2.Http() http.request = httplib2_request token = credentials.get_access_token(http=http) self.assertEqual('this-is-a-token', token.access_token) self.assertEqual(None, token.expires_in) m.UnsetStubs() m.VerifyAll()
def test_fail_refresh(self): m = mox.Mox() httplib2_response = m.CreateMock(object) httplib2_response.status = 400 httplib2_request = m.CreateMock(object) httplib2_request.__call__(( 'http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire' '?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb' )).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}')) m.ReplayAll() c = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) try: c._refresh(httplib2_request) self.fail('Should have raised exception on 400') except AccessTokenRefreshError: pass m.UnsetStubs() m.VerifyAll()
def main(): # Define three parameters--color, size, count--each time you run the script" parser = argparse.ArgumentParser(description="Write a labeled custom metric.") parser.add_argument("--color", required=True) parser.add_argument("--size", required=True) parser.add_argument("--count", required=True) args = parser.parse_args() # Assign some values that will be used repeatedly. project_id = GetProjectId() now_rfc3339 = GetNowRfc3339() # Create a cloudmonitoring service object. Use OAuth2 credentials. credentials = AppAssertionCredentials( scope="https://www.googleapis.com/auth/monitoring") http = credentials.authorize(httplib2.Http()) service = build(serviceName="cloudmonitoring", version="v2beta2", http=http) try: print "Labels: color: %s, size: %s." % (args.color, args.size) print "Creating custom metric..." CreateCustomMetric(service, project_id) time.sleep(2) print "Writing new data to custom metric timeseries..." WriteCustomMetric(service, project_id, now_rfc3339, args.color, args.size, args.count) print "Reading data from custom metric timeseries..." ReadCustomMetric(service, project_id, now_rfc3339, args.color, args.size) except Exception as e: print "Failed to complete operations on custom metric: exception=%s" % e
def test_to_from_json(self): c = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) json = c.to_json() c2 = Credentials.new_from_json(json) self.assertEqual(c.access_token, c2.access_token)
def test_get_access_token(self): http = mock.MagicMock() http.request = mock.MagicMock(return_value=(mock.Mock( status=200), '{"accessToken": "this-is-a-token"}')) credentials = AppAssertionCredentials(['dummy_scope']) token = credentials.get_access_token(http=http) self.assertEqual('this-is-a-token', token.access_token) self.assertEqual(None, token.expires_in) http.request.assert_called_once_with( 'http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire?scope=dummy_scope')
def main(): project_id = GetProjectId() # Create a cloudmonitoring service to call. Use OAuth2 credentials. credentials = AppAssertionCredentials( scope="https://www.googleapis.com/auth/monitoring") http = credentials.authorize(httplib2.Http()) service = build(serviceName="cloudmonitoring", version="v2beta2", http=http) # Set up the write request. now = GetNowRfc3339() desc = {"project": project_id, "metric": CUSTOM_METRIC_NAME} point = {"start": now, "end": now, "doubleValue": os.getpid()} print "Writing %d at %s" % (point["doubleValue"], now) # Write a new data point. try: write_request = service.timeseries().write( project=project_id, body={"timeseries": [{"timeseriesDesc": desc, "point": point}]}) _ = write_request.execute() # Ignore the response. except Exception as e: print "Failed to write custom metric data: exception=%s" % e raise # propagate exception # Read all data points from the time series. # When a custom metric is created, it may take a few seconds # to propagate throughout the system. Retry a few times. print "Reading data from custom metric timeseries..." read_request = service.timeseries().list( project=project_id, metric=CUSTOM_METRIC_NAME, youngest=now) start = time.time() while True: try: read_response = read_request.execute() for point in read_response["timeseries"][0]["points"]: print " %s: %s" % (point["end"], point["doubleValue"]) break except Exception as e: if time.time() < start + 20: print "Failed to read custom metric data, retrying..." time.sleep(3) else: print "Failed to read custom metric data, aborting: exception=%s" % e raise # propagate exception
def test_get_access_token(self): http = mock.MagicMock() http.request = mock.MagicMock( return_value=(mock.Mock(status=200), '{"accessToken": "this-is-a-token"}')) credentials = AppAssertionCredentials(['dummy_scope']) token = credentials.get_access_token(http=http) self.assertEqual('this-is-a-token', token.access_token) self.assertEqual(None, token.expires_in) http.request.assert_called_exactly_once_with( 'http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire?scope=dummy_scope')
def test_fail_refresh(self): http = mock.MagicMock() http.request = mock.MagicMock(return_value=(mock.Mock(status=400), '{}')) c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b']) self.assertRaises(AccessTokenRefreshError, c.refresh, http)
def test_constructor(self): scope = 'http://example.com/a http://example.com/b' scopes = scope.split() credentials = AppAssertionCredentials(scope=scopes, foo='bar') self.assertEqual(credentials.scope, scope) self.assertEqual(credentials.kwargs, {'foo': 'bar'}) self.assertEqual(credentials.assertion_type, None)
def test_good_refresh(self): http = mock.MagicMock() http.request = mock.MagicMock( return_value=(mock.Mock(status=200), '{"accessToken": "this-is-a-token"}')) c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b']) self.assertEquals(None, c.access_token) c.refresh(http) self.assertEquals('this-is-a-token', c.access_token) http.request.assert_called_exactly_once_with( 'http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire' '?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb')
def test_good_refresh(self): http = mock.MagicMock() http.request = mock.MagicMock( return_value=(mock.Mock(status=200), '{"accessToken": "this-is-a-token"}')) c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b']) self.assertEquals(None, c.access_token) c.refresh(http) self.assertEquals('this-is-a-token', c.access_token) http.request.assert_called_once_with( 'http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire' '?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb')
def test_refresh_failure_400(self): http = mock.MagicMock() content = '{}' http.request = mock.MagicMock( return_value=(mock.Mock(status=400), content)) credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) exception_caught = None try: credentials.refresh(http) except AccessTokenRefreshError as exc: exception_caught = exc self.assertNotEqual(exception_caught, None) self.assertEqual(str(exception_caught), content)
def test_refresh_failure_400(self): http = mock.MagicMock() content = '{}' http.request = mock.MagicMock(return_value=(mock.Mock(status=400), content)) credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) exception_caught = None try: credentials.refresh(http) except AccessTokenRefreshError as exc: exception_caught = exc self.assertNotEqual(exception_caught, None) self.assertEqual(str(exception_caught), content)
def test_refresh_failure_bad_json(self): http = mock.MagicMock() content = '{BADJSON' http.request = mock.MagicMock(return_value=(mock.Mock(status=200), content)) credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) self.assertRaises(AccessTokenRefreshError, credentials.refresh, http)
def main(argv): # Parse the command-line flags. flags = parser.parse_args(argv[1:]) # Obtain service account credentials from virtual machine environment. credentials = AppAssertionCredentials(['https://www.googleapis.com/auth/datastore']) # Create an httplib2.Http object to handle our HTTP requests and authorize # it with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Construct the service object for the interacting with the Compute Engine # API. service = discovery.build(API_NAME, API_VERSION, http=http) for (title, year, peak) in DATA: commit(service.datasets(), title, year, peak)
def test_refresh_failure_404(self): http = mock.MagicMock() content = '{}' http.request = mock.MagicMock(return_value=(mock.Mock(status=404), content)) credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) exception_caught = None try: credentials.refresh(http) except AccessTokenRefreshError as exc: exception_caught = exc self.assertNotEqual(exception_caught, None) expanded_content = content + (' This can occur if a VM was created' ' with no service account or scopes.') self.assertEqual(str(exception_caught), expanded_content)
def test_refresh_failure_404(self): http = mock.MagicMock() content = '{}' http.request = mock.MagicMock( return_value=(mock.Mock(status=404), content)) credentials = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) exception_caught = None try: credentials.refresh(http) except AccessTokenRefreshError as exc: exception_caught = exc self.assertNotEqual(exception_caught, None) expanded_content = content + (' This can occur if a VM was created' ' with no service account or scopes.') self.assertEqual(str(exception_caught), expanded_content)
def test_save_to_well_known_file(self): import os ORIGINAL_ISDIR = os.path.isdir try: os.path.isdir = lambda path: True credentials = AppAssertionCredentials([]) self.assertRaises(NotImplementedError, save_to_well_known_file, credentials) finally: os.path.isdir = ORIGINAL_ISDIR
def _load_credentials(cls, credentials_file_path): if credentials_file_path == GCE_CREDENTIALS: return AppAssertionCredentials(cls._SCOPES) with open(credentials_file_path, 'r') as credentials_file: credentials_json = json.load(credentials_file) if credentials_json.get('type', None): credentials = GoogleCredentials.from_stream(credentials_file_path) credentials = credentials.create_scoped(cls._SCOPES) return credentials return Storage(credentials_file_path).get()
def _refresh_success_helper(self, bytes_response=False): access_token = u'this-is-a-token' return_val = json.dumps({u'accessToken': access_token}) if bytes_response: return_val = _to_bytes(return_val) http = mock.MagicMock() http.request = mock.MagicMock( return_value=(mock.Mock(status=200), return_val)) scopes = ['http://example.com/a', 'http://example.com/b'] credentials = AppAssertionCredentials(scope=scopes) self.assertEquals(None, credentials.access_token) credentials.refresh(http) self.assertEquals(access_token, credentials.access_token) base_metadata_uri = ('http://metadata.google.internal/0.1/meta-data/' 'service-accounts/default/acquire') escaped_scopes = urllib.parse.quote(' '.join(scopes), safe='') request_uri = base_metadata_uri + '?scope=' + escaped_scopes http.request.assert_called_once_with(request_uri)
def _refresh_success_helper(self, bytes_response=False): access_token = u'this-is-a-token' return_val = json.dumps({u'accessToken': access_token}) if bytes_response: return_val = _to_bytes(return_val) http = mock.MagicMock() http.request = mock.MagicMock(return_value=(mock.Mock(status=200), return_val)) scopes = ['http://example.com/a', 'http://example.com/b'] credentials = AppAssertionCredentials(scope=scopes) self.assertEquals(None, credentials.access_token) credentials.refresh(http) self.assertEquals(access_token, credentials.access_token) base_metadata_uri = ('http://metadata.google.internal/0.1/meta-data/' 'service-accounts/default/acquire') escaped_scopes = urllib.parse.quote(' '.join(scopes), safe='') request_uri = base_metadata_uri + '?scope=' + escaped_scopes http.request.assert_called_once_with(request_uri)
def write_to_storage(file_path): '''YOUR CODE HERE''' base_url = 'https://www.googleapis.com/auth/' full_url = base_url + 'devstorage.full_control' service = build( 'storage', 'v1', AppAssertionCredentials(full_url).authorize( httplib2.Http())) media = MediaFileUpload(file_path, mimetype=WAV_TYPE) service.objects().insert( bucket=BUCKET, name=file_path, media_body=media).execute()
def test_good_refresh(self): m = mox.Mox() httplib2_response = m.CreateMock(object) httplib2_response.status = 200 httplib2_request = m.CreateMock(object) httplib2_request.__call__( ('http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire' '?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb' )).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}')) m.ReplayAll() c = AppAssertionCredentials(scope=['http://example.com/a', 'http://example.com/b']) c._refresh(httplib2_request) self.assertEquals('this-is-a-token', c.access_token) m.UnsetStubs() m.VerifyAll()
def test_good_refresh(self): m = mox.Mox() httplib2_response = m.CreateMock(object) httplib2_response.status = 200 httplib2_request = m.CreateMock(object) httplib2_request.__call__(( 'http://metadata.google.internal/0.1/meta-data/service-accounts/' 'default/acquire' '?scope=http%3A%2F%2Fexample.com%2Fa%20http%3A%2F%2Fexample.com%2Fb' )).AndReturn((httplib2_response, '{"accessToken": "this-is-a-token"}')) m.ReplayAll() c = AppAssertionCredentials( scope=['http://example.com/a', 'http://example.com/b']) c._refresh(httplib2_request) self.assertEquals('this-is-a-token', c.access_token) m.UnsetStubs() m.VerifyAll()
def __init__(self, cluster_id, project, zone): """ Initialize the GCEBlockDeviceAPI. :param unicode project: The project where all GCE operations will take place. :param unicode zone: The zone where all GCE operations will take place. """ # TODO(mewert): Also enable credentials via service account private # keys. credentials = AppAssertionCredentials( "https://www.googleapis.com/auth/cloud-platform") self._compute = discovery.build( 'compute', 'v1', credentials=credentials) self._project = project self._zone = zone self._cluster_id = cluster_id
def main(argv): # Parse the command-line flags. flags = parser.parse_args(argv[1:]) # Obtain service account credentials from virtual machine environement. credentials = AppAssertionCredentials(['https://www.googleapis.com/auth/compute']) # Create an httplib2.Http object to handle our HTTP requests and authorize # it with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Construct the service object for the interacting with the Compute Engine # API. service = discovery.build('compute', 'v1', http=http) # Set project, zone, and other constants. URL_PREFIX = 'https://www.googleapis.com/compute' API_VERSION = 'v1' PROJECT_ID = 'your-project-id' PROJECT_URL = '%s/%s/projects/%s' % (URL_PREFIX, API_VERSION, PROJECT_ID) INSTANCE_NAME = 'test-vm-serv-acct' ZONE = 'us-central1-a' MACHINE_TYPE = 'n1-standard-1' IMAGE_PROJECT_ID = 'debian-cloud' IMAGE_PROJECT_URL = '%s/%s/projects/%s' % ( URL_PREFIX, API_VERSION, IMAGE_PROJECT_ID) IMAGE_NAME = 'debian-7-wheezy-v20140807' BODY = { 'name': INSTANCE_NAME, 'tags': { 'items': ['frontend'] }, 'machineType': '%s/zones/%s/machineTypes/%s' % ( PROJECT_URL, ZONE, MACHINE_TYPE), 'disks': [{ 'boot': True, 'type': 'PERSISTENT', 'mode': 'READ_WRITE', 'zone': '%s/zones/%s' % (PROJECT_URL, ZONE), 'initializeParams': { 'sourceImage': '%s/global/images/%s' % (IMAGE_PROJECT_URL, IMAGE_NAME) }, }], 'networkInterfaces': [{ 'accessConfigs': [{ 'name': 'External NAT', 'type': 'ONE_TO_ONE_NAT' }], 'network': PROJECT_URL + '/global/networks/default' }], 'scheduling': { 'automaticRestart': True, 'onHostMaintenance': 'MIGRATE' }, 'serviceAccounts': [{ 'email': 'default', 'scopes': [ 'https://www.googleapis.com/auth/compute', 'https://www.googleapis.com/auth/devstorage.full_control' ] }], } # Build and execute instance insert request. request = service.instances().insert( project=PROJECT_ID, zone=ZONE, body=BODY) try: response = request.execute() except Exception, ex: print 'ERROR: ' + str(ex) sys.exit()
def test_save_to_well_known_file(self): credentials = AppAssertionCredentials([]) self.assertRaises(NotImplementedError, save_to_well_known_file, credentials)
def GetService(): """Create a cloudmonitoring service to call. Use OAuth2 credentials.""" credentials = AppAssertionCredentials( scope="https://www.googleapis.com/auth/monitoring") http = credentials.authorize(httplib2.Http()) return build(serviceName="cloudmonitoring", version="v2beta2", http=http)
def test_create_scoped(self): credentials = AppAssertionCredentials([]) new_credentials = credentials.create_scoped(['dummy_scope']) self.assertNotEqual(credentials, new_credentials) self.assertTrue(isinstance(new_credentials, AppAssertionCredentials)) self.assertEqual('dummy_scope', new_credentials.scope)
def test_serialization_data(self): credentials = AppAssertionCredentials(scope=[]) self.assertRaises(NotImplementedError, getattr, credentials, 'serialization_data')
def test_create_scoped_required_with_scopes(self): credentials = AppAssertionCredentials(['dummy_scope']) self.assertFalse(credentials.create_scoped_required())
def test_create_scoped_required_without_scopes(self): credentials = AppAssertionCredentials([]) self.assertTrue(credentials.create_scoped_required())
def create(self, scope): from oauth2client.gce import AppAssertionCredentials return AppAssertionCredentials(scope=scope)
def main(argv): # Parse the command-line flags. flags = parser.parse_args(argv[1:]) # Obtain service account credentials from virtual machine environement. credentials = AppAssertionCredentials( ['https://www.googleapis.com/auth/compute']) # Create an httplib2.Http object to handle our HTTP requests and authorize # it with our good Credentials. http = httplib2.Http() http = credentials.authorize(http) # Construct the service object for the interacting with the Compute Engine # API. service = discovery.build('compute', 'v1', http=http) # Set project, zone, and other constants. URL_PREFIX = 'https://www.googleapis.com/compute' API_VERSION = 'v1' PROJECT_ID = 'your-project-id' PROJECT_URL = '%s/%s/projects/%s' % (URL_PREFIX, API_VERSION, PROJECT_ID) INSTANCE_NAME = 'test-vm-serv-acct' ZONE = 'us-central1-a' MACHINE_TYPE = 'n1-standard-1' IMAGE_PROJECT_ID = 'debian-cloud' IMAGE_PROJECT_URL = '%s/%s/projects/%s' % (URL_PREFIX, API_VERSION, IMAGE_PROJECT_ID) IMAGE_NAME = 'debian-7-wheezy-v20140807' BODY = { 'name': INSTANCE_NAME, 'tags': { 'items': ['frontend'] }, 'machineType': '%s/zones/%s/machineTypes/%s' % (PROJECT_URL, ZONE, MACHINE_TYPE), 'disks': [{ 'boot': True, 'type': 'PERSISTENT', 'mode': 'READ_WRITE', 'zone': '%s/zones/%s' % (PROJECT_URL, ZONE), 'initializeParams': { 'sourceImage': '%s/global/images/%s' % (IMAGE_PROJECT_URL, IMAGE_NAME) }, }], 'networkInterfaces': [{ 'accessConfigs': [{ 'name': 'External NAT', 'type': 'ONE_TO_ONE_NAT' }], 'network': PROJECT_URL + '/global/networks/default' }], 'scheduling': { 'automaticRestart': True, 'onHostMaintenance': 'MIGRATE' }, 'serviceAccounts': [{ 'email': 'default', 'scopes': [ 'https://www.googleapis.com/auth/compute', 'https://www.googleapis.com/auth/devstorage.full_control' ] }], } # Build and execute instance insert request. request = service.instances().insert(project=PROJECT_ID, zone=ZONE, body=BODY) try: response = request.execute() except Exception, ex: print 'ERROR: ' + str(ex) sys.exit()