Skip to content

Commit

Permalink
Code samples for Identity-Aware Proxy (#845)
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewg authored and waprin committed Mar 9, 2017
1 parent 53bebcc commit 1af1c30
Show file tree
Hide file tree
Showing 7 changed files with 422 additions and 0 deletions.
77 changes: 77 additions & 0 deletions iap/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# Identity-Aware Proxy Samples

<!-- auto-doc-link -->
These samples are used on the following documentation pages:

>
* https://cloud.google.com/iap/docs/authentication-howto
* https://cloud.google.com/iap/docs/signed-headers-howto

<!-- end-auto-doc-link -->

## Using make_iap_request

### Google App Engine flexible environment

1. Add the contents of this directory's `requirements.txt` file to the one
inside your application.
2. Copy `make_iap_request.py` into your application.

### Google App Engine standard environment

1. Follow the instructions
in
[Installing a third-party library](https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27#installing_a_third-party_library) to
install the `google-auth` and `requests` libraries into your application.
2. Copy `make_iap_request.py` into the same folder as app.yaml .

### Google Compute Engine or Google Container Engine

1. Enable the IAM API on your project.
2. Create a VM with the IAM scope:
```gcloud compute instances create INSTANCE_NAME
--scopes=https://www.googleapis.com/auth/iam```
3. Give your VM's default service account the `Service Account Actor` role:
```gcloud projects add-iam-policy-binding PROJET_ID
--role=roles/iam.serviceAccountActor
--member=serviceAccount:SERVICE_ACCOUNT```
4. Install the libraries listed in `requirements.txt`, e.g. by running:
```virtualenv/bin/pip install -r requirements.txt```
5. Copy `make_iap_request.py` into your application.

### Using a downloaded service account private key

1. Create a service account and download its private key.
See https://cloud.google.com/iam/docs/creating-managing-service-account-keys
for more information on how to do this.
2. Set the environment variable `GOOGLE_APPLICATION_CREDENTIALS` to the path
to your service account's `.json` file.
3. Install the libraries listed in `requirements.txt`, e.g. by running:
```virtualenv/bin/pip install -r requirements.txt```
4. Copy `make_iap_request.py` into your application.

If you prefer to manage service account credentials manually, this method can
also be used in the App Engine flexible environment, Compute Engine, and
Container Engine. Note that this may be less secure, as anyone who obtains the
service account private key can impersonate that account!

## Using validate_jwt

`validate_jwt` is not compatible with App Engine standard environment;
use App Engine's Users API instead. (See `app_engine_app` for an example
of how to do this.)

For all other environments:

1. Install the libraries listed in `requirements.txt`, e.g. by running:
```virtualenv/bin/pip install -r requirements.txt```
2. Copy `validate_jwt.py` into your application.

## Running Tests

1. Deploy `app_engine_app` to a project.
2. Enable Identity-Aware Proxy on that project's App Engine app.
3. Add the service account you'll be running the test as to the
Identity-Aware Proxy access list for the project.
4. Update iap_test.py with the hostname for your project.
5. Run the command: ```GOOGLE_CLOUD_PROJECT=project-id pytest iap_test.py```
11 changes: 11 additions & 0 deletions iap/app_engine_app/app.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
runtime: python27
api_version: 1
threadsafe: true

handlers:
- url: /.*
script: iap_demo.app

libraries:
- name: webapp2
version: latest
45 changes: 45 additions & 0 deletions iap/app_engine_app/iap_demo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.

"""Demo App Engine standard environment app for Identity-Aware Proxy.
The / handler returns the contents of the JWT header, for use in
iap_test.py.
The /identity handler demonstrates how to use the Google App Engine
standard environment's Users API to obtain the identity of users
authenticated by Identity-Aware Proxy.
To deploy this app, follow the instructions in
https://cloud.google.com/appengine/docs/python/tools/using-libraries-python-27#installing_a_third-party_library
to install the flask library into your application.
"""
import flask

from google.appengine.api import users


app = flask.Flask(__name__)


@app.route('/')
def echo_jwt():
return flask.request.headers.get('x-goog-authenticated-user-jwt')


@app.route('/identity')
def show_identity():
user = users.get_current_user()
return '<p>Authenticated as {} ({}).</p>'.format(
user.email(), user.user_id())
47 changes: 47 additions & 0 deletions iap/iap_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.

"""Test script for Identity-Aware Proxy code samples."""
import os

from gcp.testing.flaky import flaky

import make_iap_request
import validate_jwt


# The hostname of an application protected by Identity-Aware Proxy.
# When a request is made to https://${JWT_REFLECT_HOSTNAME}/, the
# application should respond with the value of the
# X-Goog-Authenticated-User-JWT (and nothing else.) The
# app_engine_app/ subdirectory contains an App Engine standard
# environment app that does this.
GOOGLE_CLOUD_PROJECT = os.getenv('GOOGLE_CLOUD_PROJECT')
assert GOOGLE_CLOUD_PROJECT
JWT_REFLECT_HOSTNAME = '{}.appspot.com'.format(GOOGLE_CLOUD_PROJECT)


@flaky
def test_main(cloud_config, capsys):
# JWTs are obtained by IAP-protected applications whenever an
# end-user makes a request. We've set up an app that echoes back
# the JWT in order to expose it to this test. Thus, this test
# exercises both make_iap_request and validate_jwt.
iap_jwt = make_iap_request.make_iap_request(
'https://{}/'.format(JWT_REFLECT_HOSTNAME))
jwt_validation_result = validate_jwt.validate_iap_jwt(
'https://{}'.format(JWT_REFLECT_HOSTNAME), iap_jwt)
assert jwt_validation_result[0]
assert jwt_validation_result[1]
assert not jwt_validation_result[2]
154 changes: 154 additions & 0 deletions iap/make_iap_request.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# Copyright 2016 Google Inc. All Rights Reserved.
#
# 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.

"""Example use of a service account to authenticate to Identity-Aware Proxy."""

# [START iap_make_request]
import google.auth
import google.auth.app_engine
import google.auth.compute_engine.credentials
import google.auth.iam
from google.auth.transport.requests import Request
import google.oauth2.credentials
import google.oauth2.service_account
import requests
import requests_toolbelt.adapters.appengine
from six.moves import urllib_parse as urlparse


IAM_SCOPE = 'https://www.googleapis.com/auth/iam'
OAUTH_TOKEN_URI = 'https://www.googleapis.com/oauth2/v4/token'


def make_iap_request(url):
"""Makes a request to an application protected by Identity-Aware Proxy.
Args:
url: The Identity-Aware Proxy-protected URL to fetch.
Returns:
The page body, or raises an exception if the page couldn't be retrieved.
"""
# Take the input URL and remove everything except the protocol, domain,
# and port. Examples:
# https://foo.example.com/ => https://foo.example.com
# https://example.com:8443/foo/bar?quuz=quux#lorem =>
# https://example.com:8443
base_url = urlparse.urlunparse(
urlparse.urlparse(url)._replace(path='', query='', fragment=''))

# Figure out what environment we're running in and get some preliminary
# information about the service account.
bootstrap_credentials, _ = google.auth.default(
scopes=[IAM_SCOPE])
if isinstance(bootstrap_credentials,
google.oauth2.credentials.Credentials):
raise Exception('make_iap_request is only supported for service '
'accounts.')
elif isinstance(bootstrap_credentials,
google.auth.app_engine.Credentials):
requests_toolbelt.adapters.appengine.monkeypatch()

# For service account's using the Compute Engine metadata service,
# service_account_email isn't available until refresh is called.
bootstrap_credentials.refresh(Request())

signer_email = bootstrap_credentials.service_account_email
if isinstance(bootstrap_credentials,
google.auth.compute_engine.credentials.Credentials):
# Since the Compute Engine metadata service doesn't expose the service
# account key, we use the IAM signBlob API to sign instead.
# In order for this to work:
#
# 1. Your VM needs the https://www.googleapis.com/auth/iam scope.
# You can specify this specific scope when creating a VM
# through the API or gcloud. When using Cloud Console,
# you'll need to specify the "full access to all Cloud APIs"
# scope. A VM's scopes can only be specified at creation time.
#
# 2. The VM's default service account needs the "Service Account Actor"
# role. This can be found under the "Project" category in Cloud
# Console, or roles/iam.serviceAccountActor in gcloud.
signer = google.auth.iam.Signer(
Request(), bootstrap_credentials, signer_email)
else:
# A Signer object can sign a JWT using the service account's key.
signer = bootstrap_credentials.signer

# Construct OAuth 2.0 service account credentials using the signer
# and email acquired from the bootstrap credentials.
service_account_credentials = google.oauth2.service_account.Credentials(
signer, signer_email, token_uri=OAUTH_TOKEN_URI, additional_claims={
'target_audience': base_url
})

# service_account_credentials gives us a JWT signed by the service
# account. Next, we use that to obtain an OpenID Connect token,
# which is a JWT signed by Google.
google_open_id_connect_token = get_google_open_id_connect_token(
service_account_credentials)

# Fetch the Identity-Aware Proxy-protected URL, including an
# Authorization header containing "Bearer " followed by a
# Google-issued OpenID Connect token for the service account.
resp = requests.get(
url,
headers={'Authorization': 'Bearer {}'.format(
google_open_id_connect_token)})
if resp.status_code == 403:
raise Exception('Service account {} does not have permission to '
'access the IAP-protected application.'.format(
signer_email))
elif resp.status_code != 200:
raise Exception(
'Bad response from application: {!r} / {!r} / {!r}'.format(
resp.status_code, resp.headers, resp.text))
else:
return resp.text


def get_google_open_id_connect_token(service_account_credentials):
"""Get an OpenID Connect token issued by Google for the service account.
This function:
1. Generates a JWT signed with the service account's private key
containing a special "target_audience" claim.
2. Sends it to the OAUTH_TOKEN_URI endpoint. Because the JWT in #1
has a target_audience claim, that endpoint will respond with
an OpenID Connect token for the service account -- in other words,
a JWT signed by *Google*. The aud claim in this JWT will be
set to the value from the target_audience claim in #1.
For more information, see
https://developers.google.com/identity/protocols/OAuth2ServiceAccount .
The HTTP/REST example on that page describes the JWT structure and
demonstrates how to call the token endpoint. (The example on that page
shows how to get an OAuth2 access token; this code is using a
modified version of it to get an OpenID Connect token.)
"""

service_account_jwt = (
service_account_credentials._make_authorization_grant_assertion())
request = google.auth.transport.requests.Request()
body = {
'assertion': service_account_jwt,
'grant_type': google.oauth2._client._JWT_GRANT_TYPE,
}
token_response = google.oauth2._client._token_endpoint_request(
request, OAUTH_TOKEN_URI, body)
return token_response['id_token']

# [END iap_make_request]
5 changes: 5 additions & 0 deletions iap/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
PyJWT==1.4.2
cryptography==1.7.2
google-auth==0.8.0
requests==2.13.0
requests_toolbelt==0.7.1
Loading

0 comments on commit 1af1c30

Please sign in to comment.