2025-08-07 14:59:29 +08:00
|
|
|
import re
|
2025-06-12 04:20:27 -04:00
|
|
|
from enum import StrEnum
|
2025-08-07 14:59:29 +08:00
|
|
|
from urllib.parse import unquote
|
2025-06-12 04:20:27 -04:00
|
|
|
|
2025-08-07 14:59:29 +08:00
|
|
|
import pyotp
|
|
|
|
|
import structlog
|
|
|
|
|
|
|
|
|
|
LOG = structlog.get_logger()
|
2025-06-12 04:20:27 -04:00
|
|
|
|
|
|
|
|
|
|
|
|
|
class OnePasswordConstants(StrEnum):
|
|
|
|
|
"""Constants for 1Password integration."""
|
|
|
|
|
|
|
|
|
|
TOTP = "OP_TOTP" # Special value to indicate a TOTP code
|
2025-08-07 14:59:29 +08:00
|
|
|
|
|
|
|
|
|
2025-09-12 11:01:57 -06:00
|
|
|
class AzureVaultConstants(StrEnum):
|
|
|
|
|
"""Constants for Azure Vault integration."""
|
|
|
|
|
|
|
|
|
|
TOTP = "AZ_TOTP" # Special value to indicate a TOTP code
|
|
|
|
|
|
|
|
|
|
|
2025-08-07 14:59:29 +08:00
|
|
|
def parse_totp_secret(totp_secret: str) -> str:
|
|
|
|
|
if not totp_secret:
|
|
|
|
|
return ""
|
|
|
|
|
|
2025-08-28 14:17:29 +08:00
|
|
|
totp_secret_no_dashe = "".join(totp_secret.split("-"))
|
|
|
|
|
totp_secret_no_whitespace = "".join(totp_secret_no_dashe.split())
|
2025-08-07 15:31:09 +08:00
|
|
|
try:
|
|
|
|
|
# to verify if it's a valid TOTP secret
|
|
|
|
|
pyotp.TOTP(totp_secret_no_whitespace).byte_secret()
|
2025-08-07 14:59:29 +08:00
|
|
|
return totp_secret_no_whitespace
|
2025-08-07 15:31:09 +08:00
|
|
|
except Exception:
|
|
|
|
|
LOG.warning("It's not a valid TOTP secret, going to parse it from URI format", exc_info=True)
|
2025-08-07 14:59:29 +08:00
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
totp_secret = pyotp.parse_uri(totp_secret_no_whitespace).secret
|
|
|
|
|
totp_secret_no_whitespace = "".join(totp_secret.split())
|
|
|
|
|
return totp_secret_no_whitespace
|
|
|
|
|
except Exception:
|
|
|
|
|
LOG.warning("Failed to parse TOTP secret key from URI format, going to extract secret by regex", exc_info=True)
|
|
|
|
|
m = re.search(r"(?i)(?:^|[?&])secret=([^&#]+)", unquote(totp_secret_no_whitespace))
|
|
|
|
|
if m is None:
|
2025-08-08 11:00:27 -07:00
|
|
|
return totp_secret_no_whitespace
|
2025-08-07 14:59:29 +08:00
|
|
|
totp_secret = m.group(1)
|
|
|
|
|
totp_secret_no_whitespace = "".join(totp_secret.split())
|
|
|
|
|
return totp_secret_no_whitespace
|