| 1 |
""" |
| 2 |
Copyright 2020-2024 by J. Christopher Wagner (jwag). All rights reserved. |
| 3 |
:license: MIT, see LICENSE for more details. |
| 4 |
|
| 5 |
This relies on session/session cookie for continued authentication. |
| 6 |
It assumes server is set up to send a CSRF cookie. |
| 7 |
|
| 8 |
We assume server doesn't require CSRF for unauthenticated endpoints. |
| 9 |
|
| 10 |
Note that we have to manually take the CSRF cookie and send it as a header. |
| 11 |
For many JavaScript http clients - they do this as part of default configuration. |
| 12 |
|
| 13 |
""" |
| 14 |
|
| 15 |
import logging |
| 16 |
import random |
| 17 |
import re |
| 18 |
|
| 19 |
import requests |
| 20 |
|
| 21 |
logger = logging.getLogger(__name__) |
| 22 |
|
| 23 |
|
| 24 |
class ApiException(Exception): |
| 25 |
def __init__(self, msg, status_code): |
| 26 |
super().__init__(msg, status_code) |
| 27 |
if isinstance(msg, list): |
| 28 |
self.msg = msg |
| 29 |
else: |
| 30 |
self.msg = [msg] |
| 31 |
self.status_code = status_code |
| 32 |
|
| 33 |
def get_msgs(self): |
| 34 |
return ", ".join(self.msg) |
| 35 |
|
| 36 |
|
| 37 |
def check_error(resp): |
| 38 |
# look for errors from Flask-Security API and throw exception with info |
| 39 |
jresp = resp.json() |
| 40 |
rdata = jresp.get("response") |
| 41 |
if not rdata: |
| 42 |
raise ApiException("Bad Api Response", resp.status_code) |
| 43 |
if "error" in rdata: |
| 44 |
raise ApiException(rdata["error"], resp.status_code) |
| 45 |
if "errors" in rdata: |
| 46 |
# these are form errors a dict of form label: [list of errors] |
| 47 |
msgs = [] |
| 48 |
for label, emsgs in rdata["errors"].items(): |
| 49 |
msgs.extend([f"{label}-{msg}" for msg in emsgs]) |
| 50 |
raise ApiException(msgs, resp.status_code) |
| 51 |
if resp.status_code >= 400: |
| 52 |
raise ApiException("Error status w/o response", resp.status_code) |
| 53 |
return None |
| 54 |
|
| 55 |
|
| 56 |
def register(server_url, session, email, password): |
| 57 |
# Register new email with password |
| 58 |
# Use the backdoor to grab confirmation email and confirm. |
| 59 |
|
| 60 |
resp = session.post( |
| 61 |
f"{server_url}/register", |
| 62 |
json={"email": email, "password": password}, |
| 63 |
) |
| 64 |
check_error(resp) |
| 65 |
|
| 66 |
resp = session.get(f"{server_url}/api/popmail") |
| 67 |
if resp.status_code != 200: |
| 68 |
raise ApiException("popmail error", resp.status_code) |
| 69 |
|
| 70 |
jbody = resp.json() |
| 71 |
|
| 72 |
# Parse for link |
| 73 |
matcher = re.match( |
| 74 |
r".*(http://[^\s*]*).*", jbody["mail"], re.IGNORECASE | re.DOTALL |
| 75 |
) |
| 76 |
magic_link = matcher.group(1) |
| 77 |
|
| 78 |
# Note this simulates someone clicking on the email link - no point in claiming |
| 79 |
# this is json. |
| 80 |
resp = session.get(magic_link, allow_redirects=False) |
| 81 |
assert resp.status_code == 302 |
| 82 |
|
| 83 |
|
| 84 |
def ussetup(server_url, session, password, phone): |
| 85 |
# unified sign in - setup sms with a phone number |
| 86 |
# Use the backdoor to grab verification SMS. |
| 87 |
|
| 88 |
# reset freshness to show how that would work |
| 89 |
resp = session.get(f"{server_url}/api/resetfresh") |
| 90 |
|
| 91 |
csrf_token = session.cookies["XSRF-TOKEN"] |
| 92 |
resp = session.post( |
| 93 |
f"{server_url}/us-setup", |
| 94 |
json={"chosen_method": "us_phone_number", "phone": phone}, |
| 95 |
headers={"X-XSRF-Token": csrf_token}, |
| 96 |
) |
| 97 |
|
| 98 |
# this should be a 401 reauth required |
| 99 |
assert resp.status_code == 401 |
| 100 |
jbody = resp.json() |
| 101 |
assert jbody["response"]["reauth_required"] |
| 102 |
|
| 103 |
# re-verify |
| 104 |
resp = session.post( |
| 105 |
f"{server_url}/us-verify", |
| 106 |
json={"passcode": password}, |
| 107 |
headers={"X-XSRF-Token": csrf_token}, |
| 108 |
) |
| 109 |
assert resp.status_code == 200 |
| 110 |
|
| 111 |
# try again |
| 112 |
resp = session.post( |
| 113 |
f"{server_url}/us-setup", |
| 114 |
json={"chosen_method": "sms", "phone": phone}, |
| 115 |
headers={"X-XSRF-Token": csrf_token}, |
| 116 |
) |
| 117 |
check_error(resp) |
| 118 |
jbody = resp.json() |
| 119 |
state = jbody["response"]["state"] |
| 120 |
|
| 121 |
resp = session.get(f"{server_url}/api/popsms") |
| 122 |
if resp.status_code != 200: |
| 123 |
raise ApiException("popsms error", resp.status_code) |
| 124 |
|
| 125 |
jbody = resp.json() |
| 126 |
code = jbody["sms"].split()[-1].strip(".") |
| 127 |
resp = session.post( |
| 128 |
f"{server_url}/us-setup/{state}", |
| 129 |
json={"passcode": code}, |
| 130 |
headers={"X-XSRF-Token": csrf_token}, |
| 131 |
) |
| 132 |
check_error(resp) |
| 133 |
|
| 134 |
|
| 135 |
def sms_signin(server_url, session, username, phone): |
| 136 |
# Sign in using SMS code. |
| 137 |
session.post( |
| 138 |
f"{server_url}/us-signin/send-code", |
| 139 |
json={"identity": username, "chosen_method": "sms"}, |
| 140 |
) |
| 141 |
|
| 142 |
# Fetch code via test API |
| 143 |
resp = session.get(f"{server_url}/api/popsms") |
| 144 |
if resp.status_code != 200: |
| 145 |
raise ApiException("popsms error", resp.status_code) |
| 146 |
|
| 147 |
jbody = resp.json() |
| 148 |
code = jbody["sms"].split()[-1].strip(".") |
| 149 |
resp = session.post( |
| 150 |
f"{server_url}/us-signin", |
| 151 |
json={"identity": username, "passcode": code}, |
| 152 |
) |
| 153 |
check_error(resp) |
| 154 |
|
| 155 |
|
| 156 |
def runit(): |
| 157 |
session = requests.session() |
| 158 |
session.headers.update( |
| 159 |
{"Accept": "application/json", "Content-Type": "application/json"} |
| 160 |
) |
| 161 |
server_url = "http://localhost:5002" |
| 162 |
|
| 163 |
try: |
| 164 |
username = f"example{str(random.randint(0, 100000))}@me.com" |
| 165 |
mypassword = "a good easy question" |
| 166 |
myphone = "+16505551212" |
| 167 |
|
| 168 |
# New user - register and confirm |
| 169 |
register( |
| 170 |
server_url, |
| 171 |
session, |
| 172 |
username, |
| 173 |
mypassword, |
| 174 |
) |
| 175 |
# verify confirmed and logged in |
| 176 |
resp = session.get(f"{server_url}/api/health") |
| 177 |
assert resp.status_code == 200 |
| 178 |
jresp = resp.json() |
| 179 |
assert jresp["secret"] == "lush oranges" |
| 180 |
|
| 181 |
# Now us-setup to setup a phone number |
| 182 |
ussetup(server_url, session, mypassword, myphone) |
| 183 |
|
| 184 |
# Verify can sign in with SMS |
| 185 |
session.post(f"{server_url}/logout") |
| 186 |
sms_signin(server_url, session, username, myphone) |
| 187 |
|
| 188 |
# verify logged in |
| 189 |
resp = session.get(f"{server_url}/api/health") |
| 190 |
assert resp.status_code == 200 |
| 191 |
jresp = resp.json() |
| 192 |
assert jresp["secret"] == "lush oranges" |
| 193 |
logging.info("Success") |
| 194 |
|
| 195 |
except ApiException as exc: |
| 196 |
logging.error(f"{exc.get_msgs()}") |
| 197 |
|
| 198 |
|
| 199 |
if __name__ == "__main__": |
| 200 |
# Run through simple sequence |
| 201 |
logging.basicConfig(level=logging.INFO) |
| 202 |
runit() |