Coretex
remote.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import Tuple, Optional, List
19 
20 import json
21 import logging
22 import sys
23 
24 from tap import Tap
25 
26 from ..base_callback import TaskCallback
27 from ...networking import networkManager
28 from ...entities import TaskRun, secret_factory
29 
30 
31 class RemoteArgumentParser(Tap):
32 
33  refreshToken: str
34  taskRunId: int
35  decryptedSecrets: Optional[str]
36 
37  def configure(self) -> None:
38  self.add_argument("--refreshToken", type = str)
39  self.add_argument("--taskRunId", type = int)
40  self.add_argument("--decryptedSecrets", nargs = "?", type = str, default = None)
41 
42 
43 def processRemote(args: Optional[List[str]] = None) -> Tuple[TaskRun, TaskCallback]:
44  remoteArgumentParser, unknown = RemoteArgumentParser().parse_known_args(args)
45 
46  response = networkManager.authenticateWithRefreshToken(remoteArgumentParser.refreshToken)
47  if response.hasFailed():
48  raise RuntimeError(">> [Coretex] Failed to authenticate")
49 
50  taskRun: TaskRun = TaskRun.fetchById(remoteArgumentParser.taskRunId)
51 
52  if remoteArgumentParser.decryptedSecrets is not None:
53  try:
54  decryptedSecrets = json.loads(remoteArgumentParser.decryptedSecrets)
55  if not isinstance(decryptedSecrets, dict):
56  raise TypeError
57 
58  for key, value in decryptedSecrets.items():
59  if isinstance(value, dict):
60  taskRun.parameters[key] = secret_factory.create(value)
61 
62  if isinstance(value, list):
63  taskRun.parameters[key] = [secret_factory.create(element) for element in value]
64  except BaseException as ex:
65  logging.getLogger("coretexpylib").debug(f">> [Coretex] Failed to load decrypted secrets - \"{ex}\"", exc_info = ex)
66 
67  return taskRun, TaskCallback(taskRun)