Skip to content

Commit

Permalink
Client handling improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
OllieJC committed Sep 14, 2023
1 parent e9412ee commit 8a60308
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 11 deletions.
13 changes: 6 additions & 7 deletions sso_data_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,8 @@ def delete_file(filename: str, bucket_type: str = "sessions") -> bool:

def read_all_files(
folder: str = "", default: str = None, bucket_type: str = "sessions"
) -> list:
res = []
keys = []
) -> dict:
res = {}

if USE_AWS_S3_SESSIONS:
try:
Expand All @@ -139,7 +138,7 @@ def read_all_files(
)
if "Contents" in s3_res:
for key in s3_res["Contents"]:
keys.append(key["Key"])
res[key["Key"]] = None
except Exception as e:
jprint({"function": "read_all_files", "error": str(e)})
else:
Expand All @@ -151,12 +150,12 @@ def read_all_files(
os.path.normpath(folder),
)
):
keys.append(os.path.join(folder, filename))
res[os.path.join(folder, filename)] = None

for key in keys:
for key in res:
fres = read_file(key, default, bucket_type)
if fres:
res.append(fres)
res[key] = fres

return res

Expand Down
19 changes: 16 additions & 3 deletions sso_oidc.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,26 @@ def get_clients() -> dict:
res = {}

from_files = read_all_files(bucket_type="clients")
for fc in from_files:
for fn in from_files:
fc = from_files[fn]
if fc and fc.startswith("{"):
res.update(json.loads(fc))
try:
res.update(json.loads(fc))
except Exception as e:
jprint({"function": "get_clients", "file": fn, "error": str(e)})

from_env = env_var("OAUTH_CLIENTS_JSON_OBJECT")
if from_env and from_env.startswith("{"):
res.update(json.loads(from_env))
try:
res.update(json.loads(from_env))
except Exception as e:
jprint(
{
"function": "get_clients",
"env_var": "OAUTH_CLIENTS_JSON_OBJECT",
"error": str(e),
}
)

if not IS_PROD:
jprint({"function": "get_clients", "clients": res})
Expand Down
49 changes: 49 additions & 0 deletions sso_oidc_client_generation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import uuid
import json
import re

from sso_utils import random_string


def generate_client_auth_pair():
"""
Returns a valid client ID and secret
>>> gc = generate_client_auth_pair()
>>> "client_id" in gc
True
>>> len(gc["client_id"])
36
>>> "client_secret" in gc
True
>>> len(gc["client_secret"])
64
"""
client_id = str(uuid.uuid4())

if not re.match(r"^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$", client_id):
raise Exception("Unexpected client_id format!")

cspf = "ssosecgovuk"
cs1_len = 21
cs1 = random_string(length=cs1_len)
cs2_len = 30
cs2 = random_string(length=cs2_len)
client_secret = f"{cspf}-{cs1}-{cs2}"

if not re.match(
rf"^{cspf}\-[A-Za-z0-9]{{{cs1_len}}}\-[A-Za-z0-9]{{{cs2_len}}}$", client_secret
):
raise Exception("Unexpected client_secret format!")

return {"client_id": client_id, "client_secret": client_secret}


if __name__ == "__main__":
import doctest

flags = doctest.REPORT_NDIFF | doctest.FAIL_FAST
fail, total = doctest.testmod(optionflags=flags)

if not fail:
print(json.dumps(generate_client_auth_pair(), default=str, indent=2))
3 changes: 2 additions & 1 deletion sso_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import random
import secrets
import string
import re
import json
Expand Down Expand Up @@ -140,7 +141,7 @@ def random_string(
chars = string.digits
else:
chars = string.digits + string.ascii_letters
res = "".join(random.choice(chars) for i in range(length))
res = "".join(secrets.choice(chars) for _ in range(length))
if lower:
res = res.lower()
return res
Expand Down

0 comments on commit 8a60308

Please sign in to comment.