Exemple #1
0
def get_signed_url(bucket_name,
                   path,
                   method='GET',
                   expiry=DEFAULT_URL_VALID_SECONDS):
  """Return a signed url."""
  timestamp = _get_expiration_time(expiry)
  blob = '%s\n\n\n%d\n/%s/%s' % (method, timestamp, bucket_name, path)

  local_server = environment.get_value('LOCAL_GCS_SERVER_HOST')
  if local_server:
    url = local_server + '/' + bucket_name
    signed_blob = 'SIGNATURE'
    service_account_name = 'service_account'
  else:
    url = STORAGE_URL % bucket_name
    signed_blob = sign_data(str(blob))
    service_account_name = utils.service_account_email()

  params = {
      'GoogleAccessId': service_account_name,
      'Expires': timestamp,
      'Signature': base64.b64encode(signed_blob),
  }

  return str(url + '/' + path + '?' + urllib.parse.urlencode(params))
Exemple #2
0
def prepare_upload(bucket_name, path, expiry=DEFAULT_URL_VALID_SECONDS):
  """Prepare a signed GCS upload."""
  expiration_time = (
      datetime.datetime.utcnow() + datetime.timedelta(seconds=expiry))

  conditions = [
      {
          'key': path
      },
      {
          'bucket': bucket_name
      },
      ['content-length-range', 0, MAX_UPLOAD_SIZE],
      ['starts-with', '$x-goog-meta-filename', ''],
  ]

  policy = base64.b64encode(
      json.dumps({
          'expiration': expiration_time.isoformat() + 'Z',
          'conditions': conditions,
      }))

  local_server = environment.get_value('LOCAL_GCS_SERVER_HOST')
  if local_server:
    url = local_server
    signature = 'SIGNATURE'
    service_account_name = 'service_account'
  else:
    url = STORAGE_URL % bucket_name
    signature = base64.b64encode(sign_data(policy))
    service_account_name = utils.service_account_email()

  return GcsUpload(url, bucket_name, path, service_account_name, policy,
                   signature)
Exemple #3
0
def sign_data(data):
  """Sign data with the default App Engine service account."""
  iam = googleapiclient.discovery.build('iamcredentials', 'v1')
  service_account = 'projects/-/serviceAccounts/' + utils.service_account_email(
  )

  response = iam.projects().serviceAccounts().signBlob(
      name=service_account,
      body={
          'delegates': [],
          'payload': base64.b64encode(data),
      }).execute()

  try:
    return base64.b64decode(response['signedBlob'])
  except Exception as e:
    raise GcsError('Invalid response: ' + str(e))
Exemple #4
0
    def wrapper(self):
        """Wrapper."""
        try:
            bearer_token = request.headers.get('Authorization', '')
            if not bearer_token.startswith(BEARER_PREFIX):
                raise helpers.UnauthorizedException(
                    'Missing or invalid bearer token.')

            token = bearer_token.split(' ')[1]
            claim = id_token.verify_oauth2_token(token,
                                                 google_requests.Request())
        except google.auth.exceptions.GoogleAuthError as e:
            raise helpers.UnauthorizedException('Invalid ID token.') from e

        if (not claim.get('email_verified')
                or claim.get('email') != utils.service_account_email()):
            raise helpers.UnauthorizedException('Invalid ID token.')

        message = pubsub.raw_message_to_message(
            json.loads(request.data.decode()))
        return func(self, message)
Exemple #5
0
 def test_with_domain(self):
     """Test with a project ID with a domain."""
     os.environ['APPLICATION_ID'] = 'domain.com:project-id'
     self.assertEqual('*****@*****.**',
                      utils.service_account_email())
Exemple #6
0
 def test_plain_project_id(self):
     """Test with a plain project ID."""
     os.environ['APPLICATION_ID'] = 'project-id'
     self.assertEqual('*****@*****.**',
                      utils.service_account_email())