regscale-cli 6.20.8.0__py3-none-any.whl → 6.20.9.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of regscale-cli might be problematic. Click here for more details.

regscale/_version.py CHANGED
@@ -33,7 +33,7 @@ def get_version_from_pyproject() -> str:
33
33
  return match.group(1)
34
34
  except Exception:
35
35
  pass
36
- return "6.20.8.0" # fallback version
36
+ return "6.20.9.0" # fallback version
37
37
 
38
38
 
39
39
  __version__ = get_version_from_pyproject()
@@ -399,10 +399,10 @@ class Application(metaclass=Singleton):
399
399
  if config is None:
400
400
  config = {}
401
401
  self.logger.debug(f"Provided config in _fetch_config_from_regscale is: {type(config)}")
402
- token = config.get("token") or os.getenv("REGSCALE_TOKEN")
403
- domain = config.get("domain") or os.getenv("REGSCALE_DOMAIN")
402
+ token = config.get("token", os.getenv("REGSCALE_TOKEN"))
403
+ domain = config.get("domain", os.getenv("REGSCALE_DOMAIN"))
404
404
  if domain is None or "http" not in domain or domain == self.template["domain"]:
405
- domain = self.retrieve_domain()[:-1] if self.retrieve_domain().endswith("/") else self.retrieve_domain()
405
+ domain = self.retrieve_domain().rstrip("/")
406
406
  self.logger.debug(f"domain: {domain}, token: {token}")
407
407
  if domain is not None and token is not None:
408
408
  self.logger.info(f"Fetching config from {domain}...")
@@ -416,23 +416,87 @@ class Application(metaclass=Singleton):
416
416
  },
417
417
  )
418
418
  self.logger.debug(f"status_code: {response.status_code} text: {response.text}")
419
- res_data = response.json()
420
- if config := res_data.get("cliConfig"):
421
- parsed_dict = yaml.safe_load(config)
422
- self.logger.debug(f"parsed_dict: {parsed_dict}")
423
- parsed_dict["token"] = token
424
- parsed_dict["domain"] = domain
425
- from regscale.core.app.internal.login import parse_user_id_from_jwt
426
-
427
- parsed_dict["userId"] = res_data.get("userId") or parse_user_id_from_jwt(self, token)
428
- self.logger.debug(f"Updated domain, token and userId: {parsed_dict}")
429
- self.logger.info("Successfully fetched config from RegScale.")
430
- # fill in any missing keys with the template
431
- return {**self.template, **parsed_dict}
419
+
420
+ # Get the encrypted config from the response
421
+ fetched_config = response.json()
422
+ if not fetched_config or response.text == "":
423
+ self.logger.warning("No secrets found in %s", domain)
424
+ return {}
425
+ # see if it's just a dictionary
426
+ if isinstance(fetched_config, dict):
427
+ parsed_dict = fetched_config
428
+ else:
429
+ decrypted_config = self._decrypt_config(fetched_config, token)
430
+ parsed_dict = json.loads(decrypted_config)
431
+
432
+ parsed_dict["token"] = token
433
+ parsed_dict["domain"] = domain
434
+ from regscale.core.app.internal.login import parse_user_id_from_jwt
435
+
436
+ parsed_dict["userId"] = parsed_dict.get("userId") or parse_user_id_from_jwt(self, token)
437
+ self.logger.info("Successfully fetched config from RegScale.")
438
+ # fill in any missing keys with the template
439
+ return {**self.template, **parsed_dict}
432
440
  except Exception as ex:
433
- self.logger.error("Unable to fetch config from RegScale.\n%s", ex)
441
+ self.logger.error("Unable to fetch config from RegScale.\n%s", str(ex))
434
442
  return {}
435
443
 
444
+ def _decrypt_config(self, encrypted_text: str, bearer_token: str) -> str:
445
+ """
446
+ Decrypt the configuration using AES encryption with the bearer token as key
447
+
448
+ :param str encrypted_text: Base64 encoded encrypted text
449
+ :param str bearer_token: Bearer token used as encryption key
450
+ :return: Decrypted configuration string
451
+ :rtype: str
452
+ """
453
+ import base64
454
+ import hashlib
455
+ from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
456
+ from cryptography.hazmat.backends import default_backend
457
+
458
+ try:
459
+ # Convert from base64
460
+ combined = base64.b64decode(encrypted_text)
461
+
462
+ # Extract IV (first 16 bytes) and cipher text
463
+ iv = combined[:16]
464
+ cipher_text = combined[16:]
465
+
466
+ # Generate key from bearer token using SHA256
467
+ key = hashlib.sha256(bearer_token.encode()).digest()
468
+
469
+ # Create cipher
470
+ cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
471
+
472
+ # Decrypt
473
+ decryptor = cipher.decryptor()
474
+ decrypted = decryptor.update(cipher_text) + decryptor.finalize()
475
+
476
+ # Remove padding and convert to string
477
+ decoded = decrypted.decode("utf-8")
478
+ # Remove all trailing whitespace and control characters
479
+ cleaned = decoded.rstrip()
480
+ # Also remove any trailing null bytes that might remain
481
+ while cleaned.endswith("\0"):
482
+ cleaned = cleaned[:-1]
483
+ # Use regex to remove any ending backslash-like pattern and characters after it
484
+ import re
485
+
486
+ # Remove any trailing backslash followed by any characters until the end
487
+ # This handles both literal backslashes and control characters like \x0e
488
+ cleaned = re.sub(r"\\[^\\]*$", "", cleaned)
489
+ # Also remove any trailing control characters that might remain
490
+ # Avoid regex for trailing control character removal to prevent potential catastrophic backtracking.
491
+ # Instead, use rstrip with a string of control characters.
492
+ cleaned = cleaned.rstrip(
493
+ "".join([chr(i) for i in range(0x00, 0x20)]) + "".join([chr(i) for i in range(0x7F, 0xA0)])
494
+ )
495
+ return cleaned
496
+ except Exception as err:
497
+ self.logger.error("Unable to decrypt config: %s", err)
498
+ return "{}"
499
+
436
500
  def _load_config_from_click_context(self) -> Optional[dict]:
437
501
  """
438
502
  Load configuration from Click context