-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathconfig.py
172 lines (131 loc) · 5.19 KB
/
config.py
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
"""Utils for the SDK."""
import base64
import logging
import os
from pathlib import Path
from typing import Union
import pem
from bacalhau_apiclient import Configuration
from Crypto.Hash import SHA256
from Crypto.PublicKey import RSA
from Crypto.Signature import pkcs1_15
__client_id = None
__user_id_key = None
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
def get_client_id() -> Union[str, None]:
"""Return the client ID."""
global __client_id
return __client_id
def set_client_id(client_id: str):
"""Set the client ID."""
global __client_id
__client_id = client_id
log.debug("set client_id to %s", __client_id)
# def get_user_id_key() -> Union[RSA.RsaKey, None]:
def get_user_id_key():
"""Return the user ID key."""
global __user_id_key
return __user_id_key
def set_user_id_key(user_id_key: RSA.RsaKey):
"""Set the user ID key."""
global __user_id_key
__user_id_key = user_id_key
def init_config():
"""Initialize the config."""
config_dir = __ensure_config_dir()
log.debug("config_dir: {}".format(config_dir))
__ensure_config_file()
key_path = __ensure_user_id_key(config_dir)
log.debug("key_path: {}".format(key_path))
set_user_id_key(__load_user_id_key(key_path))
log.debug("user_id_key set")
set_client_id(__load_client_id(key_path))
log.debug("client_id: {}".format(get_client_id()))
conf = Configuration()
if os.getenv("BACALHAU_API_HOST") and os.getenv("BACALHAU_API_PORT"):
conf.host = "http://{}:{}".format(os.getenv("BACALHAU_API_HOST"), os.getenv("BACALHAU_API_PORT"))
log.debug("Using BACALHAU_API_HOST and BACALHAU_API_PORT to set host: %s", conf.host)
log.debug("init config done")
return conf
def __ensure_config_dir() -> Path:
"""Ensure the config directory exists and return its path."""
config_dir_str = os.getenv("BACALHAU_DIR")
if config_dir_str is None:
log.debug("BACALHAU_DIR not set, using default of ~/.bacalhau")
home_path = Path.home()
config_dir = home_path.joinpath(".bacalhau")
config_dir.mkdir(mode=700, parents=True, exist_ok=True)
else:
os.stat(config_dir_str)
config_dir = Path(config_dir_str)
log.debug("Using config dir: %s", config_dir.absolute().resolve())
return config_dir.absolute().resolve()
def __ensure_config_file() -> str:
"""Ensure that BACALHAU_DIR/config.yaml exists."""
# warnings.warn("Not implemented - the BACALHAU_DIR/config.yaml config file is not used yet.")
return ""
def __ensure_user_id_key(config_dir: Path) -> Path:
"""Ensure that the user_id key exists."""
user_id_key = config_dir.joinpath("user_id.pem")
if not os.path.isfile(user_id_key):
log.error("User ID key not found at %s", user_id_key)
raise Exception(
"""{} does not exist and this python sdk will not generate one for you.
Please install the go client and run any command to generate the key:
https://docs.bacalhau.org/getting-started/installation""".format(
user_id_key
)
)
else:
log.debug("Found user ID key at %s", user_id_key)
return user_id_key
def __load_user_id_key(key_file: Path) -> RSA.RsaKey:
"""Return the private key."""
log.debug("Loading user ID key from %s", key_file)
with open(key_file, 'rb') as f:
certs = pem.parse(f.read())
private_key = RSA.import_key(certs[0].as_bytes())
return private_key
def __convert_to_client_id(key: RSA.RsaKey) -> str:
"""Return the client ID from a public key.
e.g. `bae8c1b2adfa04cc647a2457e8c0c605cef8ed11bdea5ac1f19f94219d722dfz`.
"""
der_key = key.public_key()
hash_obj = SHA256.new()
hash_obj.update(der_key.n.to_bytes(der_key.size_in_bytes(), byteorder='big'))
return hash_obj.hexdigest()
def __load_client_id(key_path: Path) -> str:
"""Return the client ID.
Should be callable without the need of invoking init_config() first.
"""
key = __load_user_id_key(key_path)
return __convert_to_client_id(key)
def sign_for_client(msg: bytes) -> str:
"""sign_for_client signs a message with the user's private ID key.
Must be called after init_config().
"""
signer = pkcs1_15.new(get_user_id_key())
hash_obj = SHA256.new()
hash_obj.update(msg)
signed_payload = signer.sign(hash_obj)
signature = base64.b64encode(signed_payload).decode()
return signature
def __clean_pem_pub_key(pem_pub_key: str) -> str:
"""Prepare a public key in the format expected by the API.
- remove the header and footer
- remove the newlines
- remove the first 32 characters i.e. `MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A`. \
https://stackoverflow.com/questions/8784905/command-line-tool-to-export-rsa-private-key-to-rsapublickey
"""
pem_public_key = (
pem_pub_key.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replace("\n", "")[32:]
)
return pem_public_key
def get_client_public_key() -> str:
"""Return the client public key."""
public_key = get_user_id_key().publickey()
pem_public_key = public_key.export_key('PEM').decode()
return __clean_pem_pub_key(pem_public_key)