Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add app engine credentials #46

Merged
merged 3 commits into from
Oct 24, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
110 changes: 110 additions & 0 deletions google/auth/app_engine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Google App Engine standard environment credentials.

This module provides authentication for application running on App Engine in
the standard environment using the `App Identity API`_.


.. _App Identity API:
https://cloud.google.com/appengine/docs/python/appidentity/
"""

import datetime

from google.auth import _helpers
from google.auth import credentials
from google.auth import exceptions


This comment was marked as spam.

This comment was marked as spam.

try:
from google.appengine.api import app_identity
except ImportError:
app_identity = None

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.



class Credentials(credentials.Scoped, credentials.Signing,
credentials.Credentials):
"""App Engine standard environment credentials.

These credentials use the App Engine App Idenity API to obtain access

This comment was marked as spam.

This comment was marked as spam.

tokens.
"""

def __init__(self, scopes=None, service_account_id=None):
"""
Args:
scopes (Sequence[str]): Scopes to request from the App Identity
API.
service_account_id (str): The service account ID passed into
:func:`google.appengine.api.app_identity.get_access_token`.
This is not required as the default application service account
ID will be used.

This comment was marked as spam.

This comment was marked as spam.

"""
super(Credentials, self).__init__()
self._scopes = scopes
self._service_account_id = service_account_id

def refresh(self, request):
"""Refresh the access token and scopes.

This comment was marked as spam.

This comment was marked as spam.


Args:
request (google.auth.transport.Request): Unused.

This comment was marked as spam.

This comment was marked as spam.


Raises:
google.auth.exceptions.RefreshError: If the App Engine APIs are
not available.
"""
# pylint: disable=unused-argument

This comment was marked as spam.

This comment was marked as spam.

if not app_identity:

This comment was marked as spam.

This comment was marked as spam.

raise exceptions.RefreshError(
'The App Engine APIs are not available.')

token, ttl = app_identity.get_access_token(
self._scopes, self._service_account_id)
expiry = _helpers.utcnow() + datetime.timedelta(seconds=ttl)

self.token, self.expiry = token, expiry

@property
def requires_scopes(self):
"""Checks if the credentials requires scopes.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.


Returns:
bool: True if there are no scopes set otherwise False.
"""
return True if not self._scopes else False

This comment was marked as spam.

This comment was marked as spam.


@_helpers.copy_docstring(credentials.Scoped)
def with_scopes(self, scopes):
return Credentials(
scopes=scopes, service_account_id=self._service_account_id)

This comment was marked as spam.

This comment was marked as spam.

This comment was marked as spam.


def sign_bytes(self, message):
"""Signs the given message.

This comment was marked as spam.

This comment was marked as spam.


Args:
message (bytes): The message to sign.

Returns:
bytes: The message's cryptographic signature.

Raises:
EnvironmentError: If the App Engine APIs are unavailable.
"""
if not app_identity:

This comment was marked as spam.

This comment was marked as spam.

raise EnvironmentError('The App Engine APIs are not available.')

return app_identity.sign_blob(message)
118 changes: 118 additions & 0 deletions tests/test_app_engine.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import datetime
import sys

import mock
import pytest
from six.moves import reload_module

from google.auth import exceptions


@pytest.fixture
def app_identity_mock(monkeypatch):
"""Mocks the google.appengine.api.app_identity module."""
api_mock = mock.Mock()
app_identity_mock = api_mock.app_identity

monkeypatch.setitem(
sys.modules, 'google.appengine', mock.Mock())
monkeypatch.setitem(
sys.modules, 'google.appengine.api', api_mock)

This comment was marked as spam.

This comment was marked as spam.


from google.appengine.api import app_identity
assert app_identity == app_identity_mock

yield app_identity_mock


@pytest.fixture
def app_engine(app_identity_mock):
from google.auth import app_engine
reload_module(app_engine)

This comment was marked as spam.

This comment was marked as spam.

yield app_engine

This comment was marked as spam.

This comment was marked as spam.



@pytest.fixture
def app_engine_no_apis():
from google.auth import app_engine
reload_module(app_engine)

This comment was marked as spam.

This comment was marked as spam.

yield app_engine


class TestCredentials(object):
def test_default_state(self, app_engine):

This comment was marked as spam.

This comment was marked as spam.

credentials = app_engine.Credentials()

# Not token acquired yet
assert not credentials.valid
# Expiration hasn't been set yet
assert not credentials.expired
# Scopes are required
assert not credentials.scopes
assert credentials.requires_scopes

def test_with_scopes(self, app_engine):
credentials = app_engine.Credentials()

assert not credentials.scopes
assert credentials.requires_scopes

scoped_credentials = credentials.with_scopes(['email'])

assert scoped_credentials.has_scopes(['email'])
assert not scoped_credentials.requires_scopes

@mock.patch(
'google.auth._helpers.utcnow',
return_value=datetime.datetime.min)
def test_refresh(self, now_mock, app_engine, app_identity_mock):
token = 'token'
ttl = 100
app_identity_mock.get_access_token.return_value = (token, ttl)

This comment was marked as spam.

This comment was marked as spam.

credentials = app_engine.Credentials(scopes=['email'])

credentials.refresh(None)

app_identity_mock.get_access_token.assert_called_with(
credentials.scopes, credentials._service_account_id)
assert credentials.token == token
assert credentials.expiry == (
datetime.datetime.min + datetime.timedelta(seconds=ttl))
assert credentials.valid
assert not credentials.expired

def test_refresh_failure(self, app_engine_no_apis):
with pytest.raises(exceptions.RefreshError) as excinfo:
app_engine_no_apis.Credentials().refresh(None)

assert excinfo.match(r'App Engine APIs are not available')

def test_sign_bytes(self, app_engine, app_identity_mock):
app_identity_mock.sign_blob.return_value = mock.sentinel.signature
credentials = app_engine.Credentials()
to_sign = b'123'

signature = credentials.sign_bytes(to_sign)

assert signature == mock.sentinel.signature
app_identity_mock.sign_blob.assert_called_with(to_sign)

def test_sign_bytes_failure(self, app_engine_no_apis):
with pytest.raises(EnvironmentError) as excinfo:
app_engine_no_apis.Credentials().sign_bytes(b'123')

assert excinfo.match(r'App Engine APIs are not available')