Пример #1
0
 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)
Пример #2
0
 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)
Пример #3
0
  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)
Пример #4
0
    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()
Пример #5
0
    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()
Пример #6
0
    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)
Пример #7
0
    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)
Пример #8
0
 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
Пример #9
0
    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()
Пример #10
0
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()
Пример #11
0
    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')
Пример #12
0
  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')
Пример #13
0
    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
Пример #14
0
    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)
Пример #15
0
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)
Пример #16
0
    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)
Пример #17
0
    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)
Пример #18
0
    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()
Пример #19
0
 def test_save_to_well_known_file(self):
     credentials = AppAssertionCredentials([])
     self.assertRaises(NotImplementedError, save_to_well_known_file,
                       credentials)
Пример #20
0
 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)
Пример #21
0
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)
Пример #22
0
 def test_serialization_data(self):
     credentials = AppAssertionCredentials(scope=[])
     self.assertRaises(NotImplementedError, getattr, credentials,
                       'serialization_data')
    def create(self, scope):
        from oauth2client.gce import AppAssertionCredentials

        return AppAssertionCredentials(scope=scope)
Пример #24
0
 def test_create_scoped_required_without_scopes(self):
     credentials = AppAssertionCredentials([])
     self.assertTrue(credentials.create_scoped_required())
Пример #25
0
 def test_create_scoped_required_with_scopes(self):
     credentials = AppAssertionCredentials(['dummy_scope'])
     self.assertFalse(credentials.create_scoped_required())
Пример #26
0
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()