forked from EnAccess/OpenPAYGO-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetrics_shared.py
More file actions
173 lines (156 loc) · 6.51 KB
/
Copy pathmetrics_shared.py
File metadata and controls
173 lines (156 loc) · 6.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
import codecs
import json
import siphash
class AuthMethod(object):
SIMPLE_AUTH = "sa"
TIMESTAMP_AUTH = "ta"
COUNTER_AUTH = "ca"
DATA_AUTH = "da"
RECURSIVE_DATA_AUTH = "ra"
class OpenPAYGOMetricsShared(object):
CONDENSED_KEY_NAMES = {
# Request
"serial_number": "sn",
"timestamp": "ts",
"auth": "a",
"request_count": "rc",
"data_collection_timestamp": "dtc",
"data_format_id": "df",
"data_format": "dfo",
"data": "d",
"historical_data": "hd",
"accessories": "acc",
# Response
"token_list": "tkl",
"active_until_timestamp": "auts",
"active_seconds_left": "asl",
"settings": "st",
"extra_data": "ed",
# Data
"token_count": "tc",
"active_until_timestamp_requested": "autsr",
"active_seconds_left_requested": "aslr",
}
@classmethod
def convert_dict_keys_to_condensed(cls, simple_dict):
return cls.convert_dict_keys(simple_dict, cls.CONDENSED_KEY_NAMES)
@classmethod
def convert_dict_keys_to_simple(cls, condensed_dict):
revert_keys = {v: k for k, v in cls.CONDENSED_KEY_NAMES.items()}
return cls.convert_dict_keys(condensed_dict, revert_keys)
@classmethod
def convert_dict_keys(cls, origin_dict, key_map):
condensed_dict = {}
for key in origin_dict:
if key in key_map:
condensed_dict[key_map[key]] = origin_dict[key]
else:
condensed_dict[key] = origin_dict[key]
return condensed_dict
@classmethod
def remove_trailing_empty_elements(cls, list_with_empty):
while list_with_empty and list_with_empty[-1] is None:
list_with_empty.pop()
return list_with_empty
@classmethod
def convert_to_metrics_json(cls, data):
return json.dumps(data, separators=(",", ":"))
@classmethod
def generate_response_signature_from_data(
cls, data, secret_key, serial_number, timestamp=None, request_count=None
):
payload = serial_number
if timestamp:
payload += str(timestamp)
if request_count:
payload += str(request_count)
if data.get("active_until_timestamp"):
payload += str(data.get("active_until_timestamp"))
if data.get("active_seconds_left"):
payload += str(data.get("active_seconds_left"))
if data.get("token_list"):
payload += cls.convert_to_metrics_json(data.get("token_list"))
if data.get("settings"):
payload += cls.convert_to_metrics_json(data.get("settings"))
if data.get("extra_data"):
payload += cls.convert_to_metrics_json(data.get("extra_data"))
return AuthMethod.DATA_AUTH + cls.generate_hash_string(payload, secret_key)
@classmethod
def generate_request_signature_from_data(cls, data, auth_method, secret_key):
if auth_method == AuthMethod.SIMPLE_AUTH:
signature = cls.generate_hash_string(data.get("serial_number"), secret_key)
elif auth_method == AuthMethod.TIMESTAMP_AUTH:
if not data.get("timestamp", None):
raise ValueError("Timestamp is required for Timestamp Auth")
signature = cls.generate_hash_string(
data.get("serial_number") + str(data.get("timestamp")), secret_key
)
elif auth_method == AuthMethod.COUNTER_AUTH:
if not data.get("request_count", None):
raise ValueError("Request Count is required for Counter Auth")
signature = cls.generate_hash_string(
data.get("serial_number") + str(data.get("request_count")), secret_key
)
elif auth_method == AuthMethod.DATA_AUTH:
payload = data.get("serial_number")
if data.get("timestamp"):
payload += str(data.get("timestamp"))
if data.get("request_count"):
payload += str(data.get("request_count"))
if data.get("data"):
payload += cls.convert_to_metrics_json(data.get("data", []))
if data.get("historical_data"):
payload += cls.convert_to_metrics_json(data.get("historical_data", []))
signature = cls.generate_hash_string(payload, secret_key)
elif auth_method == AuthMethod.RECURSIVE_DATA_AUTH:
payload = data.get("serial_number")
payload = cls.generate_hash_string(payload, secret_key)
if data.get("timestamp"):
payload = cls.generate_hash_string(
payload + str(data.get("timestamp")), secret_key
)
if data.get("request_count"):
payload = cls.generate_hash_string(
payload + str(data.get("request_count")), secret_key
)
payload = cls.generate_hash_string(
payload + cls.convert_to_metrics_json(data.get("data", [])), secret_key
)
for time_step_data in data.get("historical_data", []):
payload = cls.generate_hash_string(
payload + cls.convert_to_metrics_json(time_step_data), secret_key
)
signature = payload
else:
raise ValueError("Invalid Authentication Method")
return auth_method + signature
@classmethod
def generate_hash_string(cls, input_string, secret_key):
key = cls.load_secret_key_from_hex(secret_key)
hash = siphash.SipHash_2_4(key, codecs.encode(input_string, "utf-8")).hash()
hash_string = "{:x}".format(hash)
return hash_string
@classmethod
def load_secret_key_from_hex(cls, secret_key):
if isinstance(secret_key, (bytes, bytearray)):
secret_key_bytes = bytes(secret_key)
if len(secret_key_bytes) != 16:
raise ValueError(
"The secret key provided is not correctly formatted, it should be "
"16 "
"bytes. "
)
return secret_key_bytes
try:
decoded = codecs.decode(secret_key, "hex")
except Exception:
raise ValueError(
"The secret key provided is not correctly formatted, it should be 32 "
"hexadecimal characters. "
)
if len(decoded) != 16:
raise ValueError(
"The secret key provided is not correctly formatted, it should be 32 "
"hexadecimal characters. "
)
return decoded