app-MAIL-temp/tests/oauth/test_authorize.py

693 lines
21 KiB
Python
Raw Normal View History

import base64
2019-08-10 17:34:27 +02:00
import json
from urllib.parse import urlparse, parse_qs
from flask import url_for
from app.db import Session
2019-08-10 17:34:27 +02:00
from app.jose_utils import verify_id_token, decode_id_token
2021-08-06 08:46:34 +02:00
from app.models import Client, User, ClientUser
create BaseForm to enable CSRF register page redirect user to dashboard if they are logged in enable csrf for login page Set models more strict bootstrap developer page add helper method to ModelMixin, remove CRUDMixin display list of clients on developer index, add copy client-secret to clipboard using clipboardjs add toastr and use jquery non slim display a toast when user copies the client-secret create new client, generate client-id using unidecode client detail page: can edit client add delete client implement /oauth/authorize and /oauth/allow-deny implement /oauth/token add /oauth/user_info endpoint handle scopes: wip take into account scope: display scope, return user data according to scope create virtual-domain, gen email, client_user model WIP create authorize_nonlogin_user page user can choose to generate a new email no need to interfere with root logger log for before and after request if user has already allowed a client: generate a auth-code and redirect user to client get_user_info takes into account gen email display list of clients that have user has authorised use yk-client domain instead of localhost as cookie depends on the domain name use wtforms instead of flask_wtf Dockerfile delete virtual domain EMAIL_DOMAIN can come from env var bind to host 0.0.0.0 fix signup error: use session as default csrf_context rename yourkey to simplelogin add python-dotenv, ipython, sqlalchemy_utils create DB_URI, FLASK_SECRET. Load config from CONFIG file if exist add shortcuts to logging create shell add psycopg2 do not add local data in Dockerfile add drop_db into shell add shell.prepare_db() fix prepare_db setup sentry copy assets from tabler/dist add icon downloaded from https://commons.wikimedia.org/wiki/File:Simpleicons_Interface_key-tool-1.svg integrate tabler - login and register page add favicon template: default, header. Use gravatar for user avatar url use default template for dashboard, developer page use another icon add clipboard and notie prettify dashboard add notie css add fake gen email and client-user prettify list client page, use notie for toast add email, name scope to new client display client scope in client list prettify new-client, client-detail add sentry-sdk and blinker add arrow, add dt jinja filter, prettify logout, dashboard comment "last used" in dashboard for now prettify date display add copy email to clipboard to dashboard use "users" as table name for User as "user" is reserved key in postgres call prepare_db() when creating new db error page 400, 401, 403, 404 prettify authorize_login_user create already_authorize.html for user who has already authorized a client user can generate new email display all other generated emails add ENV variable, only reset DB when ENV=local fix: not return other users gen emails display nb users for each client refactor shell: remove prepare_db() add sendgrid add /favicon.ico route add new config: URL, SUPPORT_EMAIL, SENDGRID_API_KEY user needs to activate their account before login create copy button on dashboard client can have multiple redirect uris, in client detail can add/remove redirect-uri, use redirect_uri passed in /authorize refactor: move get_user_info into ClientUser model dashboard: display all apps, all generated emails add "id" into user_info add trigger email button invalidate the session at each new version by changing the secret centralize Client creation into Client.create_new user can enable/disable email forwarding setup auto dismiss alert: just add .alert-auto-dismiss move name down in register form add shell.add_real_data move blueprint template to its own package prettify authorize page for non-authenticated user update readme, return error if not redirect_uri add flask-wtf, use psycopg2-binary use flask-wtf FlaskForm instead of Form rename email -> email_utils add AWS_REGION, BUCKET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY to config add s3 module add File model, add Client.icon_id handle client icon update can create client with icon display client icon in client list page add Client.home_url take into account Client.home_url add boto3 register: ask name first only show "trigger test email" if email forwarding is enabled display gen email in alphabetical order, client in client.name alphabetical order better error page the modal does not get close when user clicks outside of modal add Client.published column discover page that displays all published Client add missing bootstrap.bundle.min.js.map developer can publish/unpublish their app in discover use notie for display flash message create hotmail account fix missing jquery add footer, add global jinja2 variable strengthen model: use nullable=False whenever possible, rename client_id to oauth_client_id, client_secret to oauth_client_secret add flask-migrate init migrate 1st migrate version fix rename client_id -> oauth_client_id prettify UI use flask_migrate.upgrade() instead of db.create_all() make sure requirejs.config is called for all page enable sentry for js, use uppercase for global jinja2 variables add flask-admin add User.is_admin column setup flask admin, only accessible to admin user fix migration: add server_default replace session[redirect_after_login] by "next" request args add pyproject.toml: ignore migrations/ in black add register waiting_activation_email page better email wording add pytest add get_host_name_and_scheme and tests example fail test fix test fix client-id display add flask-cors /user_info supports cors, add /me as /user_info synonym return client in /me support implicit flow no need to use with "app.app_context()" add watchtower to requirement add param ENABLE_CLOUDWATCH, CLOUDWATCH_LOG_GROUP, CLOUDWATCH_LOG_STREAM add cloudwatch logger if cloudwatch is enabled add 500 error page add help text for list of used client display list of app/website that an email has been used click on client name brings to client detail page create style.css to add additional style, append its url with the current sha1 to avoid cache POC on how to send email using postfix add sqlalchemy-utils use arrow instead of datetime add new params STRIPE_API, STRIPE_YEARLY_SKU, STRIPE_MONTHLY_PLAN show full error in local add plan, plan_expiration to User, need to create enum directly in migration script, cf https://github.com/sqlalchemy/alembic/issues/67 reformat all html files: use space instead of tab new user will have trial plan for 15 days add new param MAX_NB_EMAIL_FREE_PLAN only user with enough quota can create new email if user cannot create new gen email, pick randomly one from existing gen emails. Use flush instead of commit rename STRIPE_YEARLY_SKU -> STRIPE_YEARLY_PLAN open client page in discover in a new tab add stripe not logging /static call: disable flask logging, replace by after_request add param STRIPE_SECRET_KEY add 3 columns stripe_customer_id, stripe_card_token, stripe_subscription_id user can upgrade their pricing add setting page as coming-soon add GenEmail, ClientUser to admin ignore /admin/static logging add more fake data add ondelete="cascade" whenever possible rename plan_expiration -> trial_expiration reset migration: delete old migrations, create new one rename test_send_email -> poc_send_email to avoid the file being called by pytest add new param LYRA_ANALYTICS_ID, add lyra analytics add how to create new migration into readme add drift to base.html notify admin when new user signs up or pays subscription log exception in case of 500 use sendgrid to notify admin add alias /userinfo to user_info endpoint add change_password to shell add info on how payment is handled invite user to retry if card not working remove drift and add "contact us" link move poc_send_email into poc/ support getting client-id, client-secret from form-data in addition to basic auth client-id, client-secret is passed in form-data by passport-oauth2 for ex add jwtRS256 private and public key add jwk-jws-jwt poc add new param OPENID_PRIVATE_KEY_PATH, OPENID_PRIVATE_KEY_PATH add scope, redirect_url to AuthorizationCode and OauthToken take into scope when creating oauth-token, authorization-code add jwcrypto add jose_utils: make_id_token and verify_id_token add &scope to redirect uri add "email_verified": True into user_info fix user not activated add /oauth2 as alias for /oauth handle case where scope and state are empty remove threaded=False Use Email Alias as wording remove help text user can re-send activation email add "expired" into ActivationCode Handle the case activation code is expired reformat: use form.validate_on_submit instead of request.method == post && form.validate use error text instead of flash() display client oauth-id and oauth-secret on client detail page not display oauth-secret on client listing fix expiration check improve page title, footer add /jwks and /.well-known/openid-configuration init properly tests, fix blueprint conflict bug in flask-admin create oauth_models module rename Scope -> ScopeE to distinguish with Scope DB model set app.url_map.strict_slashes = False use ScopeE instead of SCOPE_NAME, ... support access_token passed as args in /userinfo merge /allow-deny into /authorize improve wording take into account the case response_type=code and openid is in scope take into account response_type=id_token, id_token token, id_token code make sure to use in-memory db in test fix scope can be null allow cross_origin for /.well-known/openid-configuration and /jwks fix footer link center authorize form rename trial_expiration to plan_expiration move stripe init to create_app() use real email to be able to receive email notification add user.profile_picture_id column use user profile picture and fallback to gravatar use nguyenkims+local@gm to distinguish with staging handle plan cancel, reactivation, user profile update fix can_create_new_email create cron.py that set plan to free when expired add crontab.yml add yacron use notify_admin instead of LOG.error add ResetPasswordCode model user can change password in setting increase display time for notie add forgot_password page If login error: redirect to this page upon success login. hide discover tab add column user.is_developer only show developer menu to developer comment out the publish button set local user to developer make sure only developer can access /developer blueprint User is invited to upgrade if they are in free plan or their trial ends soon not sending email when in local mode create Partner model create become partner page use normal error handling on local fix migration add "import sqlalchemy_utils" into migration template small refactoring on setting page handle promo code. TODO: add migration file add migration for user.promo_codes move email alias on top of apps in dashboard add introjs move encode_url to utils create GenEmail.create_new_gen_email create a first alias mail to show user how to use when they login show intro when user visits the website the first time fix register
2019-07-02 09:20:12 +02:00
from app.oauth.views.authorize import (
get_host_name_and_scheme,
generate_access_token,
construct_url,
)
from tests.utils import login
create BaseForm to enable CSRF register page redirect user to dashboard if they are logged in enable csrf for login page Set models more strict bootstrap developer page add helper method to ModelMixin, remove CRUDMixin display list of clients on developer index, add copy client-secret to clipboard using clipboardjs add toastr and use jquery non slim display a toast when user copies the client-secret create new client, generate client-id using unidecode client detail page: can edit client add delete client implement /oauth/authorize and /oauth/allow-deny implement /oauth/token add /oauth/user_info endpoint handle scopes: wip take into account scope: display scope, return user data according to scope create virtual-domain, gen email, client_user model WIP create authorize_nonlogin_user page user can choose to generate a new email no need to interfere with root logger log for before and after request if user has already allowed a client: generate a auth-code and redirect user to client get_user_info takes into account gen email display list of clients that have user has authorised use yk-client domain instead of localhost as cookie depends on the domain name use wtforms instead of flask_wtf Dockerfile delete virtual domain EMAIL_DOMAIN can come from env var bind to host 0.0.0.0 fix signup error: use session as default csrf_context rename yourkey to simplelogin add python-dotenv, ipython, sqlalchemy_utils create DB_URI, FLASK_SECRET. Load config from CONFIG file if exist add shortcuts to logging create shell add psycopg2 do not add local data in Dockerfile add drop_db into shell add shell.prepare_db() fix prepare_db setup sentry copy assets from tabler/dist add icon downloaded from https://commons.wikimedia.org/wiki/File:Simpleicons_Interface_key-tool-1.svg integrate tabler - login and register page add favicon template: default, header. Use gravatar for user avatar url use default template for dashboard, developer page use another icon add clipboard and notie prettify dashboard add notie css add fake gen email and client-user prettify list client page, use notie for toast add email, name scope to new client display client scope in client list prettify new-client, client-detail add sentry-sdk and blinker add arrow, add dt jinja filter, prettify logout, dashboard comment "last used" in dashboard for now prettify date display add copy email to clipboard to dashboard use "users" as table name for User as "user" is reserved key in postgres call prepare_db() when creating new db error page 400, 401, 403, 404 prettify authorize_login_user create already_authorize.html for user who has already authorized a client user can generate new email display all other generated emails add ENV variable, only reset DB when ENV=local fix: not return other users gen emails display nb users for each client refactor shell: remove prepare_db() add sendgrid add /favicon.ico route add new config: URL, SUPPORT_EMAIL, SENDGRID_API_KEY user needs to activate their account before login create copy button on dashboard client can have multiple redirect uris, in client detail can add/remove redirect-uri, use redirect_uri passed in /authorize refactor: move get_user_info into ClientUser model dashboard: display all apps, all generated emails add "id" into user_info add trigger email button invalidate the session at each new version by changing the secret centralize Client creation into Client.create_new user can enable/disable email forwarding setup auto dismiss alert: just add .alert-auto-dismiss move name down in register form add shell.add_real_data move blueprint template to its own package prettify authorize page for non-authenticated user update readme, return error if not redirect_uri add flask-wtf, use psycopg2-binary use flask-wtf FlaskForm instead of Form rename email -> email_utils add AWS_REGION, BUCKET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY to config add s3 module add File model, add Client.icon_id handle client icon update can create client with icon display client icon in client list page add Client.home_url take into account Client.home_url add boto3 register: ask name first only show "trigger test email" if email forwarding is enabled display gen email in alphabetical order, client in client.name alphabetical order better error page the modal does not get close when user clicks outside of modal add Client.published column discover page that displays all published Client add missing bootstrap.bundle.min.js.map developer can publish/unpublish their app in discover use notie for display flash message create hotmail account fix missing jquery add footer, add global jinja2 variable strengthen model: use nullable=False whenever possible, rename client_id to oauth_client_id, client_secret to oauth_client_secret add flask-migrate init migrate 1st migrate version fix rename client_id -> oauth_client_id prettify UI use flask_migrate.upgrade() instead of db.create_all() make sure requirejs.config is called for all page enable sentry for js, use uppercase for global jinja2 variables add flask-admin add User.is_admin column setup flask admin, only accessible to admin user fix migration: add server_default replace session[redirect_after_login] by "next" request args add pyproject.toml: ignore migrations/ in black add register waiting_activation_email page better email wording add pytest add get_host_name_and_scheme and tests example fail test fix test fix client-id display add flask-cors /user_info supports cors, add /me as /user_info synonym return client in /me support implicit flow no need to use with "app.app_context()" add watchtower to requirement add param ENABLE_CLOUDWATCH, CLOUDWATCH_LOG_GROUP, CLOUDWATCH_LOG_STREAM add cloudwatch logger if cloudwatch is enabled add 500 error page add help text for list of used client display list of app/website that an email has been used click on client name brings to client detail page create style.css to add additional style, append its url with the current sha1 to avoid cache POC on how to send email using postfix add sqlalchemy-utils use arrow instead of datetime add new params STRIPE_API, STRIPE_YEARLY_SKU, STRIPE_MONTHLY_PLAN show full error in local add plan, plan_expiration to User, need to create enum directly in migration script, cf https://github.com/sqlalchemy/alembic/issues/67 reformat all html files: use space instead of tab new user will have trial plan for 15 days add new param MAX_NB_EMAIL_FREE_PLAN only user with enough quota can create new email if user cannot create new gen email, pick randomly one from existing gen emails. Use flush instead of commit rename STRIPE_YEARLY_SKU -> STRIPE_YEARLY_PLAN open client page in discover in a new tab add stripe not logging /static call: disable flask logging, replace by after_request add param STRIPE_SECRET_KEY add 3 columns stripe_customer_id, stripe_card_token, stripe_subscription_id user can upgrade their pricing add setting page as coming-soon add GenEmail, ClientUser to admin ignore /admin/static logging add more fake data add ondelete="cascade" whenever possible rename plan_expiration -> trial_expiration reset migration: delete old migrations, create new one rename test_send_email -> poc_send_email to avoid the file being called by pytest add new param LYRA_ANALYTICS_ID, add lyra analytics add how to create new migration into readme add drift to base.html notify admin when new user signs up or pays subscription log exception in case of 500 use sendgrid to notify admin add alias /userinfo to user_info endpoint add change_password to shell add info on how payment is handled invite user to retry if card not working remove drift and add "contact us" link move poc_send_email into poc/ support getting client-id, client-secret from form-data in addition to basic auth client-id, client-secret is passed in form-data by passport-oauth2 for ex add jwtRS256 private and public key add jwk-jws-jwt poc add new param OPENID_PRIVATE_KEY_PATH, OPENID_PRIVATE_KEY_PATH add scope, redirect_url to AuthorizationCode and OauthToken take into scope when creating oauth-token, authorization-code add jwcrypto add jose_utils: make_id_token and verify_id_token add &scope to redirect uri add "email_verified": True into user_info fix user not activated add /oauth2 as alias for /oauth handle case where scope and state are empty remove threaded=False Use Email Alias as wording remove help text user can re-send activation email add "expired" into ActivationCode Handle the case activation code is expired reformat: use form.validate_on_submit instead of request.method == post && form.validate use error text instead of flash() display client oauth-id and oauth-secret on client detail page not display oauth-secret on client listing fix expiration check improve page title, footer add /jwks and /.well-known/openid-configuration init properly tests, fix blueprint conflict bug in flask-admin create oauth_models module rename Scope -> ScopeE to distinguish with Scope DB model set app.url_map.strict_slashes = False use ScopeE instead of SCOPE_NAME, ... support access_token passed as args in /userinfo merge /allow-deny into /authorize improve wording take into account the case response_type=code and openid is in scope take into account response_type=id_token, id_token token, id_token code make sure to use in-memory db in test fix scope can be null allow cross_origin for /.well-known/openid-configuration and /jwks fix footer link center authorize form rename trial_expiration to plan_expiration move stripe init to create_app() use real email to be able to receive email notification add user.profile_picture_id column use user profile picture and fallback to gravatar use nguyenkims+local@gm to distinguish with staging handle plan cancel, reactivation, user profile update fix can_create_new_email create cron.py that set plan to free when expired add crontab.yml add yacron use notify_admin instead of LOG.error add ResetPasswordCode model user can change password in setting increase display time for notie add forgot_password page If login error: redirect to this page upon success login. hide discover tab add column user.is_developer only show developer menu to developer comment out the publish button set local user to developer make sure only developer can access /developer blueprint User is invited to upgrade if they are in free plan or their trial ends soon not sending email when in local mode create Partner model create become partner page use normal error handling on local fix migration add "import sqlalchemy_utils" into migration template small refactoring on setting page handle promo code. TODO: add migration file add migration for user.promo_codes move email alias on top of apps in dashboard add introjs move encode_url to utils create GenEmail.create_new_gen_email create a first alias mail to show user how to use when they login show intro when user visits the website the first time fix register
2019-07-02 09:20:12 +02:00
def test_get_host_name_and_scheme():
assert get_host_name_and_scheme("http://localhost:8000?a=b") == (
"localhost",
"http",
)
assert get_host_name_and_scheme(
"https://www.bubblecode.net/en/2016/01/22/understanding-oauth2/#Implicit_Grant"
) == ("www.bubblecode.net", "https")
def test_generate_access_token(flask_client):
access_token = generate_access_token()
assert len(access_token) == 40
def test_construct_url():
url = construct_url("http://ab.cd", {"x": "1 2"})
assert url == "http://ab.cd?x=1%202"
def test_authorize_page_non_login_user(flask_client):
"""make sure to display login page for non-authenticated user"""
user = User.create("test@test.com", "test user")
Session.commit()
2020-02-27 16:31:38 +01:00
client = Client.create_new("test client", user.id)
Session.commit()
r = flask_client.get(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
response_type="code",
)
)
html = r.get_data(as_text=True)
assert r.status_code == 200
2021-04-06 15:19:28 +02:00
assert "Sign in to accept sharing data with" in html
def test_authorize_page_login_user_non_supported_flow(flask_client):
"""return 400 if the flow is not supported"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
Session.commit()
# Not provide any flow
r = flask_client.get(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
# not provide response_type param here
)
)
# Provide a not supported flow
html = r.get_data(as_text=True)
assert r.status_code == 400
assert "SimpleLogin only support the following OIDC flows" in html
r = flask_client.get(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
# SL does not support this flow combination
response_type="code token id_token",
)
)
html = r.get_data(as_text=True)
assert r.status_code == 400
assert "SimpleLogin only support the following OIDC flows" in html
def test_authorize_page_login_user(flask_client):
"""make sure to display authorization page for authenticated user"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
Session.commit()
r = flask_client.get(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
response_type="code",
)
)
html = r.get_data(as_text=True)
assert r.status_code == 200
assert "a@b.c (Personal Email)" in html
def test_authorize_code_flow_no_openid_scope(flask_client):
"""make sure the authorize redirects user to correct page for the *Code Flow*
and when the *openid* scope is not present
, ie when response_type=code, openid not in scope
"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
Session.commit()
# user allows client on the authorization page
r = flask_client.post(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
response_type="code",
),
data={"button": "allow", "suggested-email": "x@y.z", "suggested-name": "AB CD"},
# user will be redirected to client page, do not allow redirection here
# to assert the redirect url
# follow_redirects=True,
)
assert r.status_code == 302 # user gets redirected back to client page
# r.location will have this form http://localhost?state=teststate&code=knuyjepwvg
o = urlparse(r.location)
assert o.netloc == "localhost"
assert not o.fragment
# parse the query, should return something like
# {'state': ['teststate'], 'code': ['knuyjepwvg']}
queries = parse_qs(o.query)
2019-08-10 17:18:34 +02:00
assert len(queries) == 2
assert queries["state"] == ["teststate"]
assert len(queries["code"]) == 1
# Exchange the code to get access_token
2019-08-10 17:04:43 +02:00
basic_auth_headers = base64.b64encode(
f"{client.oauth_client_id}:{client.oauth_client_secret}".encode()
).decode("utf-8")
r = flask_client.post(
url_for("oauth.token"),
2019-08-10 17:04:43 +02:00
headers={"Authorization": "Basic " + basic_auth_headers},
data={"grant_type": "authorization_code", "code": queries["code"][0]},
)
# r.json should have this format
# {
# 'access_token': 'avmhluhonsouhcwwailydwvhankspptgidoggcbu',
# 'expires_in': 3600,
# 'scope': '',
# 'token_type': 'bearer',
# 'user': {
# 'avatar_url': None,
# 'client': 'test client',
# 'email': 'x@y.z',
# 'email_verified': True,
# 'id': 1,
# 'name': 'AB CD'
# }
# }
assert r.status_code == 200
assert r.json["access_token"]
assert r.json["expires_in"] == 3600
2019-08-11 00:32:00 +02:00
assert not r.json["scope"]
assert r.json["token_type"] == "Bearer"
2021-08-06 08:46:34 +02:00
client_user = ClientUser.first()
assert r.json["user"] == {
"avatar_url": None,
"client": "test client",
"email": "x@y.z",
"email_verified": True,
2021-08-06 08:46:34 +02:00
"id": client_user.id,
"name": "AB CD",
2021-08-06 08:46:34 +02:00
"sub": str(client_user.id),
}
def test_authorize_code_flow_with_openid_scope(flask_client):
"""make sure the authorize redirects user to correct page for the *Code Flow*
and when the *openid* scope is present
, ie when response_type=code, openid in scope
The authorize endpoint should stay the same: return the *code*.
The token endpoint however should now return id_token in addition to the access_token
"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
Session.commit()
# user allows client on the authorization page
r = flask_client.post(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
response_type="code",
scope="openid", # openid is in scope
),
data={"button": "allow", "suggested-email": "x@y.z", "suggested-name": "AB CD"},
# user will be redirected to client page, do not allow redirection here
# to assert the redirect url
# follow_redirects=True,
)
assert r.status_code == 302 # user gets redirected back to client page
# r.location will have this form http://localhost?state=teststate&code=knuyjepwvg
o = urlparse(r.location)
assert o.netloc == "localhost"
assert not o.fragment
# parse the query, should return something like
2019-08-11 00:32:00 +02:00
# {'state': ['teststate'], 'code': ['knuyjepwvg'], 'scope': ["openid"]}
queries = parse_qs(o.query)
2019-08-11 00:32:00 +02:00
assert len(queries) == 3
assert queries["state"] == ["teststate"]
assert len(queries["code"]) == 1
# Exchange the code to get access_token
2019-08-10 17:04:43 +02:00
basic_auth_headers = base64.b64encode(
f"{client.oauth_client_id}:{client.oauth_client_secret}".encode()
).decode("utf-8")
r = flask_client.post(
url_for("oauth.token"),
2019-08-10 17:04:43 +02:00
headers={"Authorization": "Basic " + basic_auth_headers},
data={"grant_type": "authorization_code", "code": queries["code"][0]},
)
# r.json should have this format
# {
# 'access_token': 'avmhluhonsouhcwwailydwvhankspptgidoggcbu',
# 'expires_in': 3600,
# 'scope': '',
# 'token_type': 'bearer',
# 'user': {
# 'avatar_url': None,
# 'client': 'test client',
# 'email': 'x@y.z',
# 'email_verified': True,
# 'id': 1,
# 'name': 'AB CD'
# }
# }
assert r.status_code == 200
assert r.json["access_token"]
assert r.json["expires_in"] == 3600
2019-08-11 00:32:00 +02:00
assert r.json["scope"] == "openid"
assert r.json["token_type"] == "Bearer"
2021-08-06 08:46:34 +02:00
client_user = ClientUser.first()
assert r.json["user"] == {
"avatar_url": None,
"client": "test client",
"email": "x@y.z",
"email_verified": True,
2021-08-06 08:46:34 +02:00
"id": client_user.id,
"name": "AB CD",
2021-08-06 08:46:34 +02:00
"sub": str(client_user.id),
}
# id_token must be returned
assert r.json["id_token"]
# id_token must be a valid, correctly signed JWT
assert verify_id_token(r.json["id_token"])
2019-08-10 17:11:47 +02:00
def test_authorize_token_flow(flask_client):
"""make sure the authorize redirects user to correct page for the *Token Flow*
, ie when response_type=token
The /authorize endpoint should return an access_token
"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
Session.commit()
2019-08-10 17:11:47 +02:00
# user allows client on the authorization page
r = flask_client.post(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
response_type="token", # token flow
),
data={"button": "allow", "suggested-email": "x@y.z", "suggested-name": "AB CD"},
# user will be redirected to client page, do not allow redirection here
# to assert the redirect url
# follow_redirects=True,
)
assert r.status_code == 302 # user gets redirected back to client page
# r.location will have this form http://localhost?state=teststate&code=knuyjepwvg
o = urlparse(r.location)
assert o.netloc == "localhost"
# in token flow, access_token is in fragment and not query
assert o.fragment
assert not o.query
# parse the fragment, should return something like
2019-08-10 17:18:34 +02:00
# {'state': ['teststate'], 'access_token': ['knuyjepwvg']}
2019-08-10 17:11:47 +02:00
queries = parse_qs(o.fragment)
2019-08-10 17:18:34 +02:00
assert len(queries) == 2
2019-08-10 17:11:47 +02:00
assert queries["state"] == ["teststate"]
# access_token must be returned
assert len(queries["access_token"]) == 1
2019-08-10 17:18:34 +02:00
def test_authorize_id_token_flow(flask_client):
"""make sure the authorize redirects user to correct page for the *ID-Token Flow*
, ie when response_type=id_token
The /authorize endpoint should return an id_token
"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
Session.commit()
2019-08-10 17:18:34 +02:00
# user allows client on the authorization page
r = flask_client.post(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
response_type="id_token", # id_token flow
),
data={"button": "allow", "suggested-email": "x@y.z", "suggested-name": "AB CD"},
# user will be redirected to client page, do not allow redirection here
# to assert the redirect url
# follow_redirects=True,
)
assert r.status_code == 302 # user gets redirected back to client page
# r.location will have this form http://localhost?state=teststate&code=knuyjepwvg
o = urlparse(r.location)
assert o.netloc == "localhost"
assert not o.fragment
assert o.query
# parse the fragment, should return something like
# {'state': ['teststate'], 'id_token': ['knuyjepwvg']}
queries = parse_qs(o.query)
assert len(queries) == 2
assert queries["state"] == ["teststate"]
# access_token must be returned
assert len(queries["id_token"]) == 1
# id_token must be a valid, correctly signed JWT
assert verify_id_token(queries["id_token"][0])
2019-08-10 17:34:27 +02:00
def test_authorize_token_id_token_flow(flask_client):
"""make sure the authorize redirects user to correct page for the *ID-Token Token Flow*
, ie when response_type=id_token,token
The /authorize endpoint should return an id_token and access_token
id_token, once decoded, should contain *at_hash* in payload
"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
Session.commit()
2019-08-10 17:34:27 +02:00
# user allows client on the authorization page
r = flask_client.post(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
response_type="id_token token", # id_token,token flow
),
data={"button": "allow", "suggested-email": "x@y.z", "suggested-name": "AB CD"},
# user will be redirected to client page, do not allow redirection here
# to assert the redirect url
# follow_redirects=True,
)
assert r.status_code == 302 # user gets redirected back to client page
# r.location will have this form http://localhost?state=teststate&code=knuyjepwvg
o = urlparse(r.location)
assert o.netloc == "localhost"
assert o.fragment
assert not o.query
# parse the fragment, should return something like
# {'state': ['teststate'], 'id_token': ['knuyjepwvg']}
queries = parse_qs(o.fragment)
assert len(queries) == 3
assert queries["state"] == ["teststate"]
# access_token must be returned
assert len(queries["id_token"]) == 1
assert len(queries["access_token"]) == 1
# id_token must be a valid, correctly signed JWT
id_token = queries["id_token"][0]
assert verify_id_token(id_token)
# make sure jwt has all the necessary fields
jwt = decode_id_token(id_token)
# payload should have this format
# {
# 'at_hash': 'jLDmoGpuOIHwxeyFEe9SKw',
# 'aud': 'testclient-sywcpwsyua',
# 'auth_time': 1565450736,
# 'avatar_url': None,
# 'client': 'test client',
# 'email': 'x@y.z',
# 'email_verified': True,
# 'exp': 1565454336,
# 'iat': 1565450736,
# 'id': 1,
# 'iss': 'http://localhost',
# 'name': 'AB CD',
# 'sub': '1'
# }
payload = json.loads(jwt.claims)
# at_hash MUST be present when the flow is id_token,token
assert "at_hash" in payload
assert "aud" in payload
assert "auth_time" in payload
assert "avatar_url" in payload
assert "client" in payload
assert "email" in payload
assert "email_verified" in payload
assert "exp" in payload
assert "iat" in payload
assert "id" in payload
assert "iss" in payload
assert "name" in payload
assert "sub" in payload
2019-08-11 11:56:30 +02:00
def test_authorize_code_id_token_flow(flask_client):
"""make sure the authorize redirects user to correct page for the *ID-Token Code Flow*
, ie when response_type=id_token,code
The /authorize endpoint should return an id_token, code and id_token must contain *c_hash*
The /token endpoint must return a access_token and an id_token
"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
Session.commit()
2019-08-11 11:56:30 +02:00
# user allows client on the authorization page
r = flask_client.post(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://localhost",
response_type="id_token code", # id_token,code flow
),
data={"button": "allow", "suggested-email": "x@y.z", "suggested-name": "AB CD"},
# user will be redirected to client page, do not allow redirection here
# to assert the redirect url
# follow_redirects=True,
)
assert r.status_code == 302 # user gets redirected back to client page
# r.location will have this form http://localhost?state=teststate&code=knuyjepwvg
o = urlparse(r.location)
assert o.netloc == "localhost"
assert not o.fragment
assert o.query
# parse the query, should return something like
# {'state': ['teststate'], 'id_token': ['knuyjepwvg'], 'code': ['longstring']}
queries = parse_qs(o.query)
assert len(queries) == 3
assert queries["state"] == ["teststate"]
assert len(queries["id_token"]) == 1
assert len(queries["code"]) == 1
# id_token must be a valid, correctly signed JWT
id_token = queries["id_token"][0]
assert verify_id_token(id_token)
# make sure jwt has all the necessary fields
jwt = decode_id_token(id_token)
# payload should have this format
# {
# 'at_hash': 'jLDmoGpuOIHwxeyFEe9SKw',
# 'aud': 'testclient-sywcpwsyua',
# 'auth_time': 1565450736,
# 'avatar_url': None,
# 'client': 'test client',
# 'email': 'x@y.z',
# 'email_verified': True,
# 'exp': 1565454336,
# 'iat': 1565450736,
# 'id': 1,
# 'iss': 'http://localhost',
# 'name': 'AB CD',
# 'sub': '1'
# }
payload = json.loads(jwt.claims)
# at_hash MUST be present when the flow is id_token,token
assert "c_hash" in payload
assert "aud" in payload
assert "auth_time" in payload
assert "avatar_url" in payload
assert "client" in payload
assert "email" in payload
assert "email_verified" in payload
assert "exp" in payload
assert "iat" in payload
assert "id" in payload
assert "iss" in payload
assert "name" in payload
assert "sub" in payload
# <<< Exchange the code to get access_token >>>
basic_auth_headers = base64.b64encode(
f"{client.oauth_client_id}:{client.oauth_client_secret}".encode()
).decode("utf-8")
r = flask_client.post(
url_for("oauth.token"),
headers={"Authorization": "Basic " + basic_auth_headers},
data={"grant_type": "authorization_code", "code": queries["code"][0]},
)
# r.json should have this format
# {
# 'access_token': 'avmhluhonsouhcwwailydwvhankspptgidoggcbu',
# 'id_token': 'ab.cd.xy',
# 'expires_in': 3600,
# 'scope': '',
# 'token_type': 'bearer',
# 'user': {
# 'avatar_url': None,
# 'client': 'test client',
# 'email': 'x@y.z',
# 'email_verified': True,
# 'id': 1,
# 'name': 'AB CD'
# }
# }
assert r.status_code == 200
assert r.json["access_token"]
assert r.json["expires_in"] == 3600
assert not r.json["scope"]
assert r.json["token_type"] == "Bearer"
2021-08-06 08:46:34 +02:00
client_user = ClientUser.first()
2019-08-11 11:56:30 +02:00
assert r.json["user"] == {
"avatar_url": None,
"client": "test client",
"email": "x@y.z",
"email_verified": True,
2021-08-06 08:46:34 +02:00
"id": client_user.id,
2019-08-11 11:56:30 +02:00
"name": "AB CD",
2021-08-06 08:46:34 +02:00
"sub": str(client_user.id),
2019-08-11 11:56:30 +02:00
}
# id_token must be returned
assert r.json["id_token"]
# id_token must be a valid, correctly signed JWT
assert verify_id_token(r.json["id_token"])
def test_authorize_page_invalid_client_id(flask_client):
"""make sure to redirect user to redirect_url?error=invalid_client_id"""
user = login(flask_client)
2020-12-06 14:51:13 +01:00
Client.create_new("test client", user.id)
Session.commit()
r = flask_client.get(
url_for(
"oauth.authorize",
client_id="invalid_client_id",
state="teststate",
redirect_uri="http://localhost",
response_type="code",
)
)
assert r.status_code == 302
assert (
r.location
== "http://localhost?error=invalid_client_id&client_id=invalid_client_id"
)
def test_authorize_page_http_not_allowed(flask_client):
"""make sure to redirect user to redirect_url?error=http_not_allowed"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
2021-04-01 18:17:27 +02:00
client.approved = True
Session.commit()
r = flask_client.get(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="http://mywebsite.com",
response_type="code",
)
)
assert r.status_code == 302
assert r.location == "http://mywebsite.com?error=http_not_allowed"
def test_authorize_page_unknown_redirect_uri(flask_client):
"""make sure to redirect user to redirect_url?error=unknown_redirect_uri"""
user = login(flask_client)
client = Client.create_new("test client", user.id)
2021-04-01 18:17:27 +02:00
client.approved = True
Session.commit()
r = flask_client.get(
url_for(
"oauth.authorize",
client_id=client.oauth_client_id,
state="teststate",
redirect_uri="https://unknown.com",
response_type="code",
)
)
assert r.status_code == 302
assert r.location == "https://unknown.com?error=unknown_redirect_uri"