Skip to content

Commit 5d1d04b

Browse files
committed
tests: decryoted AUTH utility
1 parent f497c16 commit 5d1d04b

6 files changed

Lines changed: 131 additions & 5 deletions

File tree

.gitignore

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ setup.py
77
scratchattach/test.py
88
scratchattach.code-workspace
99
**/.DS_Store
10-
setup.py
11-
setup.py
1210
.env
1311
tests/manual_tests/**
12+
tests/util/localauth.toml
13+
.venv

tests/test_auth.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,11 @@
11
import sys
22
import os
3+
import util
4+
35

46
def test_import():
5-
sys.path.insert(0, ".")
7+
sys.path.insert(0, ".")
68

7-
assert "FERNET_KEY" in os.environ
8-
assert len(os.environ["FERNET_KEY"]) == 32
9+
assert "FERNET_KEY" in os.environ
10+
assert len(os.environ["FERNET_KEY"]) == 32
11+
assert util.AUTH["test"]["note"]

tests/util/__init__.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# utility methods for testing
2+
# includes special handlers for authentication etc.
3+
from .keyhandler import AUTH

tests/util/__main__.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
# allows you to generate encrypted data
2+
3+
import argparse
4+
5+
import secrets
6+
7+
try:
8+
from .keyhandler import FERNET
9+
except ImportError:
10+
from keyhandler import FERNET
11+
12+
13+
def gen_keystr():
14+
return secrets.token_urlsafe(32)
15+
16+
17+
def main():
18+
class Args(argparse.Namespace):
19+
command: str
20+
content: str
21+
22+
parser = argparse.ArgumentParser()
23+
24+
if command := parser.add_subparsers(dest="command"):
25+
if encrypt := command.add_parser("e", help="Encrypt content"):
26+
encrypt.add_argument("content", nargs="?")
27+
if decrypt := command.add_parser("d", help="Decrypt content"):
28+
decrypt.add_argument("content", nargs="?")
29+
if keygen := command.add_parser("keygen", help="Generate a key. You could set this to $FERNET_KEY if you want"):
30+
...
31+
32+
args = parser.parse_args(namespace=Args())
33+
34+
match args.command:
35+
case "e":
36+
if not args.content:
37+
args.content = input("content: ")
38+
print(FERNET.encrypt(args.content.encode()).decode())
39+
40+
case "d":
41+
if not args.content:
42+
args.content = input("content: ")
43+
print(FERNET.decrypt(args.content.encode()).decode())
44+
45+
case "keygen":
46+
print(gen_keystr())
47+
48+
49+
if __name__ == "__main__":
50+
main()

tests/util/auth.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Encrypted authentication data using the FERNET_KEY
2+
# If you want to set local auth data, make a file 'localauth.toml' in this same directory.
3+
# any values - that be entire categories - in localauth will overwrite those in auth.toml
4+
5+
[test]
6+
# this key is just used to test if auth is working
7+
note = "gAAAAABozoVANH3_fARiCOFvv-O6pHd8DU2kb5vzs7xIxzE3JoWnsFByK5LdoLnnfh0pXpmSpo0KS1j4uwl3XvF-Qm3Sm63Fwy_H224EAdqF_d2hWdVxJkn7HmAJTT445AyrtdFYgrg9"

tests/util/keyhandler.py

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import warnings
2+
import os
3+
import tomllib
4+
from pathlib import Path
5+
from typing import TypeVar
6+
7+
from cryptography.fernet import Fernet
8+
from base64 import urlsafe_b64encode
9+
10+
11+
def str_2_key(gen: str) -> bytes:
12+
if (length := len(gen)) < 32:
13+
warnings.warn(f"Short length {length}")
14+
gen = gen.zfill(32)
15+
elif length > 32:
16+
warnings.warn(f"Long length {length}")
17+
gen = gen[:32]
18+
19+
return urlsafe_b64encode(gen.encode())
20+
21+
22+
_fernet_key_raw = os.getenv("FERNET_KEY")
23+
FERNET_KEY = str_2_key(_fernet_key_raw)
24+
FERNET = Fernet(FERNET_KEY)
25+
26+
T = TypeVar("T")
27+
28+
29+
def _decrypt_val(v: T) -> T:
30+
if isinstance(v, str):
31+
return FERNET.decrypt(v).decode()
32+
if isinstance(v, list):
33+
return _decrypt_list(v)
34+
if isinstance(v, dict):
35+
return _decrypt_dict(v)
36+
37+
return v
38+
39+
40+
def _decrypt_list(data: list) -> list:
41+
ret = []
42+
for v in data:
43+
ret.append(_decrypt_val(v))
44+
return ret
45+
46+
47+
def _decrypt_dict(data: dict) -> dict:
48+
ret = {}
49+
for k, v in data.items():
50+
ret[k] = _decrypt_val(v)
51+
52+
return ret
53+
54+
55+
__fp__ = Path(__file__).parent
56+
_auth = _decrypt_dict(tomllib.load(
57+
(__fp__ / "auth.toml").open("rb")
58+
))
59+
_local_auth = tomllib.load(
60+
(__fp__ / "localauth.toml").open("rb")
61+
)
62+
63+
AUTH = _auth | _local_auth

0 commit comments

Comments
 (0)