From 2b3b68e917f5d8c863f3c03170b935b595418cf8 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 19:53:19 +0000 Subject: [PATCH 1/4] Add customer keys for wrapping secret versions Co-authored-by: Ninad Sinha --- hyperbrowser/__init__.py | 10 +- hyperbrowser/customer_key.py | 705 +++++++++++++++++++++++++++++++++++ 2 files changed, 714 insertions(+), 1 deletion(-) create mode 100644 hyperbrowser/customer_key.py diff --git a/hyperbrowser/__init__.py b/hyperbrowser/__init__.py index 343d06c7..f00a570d 100644 --- a/hyperbrowser/__init__.py +++ b/hyperbrowser/__init__.py @@ -1,5 +1,13 @@ from .client.sync import Hyperbrowser from .client.async_client import AsyncHyperbrowser from .config import ClientConfig +from .customer_key import CustomerKey, create_customer_key, secret_envelope_digest -__all__ = ["Hyperbrowser", "AsyncHyperbrowser", "ClientConfig"] +__all__ = [ + "Hyperbrowser", + "AsyncHyperbrowser", + "ClientConfig", + "CustomerKey", + "create_customer_key", + "secret_envelope_digest", +] diff --git a/hyperbrowser/customer_key.py b/hyperbrowser/customer_key.py new file mode 100644 index 00000000..623d8847 --- /dev/null +++ b/hyperbrowser/customer_key.py @@ -0,0 +1,705 @@ +"""Customer keys for customer-protected secrets. + +A customer-protected secret's versions are sealed to the platform's key as +usual, then wrapped again with the customer's own key, so nothing the +platform stores can be opened without it. Each use passes the envelope +unwrapped with that key. + +``create_customer_key`` builds a key from local key material. To keep the +private key elsewhere, such as in a KMS or HSM, implement ``CustomerKey``. +""" + +import base64 +import hashlib +import inspect +import json +import os +import re +from typing import ( + Any, + Awaitable, + Dict, + List, + Literal, + Mapping, + Optional, + Sequence, + Tuple, + Union, +) + +from cryptography.exceptions import InvalidTag +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa, x448, x25519 +from cryptography.hazmat.primitives.ciphers.aead import AESGCM +from cryptography.hazmat.primitives.keywrap import ( + InvalidUnwrap, + aes_key_unwrap, + aes_key_wrap, +) +from typing_extensions import Protocol, runtime_checkable + +from .exceptions import HyperbrowserError + +# How a customer key wraps an envelope (JWE key management). RSA keys use +# RSA-OAEP-256; EC and X25519/X448 keys use ECDH-ES+A256KW unless ECDH-ES is +# chosen. Content is always encrypted with A256GCM. +CustomerKeyAlgorithm = Literal["RSA-OAEP-256", "ECDH-ES", "ECDH-ES+A256KW"] + +_ALGORITHMS = ("RSA-OAEP-256", "ECDH-ES", "ECDH-ES+A256KW") +_ENC = "A256GCM" +_IV_BYTES = 12 +_TAG_BYTES = 16 +_CEK_BYTES = 32 +# The server's limit on an inner envelope. +MAX_INNER_ENVELOPE_LENGTH = 64 * 1024 +MIN_RSA_KEY_BITS = 2048 +MAX_CUSTOMER_KEY_ID_LENGTH = 256 +_KID_PATTERN = re.compile(r"^[\x20-\x7e]+$") +_B64URL_PATTERN = re.compile(r"^[A-Za-z0-9_-]*$") +_CURVES = { + "P-256": ec.SECP256R1, + "P-384": ec.SECP384R1, + "P-521": ec.SECP521R1, +} +_OKP = { + "X25519": (x25519.X25519PrivateKey, x25519.X25519PublicKey), + "X448": (x448.X448PrivateKey, x448.X448PublicKey), +} +_OAEP = padding.OAEP( + mgf=padding.MGF1(algorithm=hashes.SHA256()), + algorithm=hashes.SHA256(), + label=None, +) + +_PublicKey = Union[ + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, +] +_PrivateKey = Union[ + rsa.RSAPrivateKey, + ec.EllipticCurvePrivateKey, + x25519.X25519PrivateKey, + x448.X448PrivateKey, +] +# A key as create_customer_key takes it: a cryptography key object, a PEM or +# DER private or public key, or a JWK. A public key can only wrap. +CustomerKeyInput = Union[_PrivateKey, _PublicKey, str, bytes, Mapping[str, Any]] + + +@runtime_checkable +class CustomerKey(Protocol): + """The customer's own key for customer-protected secrets. + + ``kid`` is written as the ``kid`` of every envelope the key wraps: 1-256 + printable ASCII characters. ``wrap`` returns a compact JWE (RSA-OAEP-256, + ECDH-ES or ECDH-ES+A256KW with A256GCM) whose protected header holds + exactly ``alg``, ``enc``, ``kid`` and ``ctx`` (plus ``epk``, and + optionally ``apu`` and ``apv``, with ECDH-ES), with ``ctx`` set to + ``encryption_context``. ``unwrap`` returns the inner envelope. + + With the async client, either method may return an awaitable. + """ + + @property + def kid(self) -> str: ... + + def wrap( + self, inner_envelope: str, encryption_context: str + ) -> Union[str, Awaitable[str]]: ... + + def unwrap(self, wrapped_envelope: str) -> Union[str, Awaitable[str]]: ... + + +def _key_error(message: str, code: str = "invalid_customer_key") -> HyperbrowserError: + return HyperbrowserError(message, code=code, retryable=False) + + +def _unwrap_failed(message: str) -> HyperbrowserError: + return _key_error(message, "customer_key_unwrap_failed") + + +def _b64url(data: bytes) -> str: + return base64.urlsafe_b64encode(data).rstrip(b"=").decode("ascii") + + +def _decode_segment(segment: str, what: str) -> bytes: + if _B64URL_PATTERN.fullmatch(segment): + decoded = base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4)) + if _b64url(decoded) == segment: + return decoded + raise _unwrap_failed(f"Wrapped envelope {what} is not canonical base64url") + + +def _jwk_bytes(jwk: Mapping[str, Any], member: str) -> bytes: + value = jwk.get(member) + if not isinstance(value, str) or not _B64URL_PATTERN.fullmatch(value): + raise _key_error(f"The customer key JWK's {member!r} is not base64url") + return base64.urlsafe_b64decode(value + "=" * (-len(value) % 4)) + + +def _jwk_int(jwk: Mapping[str, Any], member: str) -> int: + return int.from_bytes(_jwk_bytes(jwk, member), "big") + + +def _int_bytes(value: int, length: Optional[int] = None) -> bytes: + size = length if length is not None else max(1, (value.bit_length() + 7) // 8) + return value.to_bytes(size, "big") + + +def _uint32(value: int) -> bytes: + return value.to_bytes(4, "big") + + +def _length_prefixed(data: bytes) -> bytes: + return _uint32(len(data)) + data + + +def _concat_kdf(shared: bytes, algorithm_id: str, apu: bytes, apv: bytes) -> bytes: + """RFC 7518 section 4.6.2 Concat KDF with SHA-256, for one 256-bit key.""" + return hashlib.sha256( + _uint32(1) + + shared + + _length_prefixed(algorithm_id.encode("ascii")) + + _length_prefixed(apu) + + _length_prefixed(apv) + + _uint32(_CEK_BYTES * 8) + ).digest() + + +def _curve_name(curve: ec.EllipticCurve) -> Optional[str]: + for name, curve_type in _CURVES.items(): + if isinstance(curve, curve_type): + return name + return None + + +def _public_members(public_key: _PublicKey) -> Dict[str, str]: + """The members of a public JWK that RFC 7638 thumbprints (and ``epk`` + headers) hold, in thumbprint order.""" + if isinstance(public_key, rsa.RSAPublicKey): + numbers = public_key.public_numbers() + return { + "e": _b64url(_int_bytes(numbers.e)), + "kty": "RSA", + "n": _b64url(_int_bytes(numbers.n)), + } + if isinstance(public_key, ec.EllipticCurvePublicKey): + numbers = public_key.public_numbers() + size = (public_key.curve.key_size + 7) // 8 + return { + "crv": _curve_name(public_key.curve) or "", + "kty": "EC", + "x": _b64url(_int_bytes(numbers.x, size)), + "y": _b64url(_int_bytes(numbers.y, size)), + } + raw = public_key.public_bytes( + serialization.Encoding.Raw, serialization.PublicFormat.Raw + ) + crv = "X25519" if isinstance(public_key, x25519.X25519PublicKey) else "X448" + return {"crv": crv, "kty": "OKP", "x": _b64url(raw)} + + +def _thumbprint(public_key: _PublicKey) -> str: + """The RFC 7638 SHA-256 thumbprint of a public key.""" + members = json.dumps(_public_members(public_key), separators=(",", ":")) + return _b64url(hashlib.sha256(members.encode("ascii")).digest()) + + +def _jwk_public_key(jwk: Mapping[str, Any]) -> _PublicKey: + kty = jwk.get("kty") + if kty == "RSA": + return rsa.RSAPublicNumbers(_jwk_int(jwk, "e"), _jwk_int(jwk, "n")).public_key() + if kty == "EC": + curve = _CURVES.get(jwk.get("crv")) # type: ignore[arg-type] + if curve is None: + raise _key_error("EC customer keys must be on P-256, P-384 or P-521") + return ec.EllipticCurvePublicNumbers( + _jwk_int(jwk, "x"), _jwk_int(jwk, "y"), curve() + ).public_key() + if kty == "OKP": + okp = _OKP.get(jwk.get("crv")) # type: ignore[arg-type] + if okp is None: + raise _key_error("OKP customer keys must be X25519 or X448") + return okp[1].from_public_bytes(_jwk_bytes(jwk, "x")) + raise _key_error( + "A customer key must be RSA, EC (P-256, P-384, P-521), X25519 or X448" + ) + + +def _jwk_private_key(jwk: Mapping[str, Any], public_key: _PublicKey) -> _PrivateKey: + kty = jwk.get("kty") + private_key: _PrivateKey + if kty == "RSA": + assert isinstance(public_key, rsa.RSAPublicKey) + public_numbers = public_key.public_numbers() + d = _jwk_int(jwk, "d") + if "p" in jwk and "q" in jwk: + p, q = _jwk_int(jwk, "p"), _jwk_int(jwk, "q") + else: + p, q = rsa.rsa_recover_prime_factors(public_numbers.n, public_numbers.e, d) + private_key = rsa.RSAPrivateNumbers( + p=p, + q=q, + d=d, + dmp1=rsa.rsa_crt_dmp1(d, p), + dmq1=rsa.rsa_crt_dmq1(d, q), + iqmp=rsa.rsa_crt_iqmp(p, q), + public_numbers=public_numbers, + ).private_key() + elif kty == "EC": + assert isinstance(public_key, ec.EllipticCurvePublicKey) + private_key = ec.derive_private_key(_jwk_int(jwk, "d"), public_key.curve) + else: + private_key = _OKP[jwk["crv"]][0].from_private_bytes(_jwk_bytes(jwk, "d")) + if _public_members(private_key.public_key()) != _public_members(public_key): + raise _key_error( + "The customer key JWK's private and public members don't match" + ) + return private_key + + +def _load_pem_or_der( + data: bytes, +) -> Tuple[Any, Optional[Any]]: + pem = data.lstrip().startswith(b"-----BEGIN") + load_private = ( + serialization.load_pem_private_key + if pem + else serialization.load_der_private_key + ) + load_public = ( + serialization.load_pem_public_key if pem else serialization.load_der_public_key + ) + try: + private_key = load_private(data, password=None) + return private_key.public_key(), private_key + except TypeError: + raise _key_error( + "The customer key is encrypted; pass the decrypted key object instead" + ) from None + except ValueError: + pass + try: + return load_public(data), None + except ValueError: + raise _key_error("The customer key is not a PEM or DER key") from None + + +def _load_keys(key: Any) -> Tuple[Any, Optional[Any], Optional[str]]: + if isinstance(key, Mapping): + jwk_kid = key.get("kid") if isinstance(key.get("kid"), str) else None + try: + public_key = _jwk_public_key(key) + private_key = _jwk_private_key(key, public_key) if "d" in key else None + except HyperbrowserError: + raise + except (ValueError, TypeError, KeyError) as error: + raise HyperbrowserError( + "The customer key JWK could not be read", + code="invalid_customer_key", + cause=error, + ) from None + return public_key, private_key, jwk_kid + if isinstance(key, str): + key = key.encode("utf-8") + if isinstance(key, (bytes, bytearray)): + public_key, private_key = _load_pem_or_der(bytes(key)) + return public_key, private_key, None + if isinstance( + key, + ( + rsa.RSAPrivateKey, + ec.EllipticCurvePrivateKey, + x25519.X25519PrivateKey, + x448.X448PrivateKey, + ), + ): + return key.public_key(), key, None + if isinstance( + key, + ( + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, + ), + ): + return key, None, None + raise _key_error( + "A customer key must be RSA, EC (P-256, P-384, P-521), X25519 or X448: " + "a key object, a PEM or DER key, or a JWK" + ) + + +def check_customer_key_id(kid: Any) -> str: + """Raise unless ``kid`` is a key ID the API stores: 1-256 printable ASCII + characters.""" + if ( + not isinstance(kid, str) + or len(kid) > MAX_CUSTOMER_KEY_ID_LENGTH + or not _KID_PATTERN.fullmatch(kid) + ): + raise _key_error( + f"A customer key's kid must be 1-{MAX_CUSTOMER_KEY_ID_LENGTH} " + "printable ASCII characters" + ) + return kid + + +class LocalCustomerKey: + """A customer key held in this process. Build one with + ``create_customer_key``.""" + + def __init__( + self, + public_key: Any, + private_key: Optional[Any], + *, + kid: Optional[str] = None, + algorithm: Optional[CustomerKeyAlgorithm] = None, + ): + if isinstance(public_key, rsa.RSAPublicKey): + if public_key.key_size < MIN_RSA_KEY_BITS: + raise _key_error( + f"RSA customer keys must be at least {MIN_RSA_KEY_BITS} bits" + ) + elif isinstance(public_key, ec.EllipticCurvePublicKey): + if _curve_name(public_key.curve) is None: + raise _key_error("EC customer keys must be on P-256, P-384 or P-521") + elif not isinstance(public_key, (x25519.X25519PublicKey, x448.X448PublicKey)): + raise _key_error( + "A customer key must be RSA, EC (P-256, P-384, P-521), X25519 or X448" + ) + is_rsa = isinstance(public_key, rsa.RSAPublicKey) + if algorithm is None: + algorithm = "RSA-OAEP-256" if is_rsa else "ECDH-ES+A256KW" + if algorithm not in _ALGORITHMS: + raise _key_error(f"Unsupported customer key algorithm {algorithm!r}") + if (algorithm == "RSA-OAEP-256") != is_rsa: + raise _key_error( + "RSA customer keys wrap with RSA-OAEP-256" + if is_rsa + else "EC and X25519/X448 customer keys wrap with ECDH-ES or " + "ECDH-ES+A256KW" + ) + self._public_key = public_key + self._private_key = private_key + self._algorithm: str = algorithm + self._kid = check_customer_key_id( + kid if kid is not None else _thumbprint(public_key) + ) + + @property + def kid(self) -> str: + return self._kid + + @property + def algorithm(self) -> str: + return self._algorithm + + @property + def can_unwrap(self) -> bool: + """Whether this key holds its private key, so can unwrap.""" + return self._private_key is not None + + def __repr__(self) -> str: + return f"LocalCustomerKey(kid={self._kid!r}, algorithm={self._algorithm!r})" + + def _ephemeral(self) -> Any: + if isinstance(self._public_key, ec.EllipticCurvePublicKey): + return ec.generate_private_key(self._public_key.curve) + if isinstance(self._public_key, x25519.X25519PublicKey): + return x25519.X25519PrivateKey.generate() + return x448.X448PrivateKey.generate() + + @staticmethod + def _exchange(private_key: Any, public_key: Any) -> bytes: + if isinstance(private_key, ec.EllipticCurvePrivateKey): + return private_key.exchange(ec.ECDH(), public_key) + return private_key.exchange(public_key) + + def wrap(self, inner_envelope: str, encryption_context: str) -> str: + """Wrap an inner envelope as a compact JWE bound to + ``encryption_context``.""" + if not isinstance(inner_envelope, str) or not inner_envelope: + raise _key_error( + "The envelope to wrap must be a non-empty string", "invalid_request" + ) + if len(inner_envelope) > MAX_INNER_ENVELOPE_LENGTH: + raise _key_error( + "The envelope to wrap is larger than 64 KiB", "invalid_request" + ) + if not isinstance(encryption_context, str) or not encryption_context: + raise _key_error( + "An encryption context is required to wrap an envelope", + "invalid_request", + ) + header: Dict[str, Any] = { + "alg": self._algorithm, + "enc": _ENC, + "kid": self._kid, + "ctx": encryption_context, + } + encrypted_key = b"" + if isinstance(self._public_key, rsa.RSAPublicKey): + cek = os.urandom(_CEK_BYTES) + encrypted_key = self._public_key.encrypt(cek, _OAEP) + else: + ephemeral = self._ephemeral() + header["epk"] = _public_members(ephemeral.public_key()) + shared = self._exchange(ephemeral, self._public_key) + algorithm_id = _ENC if self._algorithm == "ECDH-ES" else self._algorithm + derived = _concat_kdf(shared, algorithm_id, b"", b"") + if self._algorithm == "ECDH-ES": + cek = derived + else: + cek = os.urandom(_CEK_BYTES) + encrypted_key = aes_key_wrap(derived, cek) + protected = _b64url( + json.dumps(header, separators=(",", ":"), ensure_ascii=False).encode( + "utf-8" + ) + ) + iv = os.urandom(_IV_BYTES) + sealed = AESGCM(cek).encrypt( + iv, inner_envelope.encode("utf-8"), protected.encode("ascii") + ) + return ".".join( + [ + protected, + _b64url(encrypted_key), + _b64url(iv), + _b64url(sealed[:-_TAG_BYTES]), + _b64url(sealed[-_TAG_BYTES:]), + ] + ) + + def unwrap(self, wrapped_envelope: str) -> str: + """Decrypt an envelope this key wrapped and return the inner + envelope.""" + if self._private_key is None: + raise _key_error( + f"Customer key {self._kid} has no private key, so it can wrap but " + "not unwrap", + "customer_key_private_key_required", + ) + if not isinstance(wrapped_envelope, str): + raise _unwrap_failed("The wrapped envelope must be a string") + segments = wrapped_envelope.split(".") + if len(segments) != 5: + raise _unwrap_failed("The wrapped envelope must have five segments") + header_segment, key_segment, iv_segment, ciphertext_segment, tag_segment = ( + segments + ) + try: + header = json.loads( + _decode_segment(header_segment, "header").decode("utf-8") + ) + except (ValueError, UnicodeDecodeError): + raise _unwrap_failed("The wrapped envelope header is not JSON") from None + if not isinstance(header, dict): + raise _unwrap_failed("The wrapped envelope header is not a JSON object") + if header.get("kid") != self._kid: + raise _key_error( + f"The envelope was wrapped with key {json.dumps(header.get('kid'))}, " + f"not {json.dumps(self._kid)}", + "customer_key_mismatch", + ) + if header.get("enc") != _ENC: + raise _unwrap_failed( + f"Unsupported wrapped envelope encryption {header.get('enc')}" + ) + alg = header.get("alg") + encrypted_key = _decode_segment(key_segment, "encrypted key") + iv = _decode_segment(iv_segment, "IV") + ciphertext = _decode_segment(ciphertext_segment, "ciphertext") + tag = _decode_segment(tag_segment, "tag") + if len(iv) != _IV_BYTES or len(tag) != _TAG_BYTES: + raise _unwrap_failed("The wrapped envelope IV or tag has the wrong length") + + is_rsa = isinstance(self._private_key, rsa.RSAPrivateKey) + try: + if alg == "RSA-OAEP-256" and is_rsa: + cek = self._private_key.decrypt(encrypted_key, _OAEP) + elif alg in ("ECDH-ES", "ECDH-ES+A256KW") and not is_rsa: + epk = header.get("epk") + if not isinstance(epk, dict): + raise _unwrap_failed("The wrapped envelope has no epk") + shared = self._exchange(self._private_key, _jwk_public_key(epk)) + + def optional(name: str) -> bytes: + value = header.get(name) + return b"" if value is None else _decode_segment(str(value), name) + + derived = _concat_kdf( + shared, + _ENC if alg == "ECDH-ES" else alg, + optional("apu"), + optional("apv"), + ) + cek = ( + derived + if alg == "ECDH-ES" + else aes_key_unwrap(derived, encrypted_key) + ) + else: + raise _unwrap_failed( + f"Customer key {self._kid} can't unwrap an envelope wrapped with {alg}" + ) + except HyperbrowserError as error: + if error.code == "invalid_customer_key": + raise _unwrap_failed(f"The wrapped envelope's epk is invalid: {error}") + raise + except (ValueError, TypeError, InvalidUnwrap) as error: + raise HyperbrowserError( + "The wrapped envelope's key could not be decrypted", + code="customer_key_unwrap_failed", + cause=error, + ) from None + if len(cek) != _CEK_BYTES: + raise _unwrap_failed( + "The wrapped envelope's content key has the wrong length" + ) + try: + plaintext = AESGCM(cek).decrypt( + iv, ciphertext + tag, header_segment.encode("ascii") + ) + except InvalidTag as error: + raise HyperbrowserError( + "The wrapped envelope could not be decrypted", + code="customer_key_unwrap_failed", + cause=error, + ) from None + try: + return plaintext.decode("utf-8") + except UnicodeDecodeError: + raise _unwrap_failed("The wrapped envelope does not hold text") from None + + +def create_customer_key( + key: CustomerKeyInput, + *, + kid: Optional[str] = None, + algorithm: Optional[CustomerKeyAlgorithm] = None, +) -> LocalCustomerKey: + """A customer key from local key material: RSA (at least 2048 bits), EC + (P-256, P-384 or P-521), X25519 or X448, as a key object, a PEM or DER + key, or a JWK. With only the public key it can wrap (upload versions) + but not unwrap (use them). + + ``kid`` defaults to the JWK's ``kid``, or else the RFC 7638 thumbprint of + the public key, so the same key always gets the same ID. ``algorithm`` is + for EC and X25519/X448 keys, and defaults to ``ECDH-ES+A256KW``. + """ + public_key, private_key, jwk_kid = _load_keys(key) + return LocalCustomerKey( + public_key, + private_key, + kid=kid if kid is not None else jwk_kid, + algorithm=algorithm, + ) + + +def secret_envelope_digest(envelope: str) -> str: + """Identify an inner envelope as the API does: the unpadded base64url + SHA-256 of its compact form.""" + return _b64url(hashlib.sha256(envelope.encode("utf-8")).digest()) + + +def check_customer_key(key: Any, what: str = "customer_key") -> CustomerKey: + """Raise unless ``key`` looks like a ``CustomerKey``.""" + if ( + key is None + or isinstance(key, (str, bytes, Mapping)) + or not callable(getattr(key, "wrap", None)) + or not callable(getattr(key, "unwrap", None)) + ): + raise HyperbrowserError( + f"{what} must be a customer key, such as one from create_customer_key()", + code="invalid_request", + ) + check_customer_key_id(getattr(key, "kid", None)) + return key + + +CustomerKeys = Union[CustomerKey, Sequence[CustomerKey]] + + +def check_customer_keys(keys: Any, what: str = "customer_key") -> List[CustomerKey]: + """Raise unless ``keys`` is a customer key or a non-empty list of them.""" + if not isinstance(keys, (list, tuple)): + return [check_customer_key(keys, what)] + if not keys: + raise HyperbrowserError( + f"Pass at least one customer key as {what}", code="invalid_request" + ) + return [ + check_customer_key(key, f"{what}[{index}]") for index, key in enumerate(keys) + ] + + +def customer_key_for(keys: Any, kid: str, label: str) -> CustomerKey: + """The key among ``keys`` that wrapped an envelope with this ``kid``.""" + for candidate in check_customer_keys(keys): + if candidate.kid == kid: + return candidate + raise HyperbrowserError( + f"{label} was wrapped with customer key {json.dumps(kid)}, which none of " + "the keys given has", + code="customer_key_mismatch", + ) + + +def check_unwrapped(inner: Any, inner_digest: str, label: str) -> str: + """Raise unless ``inner`` is the inner envelope a version holds.""" + if not isinstance(inner, str) or secret_envelope_digest(inner) != inner_digest: + raise HyperbrowserError( + f"{label} unwrapped to an envelope that doesn't match its innerDigest; " + "it may have been uploaded with the wrong digest", + code="customer_key_unwrap_failed", + ) + return inner + + +def _check_result(value: Any, what: str) -> str: + if not isinstance(value, str) or not value: + raise HyperbrowserError( + f"The customer key's {what}() must return the envelope as a string", + code="invalid_request", + ) + return value + + +def sync_result(value: Any, what: str) -> str: + """A customer key's result in the sync client, which can't await.""" + if inspect.isawaitable(value): + close = getattr(value, "close", None) + if callable(close): + close() + raise HyperbrowserError( + f"The customer key's {what}() returned an awaitable; use the async " + "client for keys whose methods are async", + code="invalid_request", + ) + return _check_result(value, what) + + +async def async_result(value: Any, what: str) -> str: + """A customer key's result in the async client, awaited when needed.""" + if inspect.isawaitable(value): + value = await value + return _check_result(value, what) + + +__all__ = [ + "CustomerKey", + "CustomerKeyAlgorithm", + "CustomerKeyInput", + "CustomerKeys", + "LocalCustomerKey", + "create_customer_key", + "secret_envelope_digest", +] From 83048ea0b607f215ec32f4eb117d11b90f2f41f7 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 19:53:19 +0000 Subject: [PATCH 2/4] Support customer-protected secrets, wrapped vaults and unwrapped references Co-authored-by: Ninad Sinha --- .../client/managers/async_manager/sandbox.py | 5 +- .../sandboxes/sandbox_processes.py | 5 +- .../client/managers/async_manager/secret.py | 217 ++++++++++++++++-- .../client/managers/async_manager/vault.py | 35 +++ .../client/managers/sandboxes/shared.py | 10 +- .../client/managers/sync_manager/sandbox.py | 5 +- .../sandboxes/sandbox_processes.py | 5 +- .../client/managers/sync_manager/secret.py | 211 +++++++++++++++-- .../client/managers/sync_manager/vault.py | 35 +++ hyperbrowser/models/__init__.py | 16 ++ hyperbrowser/models/credential.py | 11 +- hyperbrowser/models/sandbox.py | 12 +- hyperbrowser/models/secret.py | 86 ++++++- hyperbrowser/models/session.py | 14 ++ hyperbrowser/models/vault.py | 90 +++++++- hyperbrowser/secrets_common.py | 50 ++++ hyperbrowser/types/__init__.py | 8 + hyperbrowser/types/credential.py | 6 +- hyperbrowser/types/sandbox.py | 5 +- hyperbrowser/types/secret.py | 32 ++- hyperbrowser/types/vault.py | 18 ++ 21 files changed, 815 insertions(+), 61 deletions(-) diff --git a/hyperbrowser/client/managers/async_manager/sandbox.py b/hyperbrowser/client/managers/async_manager/sandbox.py index 5ac14d1b..d04951ec 100644 --- a/hyperbrowser/client/managers/async_manager/sandbox.py +++ b/hyperbrowser/client/managers/async_manager/sandbox.py @@ -81,6 +81,7 @@ ) from ..sandboxes.shared import ( OnePasswordSourceInput, + VaultSourceInput, SecretReferences, _build_sandbox_exposed_url, _copy_model, @@ -337,7 +338,7 @@ async def exec( run_as: Optional[str] = None, max_output_bytes: int = 64 * 1024 * 1024, secrets: Optional[SecretReferences] = None, - vault: Optional[str] = None, + vault: Optional[VaultSourceInput] = None, one_password: Optional[OnePasswordSourceInput] = None, ): """Run a command to completion. @@ -345,6 +346,8 @@ async def exec( ``secrets`` maps environment variable names to stored secrets (a name, or ``{"name": ..., "version": N}``). ``vault`` names a vault whose entries become variables too; ``secrets`` win on a clash. + Customer-protected secrets are passed as the references + ``secrets.unwrap()`` and ``vaults.unwrap()`` return. ``one_password`` sets variables from fields of a 1Password vault (``{"token": op_token_secret, "vault": ..., "fields": {ENV: {"item", "section", "field"}}}``); those variables may come from nothing else. diff --git a/hyperbrowser/client/managers/async_manager/sandboxes/sandbox_processes.py b/hyperbrowser/client/managers/async_manager/sandboxes/sandbox_processes.py index b3850153..b90aa6e6 100644 --- a/hyperbrowser/client/managers/async_manager/sandboxes/sandbox_processes.py +++ b/hyperbrowser/client/managers/async_manager/sandboxes/sandbox_processes.py @@ -27,6 +27,7 @@ ) from ...sandboxes.shared import ( OnePasswordSourceInput, + VaultSourceInput, SecretReferences, _normalize_exec_params, _runtime_process_payload, @@ -355,7 +356,7 @@ async def exec( run_as: Optional[str] = None, max_output_bytes: int = DEFAULT_MAX_PROCESS_OUTPUT_BYTES, secrets: Optional[SecretReferences] = None, - vault: Optional[str] = None, + vault: Optional[VaultSourceInput] = None, one_password: Optional[OnePasswordSourceInput] = None, ) -> SandboxProcessResult: handle = await self.start( @@ -388,7 +389,7 @@ async def start( run_as: Optional[str] = None, max_output_bytes: int = DEFAULT_MAX_PROCESS_OUTPUT_BYTES, secrets: Optional[SecretReferences] = None, - vault: Optional[str] = None, + vault: Optional[VaultSourceInput] = None, one_password: Optional[OnePasswordSourceInput] = None, ) -> SandboxProcessHandle: """Start a process. diff --git a/hyperbrowser/client/managers/async_manager/secret.py b/hyperbrowser/client/managers/async_manager/secret.py index 6d48a410..5fa5a972 100644 --- a/hyperbrowser/client/managers/async_manager/secret.py +++ b/hyperbrowser/client/managers/async_manager/secret.py @@ -1,20 +1,33 @@ import asyncio -from typing import Dict, Optional, Sequence, Union +from typing import Dict, List, Literal, Optional, Sequence, Union from ..._request import coerce_request, dump_request +from ....customer_key import ( + CustomerKey, + CustomerKeys, + check_customer_key, + check_customer_keys, + check_unwrapped, + customer_key_for, + secret_envelope_digest, + async_result, +) from ....exceptions import HyperbrowserError from ....models.secret import ( CreateSecretParams, + ReplaceSecretVersionWrappingParams, Secret, SecretDeleteResult, SecretDetail, SecretListParams, SecretListResponse, + SecretReference, SecretsPublicKey, SecretVersion, SecretValue, SecretVersionDeleteResult, UpdateSecretParams, + WrappedSecretVersion, ) from ....sandbox_common import ( ensure_response_ok, @@ -28,7 +41,11 @@ SECRET_NAME_LOOKUP_LIMIT, SecretsSealer, browser_metadata, + check_customer_protection, check_secret_version, + check_secret_version_or_latest, + create_secret_protection, + invalid_request, is_not_found, looks_like_secret_id, secret_not_found_error, @@ -37,6 +54,9 @@ update_secret_body, ) from ....types import CreateSecretParams as CreateSecretParamsDict +from ....types import ( + ReplaceSecretVersionWrappingParams as ReplaceSecretVersionWrappingParamsDict, +) from ....types import SecretListParams as SecretListParamsDict from ....types import UpdateSecretParams as UpdateSecretParamsDict @@ -47,6 +67,11 @@ class SecretManager: Values are encrypted on this machine to the platform's public key and are never returned by the API. Methods that take ``secret`` accept a secret's ID or its exact name. + + A customer-protected secret's versions are also wrapped locally with your + own key (``create_customer_key()``, or your own ``CustomerKey``), so the + platform stores nothing it can open alone. Each use passes the reference + ``unwrap()`` returns. """ def __init__(self, client): @@ -80,10 +105,14 @@ async def create( account token, which starts with ``ops_``). ``allowed_origins`` makes a ``secret`` or ``totp`` fillable into browser pages on those origins. + ``protection="customer"`` wraps each version with your own key as + well; passing ``customer_key`` implies it, and wraps the first version. + The value and the public key are checked before the secret is created, so a bad value or an unavailable key leaves nothing behind. """ normalized = coerce_request(params, CreateSecretParams) + protection = create_secret_protection(normalized) payload = None sealer = None if normalized.value is not None: @@ -91,17 +120,16 @@ async def create( normalized.type or "secret", normalized.value ) sealer = SecretsSealer(await self.get_public_key()) - secret = Secret( - **await self._request( - "POST", - "/secrets", - data=normalized.model_dump(by_alias=True, exclude_none=True), - ) - ) + body = normalized.model_dump(by_alias=True, exclude_none=True) + if protection is not None: + body["protection"] = protection + secret = Secret(**await self._request("POST", "/secrets", data=body)) if sealer is None or payload is None: return secret try: - version = await self._add_version(secret, payload, sealer) + version = await self._add_version( + secret, payload, sealer, normalized.customer_key + ) except Exception as error: raise secret_value_not_stored_error(secret.id, secret.name, error) return secret.model_copy(update={"latest_version": version.version}) @@ -136,17 +164,136 @@ async def set_allowed_origins( secret, {"metadata": browser_metadata(allowed_origins)} ) - async def add_version(self, secret: str, value: SecretValue) -> SecretVersion: + async def add_version( + self, + secret: str, + value: SecretValue, + *, + customer_key: Optional[CustomerKey] = None, + ) -> SecretVersion: """Encrypt ``value`` locally and store it as the secret's next version. The value is checked against the secret's type first: a ``totp`` - secret takes a base32 seed or an ``otpauth://totp/`` URI. + secret takes a base32 seed or an ``otpauth://totp/`` URI. A + customer-protected secret's value is also wrapped with + ``customer_key``. """ secret_payload_bytes(None, value) + if customer_key is not None: + check_customer_key(customer_key) resolved = (await self._resolve(secret))[0] + check_customer_protection(resolved, customer_key) payload = secret_payload_bytes(resolved.type, value) return await self._add_version( - resolved, payload, SecretsSealer(await self.get_public_key()) + resolved, payload, SecretsSealer(await self.get_public_key()), customer_key + ) + + async def get_wrapped_version( + self, secret: str, version: Union[int, Literal["latest"]] = "latest" + ) -> WrappedSecretVersion: + """A customer-protected version's wrapped envelope, for unwrapping with + your own key. Most callers want ``unwrap()``, which also unwraps it.""" + check_secret_version_or_latest(version) + secret_id = (await self._resolve(secret))[0].id + return await self._get_wrapped(secret_id, version) + + async def unwrap( + self, + secret: str, + customer_key: CustomerKeys, + *, + version: Union[int, Literal["latest"]] = "latest", + ) -> SecretReference: + """Unwrap a customer-protected version locally with your own key. + + Returns the reference each use passes: as a sandbox's or process's + ``secrets`` entry, or as a 1Password ``token``. It is pinned to the + version unwrapped. The unwrapped envelope is checked against the + digest stored with the version, and only the platform can open it. + ``customer_key`` may be a list, such as during a rotation; the key + whose ``kid`` wrapped the version is used. + """ + check_secret_version_or_latest(version) + check_customer_keys(customer_key) + resolved = (await self._resolve(secret))[0] + wrapped = await self._get_wrapped(resolved.id, version) + inner = await self._unwrap( + wrapped, + customer_key, + f"Version {wrapped.version} of secret {resolved.name}", + ) + return SecretReference( + name=resolved.name, version=wrapped.version, unwrapped=inner + ) + + async def rewrap( + self, + secret: str, + *, + from_key: CustomerKeys, + to_key: CustomerKey, + versions: Optional[Sequence[int]] = None, + ) -> List[WrappedSecretVersion]: + """Rewrap a customer-protected secret's versions with a new key, for + rotating your own key. + + Each version is unwrapped with ``from_key`` and wrapped with + ``to_key`` locally; the value never changes and the platform never + sees it. Without ``versions``, every version not yet wrapped with + ``to_key`` is rewrapped, so an interrupted rotation can be resumed. + Returns the versions rewrapped. + """ + check_customer_keys(from_key, "from_key") + check_customer_key(to_key, "to_key") + if versions is not None: + if isinstance(versions, (str, bytes)): + raise invalid_request("versions must be a list of version numbers") + for version in versions: + check_secret_version(version) + detail = await self.get(secret) + if detail.protection != "customer": + raise invalid_request( + f"Secret {detail.name} is not customer-protected; it has no wrapping" + ) + wanted = ( + list(versions) + if versions is not None + else [ + item.version for item in detail.versions if item.outer_kid != to_key.kid + ] + ) + rewrapped = [] + for version in wanted: + wrapped = await self._get_wrapped(detail.id, version) + inner = await self._unwrap( + wrapped, from_key, f"Version {version} of secret {detail.name}" + ) + envelope = await async_result( + to_key.wrap(inner, detail.encryption_context), "wrap" + ) + rewrapped.append( + await self._replace_wrapping( + detail.id, version, envelope, wrapped.inner_digest + ) + ) + return rewrapped + + async def replace_version_wrapping( + self, + secret: str, + version: int, + params: Union[ + ReplaceSecretVersionWrappingParamsDict, ReplaceSecretVersionWrappingParams + ], + ) -> WrappedSecretVersion: + """Replace a customer-protected version's outer envelope with one you + wrapped yourself. ``inner_digest`` must match the version's: only the + wrapping changes, never the value. ``rewrap()`` does this for you.""" + check_secret_version(version) + request = coerce_request(params, ReplaceSecretVersionWrappingParams) + secret_id = (await self._resolve(secret))[0].id + return await self._replace_wrapping( + secret_id, version, request.envelope, request.inner_digest ) async def delete(self, secret: str) -> SecretDeleteResult: @@ -169,14 +316,54 @@ async def delete_version( return SecretVersionDeleteResult(**payload) async def _add_version( - self, secret: Secret, payload: bytes, sealer: SecretsSealer + self, + secret: Secret, + payload: bytes, + sealer: SecretsSealer, + customer_key: Optional[CustomerKey] = None, ) -> SecretVersion: # Always the context the API returned; it differs by secret type. envelope = sealer.seal(secret.encryption_context, payload) + data: Dict[str, object] = {"envelope": envelope} + if customer_key is not None: + data = { + "envelope": await async_result( + customer_key.wrap(envelope, secret.encryption_context), "wrap" + ), + "innerDigest": secret_envelope_digest(envelope), + "innerKid": sealer.kid, + } + response = await self._request( + "POST", f"/secrets/{secret.id}/versions", data=data + ) + return SecretVersion(**response) + + async def _get_wrapped( + self, secret_id: str, version: Union[int, str] + ) -> WrappedSecretVersion: + return WrappedSecretVersion( + **await self._request( + "GET", f"/secrets/{secret_id}/versions/{version}/wrapped" + ) + ) + + async def _replace_wrapping( + self, secret_id: str, version: int, envelope: str, inner_digest: str + ) -> WrappedSecretVersion: payload = await self._request( - "POST", f"/secrets/{secret.id}/versions", data={"envelope": envelope} + "PUT", + f"/secrets/{secret_id}/versions/{version}/wrapping", + data={"envelope": envelope, "innerDigest": inner_digest}, ) - return SecretVersion(**payload) + return WrappedSecretVersion(**payload) + + @staticmethod + async def _unwrap( + wrapped: WrappedSecretVersion, keys: CustomerKeys, label: str + ) -> str: + key = customer_key_for(keys, wrapped.outer_kid, label) + inner = await async_result(key.unwrap(wrapped.envelope), "unwrap") + return check_unwrapped(inner, wrapped.inner_digest, label) async def _get_by_id(self, secret_id: str) -> SecretDetail: return SecretDetail(**await self._request("GET", f"/secrets/{secret_id}")) diff --git a/hyperbrowser/client/managers/async_manager/vault.py b/hyperbrowser/client/managers/async_manager/vault.py index 7c30acb9..1d1c0876 100644 --- a/hyperbrowser/client/managers/async_manager/vault.py +++ b/hyperbrowser/client/managers/async_manager/vault.py @@ -1,6 +1,7 @@ from typing import Optional, Tuple, Union from ..._request import dump_request +from ....customer_key import CustomerKeys, check_customer_keys from ....exceptions import HyperbrowserError from ....models.vault import ( CreateVaultParams, @@ -9,6 +10,9 @@ VaultDeleteResult, VaultListParams, VaultListResponse, + VaultReference, + VaultUnwrappedEntry, + WrappedVault, ) from ....secrets_common import ( SECRET_NAME_LOOKUP_LIMIT, @@ -33,6 +37,9 @@ class VaultManager: Pass a vault by name as ``vault`` when creating a sandbox or starting a process, or as ``{"vault": name}`` in a browser session's ``credentials``. Methods that take ``vault`` accept its ID or exact name. + + A vault with customer-protected entries is passed to sandboxes and + processes as the reference ``unwrap()`` returns. """ def __init__(self, client): @@ -89,6 +96,34 @@ async def delete(self, vault: str) -> VaultDeleteResult: payload = await self._control._request("DELETE", f"/vaults/{vault_id}") return VaultDeleteResult(**payload) + async def get_wrapped(self, vault: str) -> WrappedVault: + """The wrapped envelopes of a vault's customer-protected entries, at + the versions they resolve to now. Most callers want ``unwrap()``.""" + vault_id = (await self._resolve(vault))[1] + payload = await self._control._request("GET", f"/vaults/{vault_id}/wrapped") + return WrappedVault(**payload) + + async def unwrap(self, vault: str, customer_key: CustomerKeys) -> VaultReference: + """Unwrap a vault's customer-protected entries locally with your own + key. + + Returns the reference a sandbox's or process's ``vault`` takes; its + other entries are delivered as usual. If an entry moves to another + secret or version before it is used, the API refuses the reference + with ``SECRET_VAULT_CHANGED``; unwrap the vault again. + ``customer_key`` may be a list; each entry uses the key whose ``kid`` + wrapped it. + """ + check_customer_keys(customer_key) + wrapped = await self.get_wrapped(vault) + unwrapped = {} + for env, entry in wrapped.entries.items(): + inner = await self._control._unwrap( + entry, customer_key, f"Entry {env} of vault {wrapped.name}" + ) + unwrapped[env] = VaultUnwrappedEntry(version=entry.version, unwrapped=inner) + return VaultReference(name=wrapped.name, unwrapped=unwrapped) + async def _resolve(self, key: str) -> Tuple[Vault, str]: """Find a vault by ID or exact name.""" key = key.strip() diff --git a/hyperbrowser/client/managers/sandboxes/shared.py b/hyperbrowser/client/managers/sandboxes/shared.py index 51b8ce4b..70b751c4 100644 --- a/hyperbrowser/client/managers/sandboxes/shared.py +++ b/hyperbrowser/client/managers/sandboxes/shared.py @@ -25,8 +25,10 @@ runtime_base_url_session_id, ) from ....models.secret import OnePasswordSource, SecretReference +from ....models.vault import VaultReference from ....types import ( OnePasswordSource as OnePasswordSourceDict, + VaultReference as VaultReferenceDict, SecretReference as SecretReferenceDict, SandboxExecParams as SandboxExecParamsDict, SandboxFileWriteEntry as SandboxFileWriteEntryDict, @@ -37,6 +39,8 @@ SecretReferences = Dict[str, Union[str, SecretReferenceDict, SecretReference]] # Fields of a 1Password vault, as a mapping or model. OnePasswordSourceInput = Union[OnePasswordSourceDict, OnePasswordSource] +# A vault's name, or the reference vaults.unwrap() returns. +VaultSourceInput = Union[str, VaultReferenceDict, VaultReference] DEFAULT_WATCH_TIMEOUT_MS = 60_000 # The receiver sends process SSE keepalives every 15 seconds. @@ -100,7 +104,7 @@ def _normalize_exec_params( timeout_sec: Optional[int] = None, run_as: Optional[str] = None, secrets: Optional[SecretReferences] = None, - vault: Optional[str] = None, + vault: Optional[VaultSourceInput] = None, one_password: Optional[OnePasswordSourceInput] = None, ) -> SandboxExecParams: if isinstance(input, str): @@ -180,7 +184,9 @@ def _secret_process_payload(params: SandboxExecParams) -> Dict[str, object]: } if secrets or (params.vault is None and params.one_password is None) else None, - "vault": params.vault, + "vault": params.vault + if params.vault is None or isinstance(params.vault, str) + else params.vault.model_dump(exclude_none=True), "onePassword": params.one_password.model_dump(exclude_none=True) if params.one_password is not None else None, diff --git a/hyperbrowser/client/managers/sync_manager/sandbox.py b/hyperbrowser/client/managers/sync_manager/sandbox.py index 76519aef..5ad0a67e 100644 --- a/hyperbrowser/client/managers/sync_manager/sandbox.py +++ b/hyperbrowser/client/managers/sync_manager/sandbox.py @@ -79,6 +79,7 @@ ) from ..sandboxes.shared import ( OnePasswordSourceInput, + VaultSourceInput, SecretReferences, _build_sandbox_exposed_url, _copy_model, @@ -329,7 +330,7 @@ def exec( run_as: Optional[str] = None, max_output_bytes: int = 64 * 1024 * 1024, secrets: Optional[SecretReferences] = None, - vault: Optional[str] = None, + vault: Optional[VaultSourceInput] = None, one_password: Optional[OnePasswordSourceInput] = None, ): """Run a command to completion. @@ -337,6 +338,8 @@ def exec( ``secrets`` maps environment variable names to stored secrets (a name, or ``{"name": ..., "version": N}``). ``vault`` names a vault whose entries become variables too; ``secrets`` win on a clash. + Customer-protected secrets are passed as the references + ``secrets.unwrap()`` and ``vaults.unwrap()`` return. ``one_password`` sets variables from fields of a 1Password vault (``{"token": op_token_secret, "vault": ..., "fields": {ENV: {"item", "section", "field"}}}``); those variables may come from nothing else. diff --git a/hyperbrowser/client/managers/sync_manager/sandboxes/sandbox_processes.py b/hyperbrowser/client/managers/sync_manager/sandboxes/sandbox_processes.py index 59b1e85b..f5185f33 100644 --- a/hyperbrowser/client/managers/sync_manager/sandboxes/sandbox_processes.py +++ b/hyperbrowser/client/managers/sync_manager/sandboxes/sandbox_processes.py @@ -27,6 +27,7 @@ ) from ...sandboxes.shared import ( OnePasswordSourceInput, + VaultSourceInput, SecretReferences, _normalize_exec_params, _runtime_process_payload, @@ -354,7 +355,7 @@ def exec( run_as: Optional[str] = None, max_output_bytes: int = DEFAULT_MAX_PROCESS_OUTPUT_BYTES, secrets: Optional[SecretReferences] = None, - vault: Optional[str] = None, + vault: Optional[VaultSourceInput] = None, one_password: Optional[OnePasswordSourceInput] = None, ) -> SandboxProcessResult: handle = self.start( @@ -387,7 +388,7 @@ def start( run_as: Optional[str] = None, max_output_bytes: int = DEFAULT_MAX_PROCESS_OUTPUT_BYTES, secrets: Optional[SecretReferences] = None, - vault: Optional[str] = None, + vault: Optional[VaultSourceInput] = None, one_password: Optional[OnePasswordSourceInput] = None, ) -> SandboxProcessHandle: """Start a process. diff --git a/hyperbrowser/client/managers/sync_manager/secret.py b/hyperbrowser/client/managers/sync_manager/secret.py index fb32ae6b..0292e9e5 100644 --- a/hyperbrowser/client/managers/sync_manager/secret.py +++ b/hyperbrowser/client/managers/sync_manager/secret.py @@ -1,20 +1,33 @@ import time -from typing import Dict, Optional, Sequence, Union +from typing import Dict, List, Literal, Optional, Sequence, Union from ..._request import coerce_request, dump_request +from ....customer_key import ( + CustomerKey, + CustomerKeys, + check_customer_key, + check_customer_keys, + check_unwrapped, + customer_key_for, + secret_envelope_digest, + sync_result, +) from ....exceptions import HyperbrowserError from ....models.secret import ( CreateSecretParams, + ReplaceSecretVersionWrappingParams, Secret, SecretDeleteResult, SecretDetail, SecretListParams, SecretListResponse, + SecretReference, SecretsPublicKey, SecretVersion, SecretValue, SecretVersionDeleteResult, UpdateSecretParams, + WrappedSecretVersion, ) from ....sandbox_common import ( ensure_response_ok, @@ -28,7 +41,11 @@ SECRET_NAME_LOOKUP_LIMIT, SecretsSealer, browser_metadata, + check_customer_protection, check_secret_version, + check_secret_version_or_latest, + create_secret_protection, + invalid_request, is_not_found, looks_like_secret_id, secret_not_found_error, @@ -37,6 +54,9 @@ update_secret_body, ) from ....types import CreateSecretParams as CreateSecretParamsDict +from ....types import ( + ReplaceSecretVersionWrappingParams as ReplaceSecretVersionWrappingParamsDict, +) from ....types import SecretListParams as SecretListParamsDict from ....types import UpdateSecretParams as UpdateSecretParamsDict @@ -47,6 +67,11 @@ class SecretManager: Values are encrypted on this machine to the platform's public key and are never returned by the API. Methods that take ``secret`` accept a secret's ID or its exact name. + + A customer-protected secret's versions are also wrapped locally with your + own key (``create_customer_key()``, or your own ``CustomerKey``), so the + platform stores nothing it can open alone. Each use passes the reference + ``unwrap()`` returns. """ def __init__(self, client): @@ -80,10 +105,14 @@ def create( account token, which starts with ``ops_``). ``allowed_origins`` makes a ``secret`` or ``totp`` fillable into browser pages on those origins. + ``protection="customer"`` wraps each version with your own key as + well; passing ``customer_key`` implies it, and wraps the first version. + The value and the public key are checked before the secret is created, so a bad value or an unavailable key leaves nothing behind. """ normalized = coerce_request(params, CreateSecretParams) + protection = create_secret_protection(normalized) payload = None sealer = None if normalized.value is not None: @@ -91,17 +120,16 @@ def create( normalized.type or "secret", normalized.value ) sealer = SecretsSealer(self.get_public_key()) - secret = Secret( - **self._request( - "POST", - "/secrets", - data=normalized.model_dump(by_alias=True, exclude_none=True), - ) - ) + body = normalized.model_dump(by_alias=True, exclude_none=True) + if protection is not None: + body["protection"] = protection + secret = Secret(**self._request("POST", "/secrets", data=body)) if sealer is None or payload is None: return secret try: - version = self._add_version(secret, payload, sealer) + version = self._add_version( + secret, payload, sealer, normalized.customer_key + ) except Exception as error: raise secret_value_not_stored_error(secret.id, secret.name, error) return secret.model_copy(update={"latest_version": version.version}) @@ -134,17 +162,136 @@ def set_allowed_origins( them, after which it can't be filled. Not for ``op_token`` secrets.""" return self.update(secret, {"metadata": browser_metadata(allowed_origins)}) - def add_version(self, secret: str, value: SecretValue) -> SecretVersion: + def add_version( + self, + secret: str, + value: SecretValue, + *, + customer_key: Optional[CustomerKey] = None, + ) -> SecretVersion: """Encrypt ``value`` locally and store it as the secret's next version. The value is checked against the secret's type first: a ``totp`` - secret takes a base32 seed or an ``otpauth://totp/`` URI. + secret takes a base32 seed or an ``otpauth://totp/`` URI. A + customer-protected secret's value is also wrapped with + ``customer_key``. """ secret_payload_bytes(None, value) + if customer_key is not None: + check_customer_key(customer_key) resolved = self._resolve(secret)[0] + check_customer_protection(resolved, customer_key) payload = secret_payload_bytes(resolved.type, value) return self._add_version( - resolved, payload, SecretsSealer(self.get_public_key()) + resolved, payload, SecretsSealer(self.get_public_key()), customer_key + ) + + def get_wrapped_version( + self, secret: str, version: Union[int, Literal["latest"]] = "latest" + ) -> WrappedSecretVersion: + """A customer-protected version's wrapped envelope, for unwrapping with + your own key. Most callers want ``unwrap()``, which also unwraps it.""" + check_secret_version_or_latest(version) + secret_id = self._resolve(secret)[0].id + return self._get_wrapped(secret_id, version) + + def unwrap( + self, + secret: str, + customer_key: CustomerKeys, + *, + version: Union[int, Literal["latest"]] = "latest", + ) -> SecretReference: + """Unwrap a customer-protected version locally with your own key. + + Returns the reference each use passes: as a sandbox's or process's + ``secrets`` entry, or as a 1Password ``token``. It is pinned to the + version unwrapped. The unwrapped envelope is checked against the + digest stored with the version, and only the platform can open it. + ``customer_key`` may be a list, such as during a rotation; the key + whose ``kid`` wrapped the version is used. + """ + check_secret_version_or_latest(version) + check_customer_keys(customer_key) + resolved = self._resolve(secret)[0] + wrapped = self._get_wrapped(resolved.id, version) + inner = self._unwrap( + wrapped, + customer_key, + f"Version {wrapped.version} of secret {resolved.name}", + ) + return SecretReference( + name=resolved.name, version=wrapped.version, unwrapped=inner + ) + + def rewrap( + self, + secret: str, + *, + from_key: CustomerKeys, + to_key: CustomerKey, + versions: Optional[Sequence[int]] = None, + ) -> List[WrappedSecretVersion]: + """Rewrap a customer-protected secret's versions with a new key, for + rotating your own key. + + Each version is unwrapped with ``from_key`` and wrapped with + ``to_key`` locally; the value never changes and the platform never + sees it. Without ``versions``, every version not yet wrapped with + ``to_key`` is rewrapped, so an interrupted rotation can be resumed. + Returns the versions rewrapped. + """ + check_customer_keys(from_key, "from_key") + check_customer_key(to_key, "to_key") + if versions is not None: + if isinstance(versions, (str, bytes)): + raise invalid_request("versions must be a list of version numbers") + for version in versions: + check_secret_version(version) + detail = self.get(secret) + if detail.protection != "customer": + raise invalid_request( + f"Secret {detail.name} is not customer-protected; it has no wrapping" + ) + wanted = ( + list(versions) + if versions is not None + else [ + item.version for item in detail.versions if item.outer_kid != to_key.kid + ] + ) + rewrapped = [] + for version in wanted: + wrapped = self._get_wrapped(detail.id, version) + inner = self._unwrap( + wrapped, from_key, f"Version {version} of secret {detail.name}" + ) + envelope = sync_result( + to_key.wrap(inner, detail.encryption_context), "wrap" + ) + rewrapped.append( + self._replace_wrapping( + detail.id, version, envelope, wrapped.inner_digest + ) + ) + return rewrapped + + def replace_version_wrapping( + self, + secret: str, + version: int, + params: Union[ + ReplaceSecretVersionWrappingParamsDict, ReplaceSecretVersionWrappingParams + ], + ) -> WrappedSecretVersion: + """Replace a customer-protected version's outer envelope with one you + wrapped yourself. ``inner_digest`` must match the version's: only the + wrapping changes, never the value. ``rewrap()`` does this for you.""" + check_secret_version(version) + request = coerce_request(params, ReplaceSecretVersionWrappingParams) + secret_id = self._resolve(secret)[0].id + return self._replace_wrapping( + secret_id, version, request.envelope, request.inner_digest ) def delete(self, secret: str) -> SecretDeleteResult: @@ -161,14 +308,48 @@ def delete_version(self, secret: str, version: int) -> SecretVersionDeleteResult return SecretVersionDeleteResult(**payload) def _add_version( - self, secret: Secret, payload: bytes, sealer: SecretsSealer + self, + secret: Secret, + payload: bytes, + sealer: SecretsSealer, + customer_key: Optional[CustomerKey] = None, ) -> SecretVersion: # Always the context the API returned; it differs by secret type. envelope = sealer.seal(secret.encryption_context, payload) + data: Dict[str, object] = {"envelope": envelope} + if customer_key is not None: + data = { + "envelope": sync_result( + customer_key.wrap(envelope, secret.encryption_context), "wrap" + ), + "innerDigest": secret_envelope_digest(envelope), + "innerKid": sealer.kid, + } + response = self._request("POST", f"/secrets/{secret.id}/versions", data=data) + return SecretVersion(**response) + + def _get_wrapped( + self, secret_id: str, version: Union[int, str] + ) -> WrappedSecretVersion: + return WrappedSecretVersion( + **self._request("GET", f"/secrets/{secret_id}/versions/{version}/wrapped") + ) + + def _replace_wrapping( + self, secret_id: str, version: int, envelope: str, inner_digest: str + ) -> WrappedSecretVersion: payload = self._request( - "POST", f"/secrets/{secret.id}/versions", data={"envelope": envelope} + "PUT", + f"/secrets/{secret_id}/versions/{version}/wrapping", + data={"envelope": envelope, "innerDigest": inner_digest}, ) - return SecretVersion(**payload) + return WrappedSecretVersion(**payload) + + @staticmethod + def _unwrap(wrapped: WrappedSecretVersion, keys: CustomerKeys, label: str) -> str: + key = customer_key_for(keys, wrapped.outer_kid, label) + inner = sync_result(key.unwrap(wrapped.envelope), "unwrap") + return check_unwrapped(inner, wrapped.inner_digest, label) def _get_by_id(self, secret_id: str) -> SecretDetail: return SecretDetail(**self._request("GET", f"/secrets/{secret_id}")) diff --git a/hyperbrowser/client/managers/sync_manager/vault.py b/hyperbrowser/client/managers/sync_manager/vault.py index 73a2aa3c..2a05b90b 100644 --- a/hyperbrowser/client/managers/sync_manager/vault.py +++ b/hyperbrowser/client/managers/sync_manager/vault.py @@ -1,6 +1,7 @@ from typing import Optional, Tuple, Union from ..._request import dump_request +from ....customer_key import CustomerKeys, check_customer_keys from ....exceptions import HyperbrowserError from ....models.vault import ( CreateVaultParams, @@ -9,6 +10,9 @@ VaultDeleteResult, VaultListParams, VaultListResponse, + VaultReference, + VaultUnwrappedEntry, + WrappedVault, ) from ....secrets_common import ( SECRET_NAME_LOOKUP_LIMIT, @@ -33,6 +37,9 @@ class VaultManager: Pass a vault by name as ``vault`` when creating a sandbox or starting a process, or as ``{"vault": name}`` in a browser session's ``credentials``. Methods that take ``vault`` accept its ID or exact name. + + A vault with customer-protected entries is passed to sandboxes and + processes as the reference ``unwrap()`` returns. """ def __init__(self, client): @@ -87,6 +94,34 @@ def delete(self, vault: str) -> VaultDeleteResult: payload = self._control._request("DELETE", f"/vaults/{vault_id}") return VaultDeleteResult(**payload) + def get_wrapped(self, vault: str) -> WrappedVault: + """The wrapped envelopes of a vault's customer-protected entries, at + the versions they resolve to now. Most callers want ``unwrap()``.""" + vault_id = (self._resolve(vault))[1] + payload = self._control._request("GET", f"/vaults/{vault_id}/wrapped") + return WrappedVault(**payload) + + def unwrap(self, vault: str, customer_key: CustomerKeys) -> VaultReference: + """Unwrap a vault's customer-protected entries locally with your own + key. + + Returns the reference a sandbox's or process's ``vault`` takes; its + other entries are delivered as usual. If an entry moves to another + secret or version before it is used, the API refuses the reference + with ``SECRET_VAULT_CHANGED``; unwrap the vault again. + ``customer_key`` may be a list; each entry uses the key whose ``kid`` + wrapped it. + """ + check_customer_keys(customer_key) + wrapped = self.get_wrapped(vault) + unwrapped = {} + for env, entry in wrapped.entries.items(): + inner = self._control._unwrap( + entry, customer_key, f"Entry {env} of vault {wrapped.name}" + ) + unwrapped[env] = VaultUnwrappedEntry(version=entry.version, unwrapped=inner) + return VaultReference(name=wrapped.name, unwrapped=unwrapped) + def _resolve(self, key: str) -> Tuple[Vault, str]: """Find a vault by ID or exact name.""" key = key.strip() diff --git a/hyperbrowser/models/__init__.py b/hyperbrowser/models/__init__.py index 33c87226..9e9e6ffd 100644 --- a/hyperbrowser/models/__init__.py +++ b/hyperbrowser/models/__init__.py @@ -266,6 +266,7 @@ CreateSecretParams, OnePasswordField, OnePasswordSource, + ReplaceSecretVersionWrappingParams, SandboxResolvedSecret, Secret, SecretBindingSource, @@ -276,6 +277,7 @@ SecretListParams, SecretListResponse, SecretMetadata, + SecretProtection, SecretReference, SecretReferenceInput, SecretsPublicKey, @@ -284,6 +286,7 @@ SecretVersion, SecretVersionDeleteResult, UpdateSecretParams, + WrappedSecretVersion, ) from .volume import ( CreateVolumeParams, @@ -348,6 +351,7 @@ ScreenConfig, Session, SessionCredential, + SessionVault, SessionCredentialInput, SessionCredentialOnePassword, SessionCredentialSecret, @@ -502,6 +506,10 @@ VaultEntry, VaultListParams, VaultListResponse, + VaultReference, + VaultUnwrappedEntry, + WrappedVault, + WrappedVaultEntry, ) __all__ = [ @@ -694,11 +702,16 @@ "VaultEntry", "VaultListParams", "VaultListResponse", + "VaultReference", + "VaultUnwrappedEntry", + "WrappedVault", + "WrappedVaultEntry", # secret "CreateSecretParams", "OnePasswordField", "OnePasswordFillSource", "OnePasswordSource", + "ReplaceSecretVersionWrappingParams", "SandboxResolvedSecret", "Secret", "SecretBindingSource", @@ -709,6 +722,7 @@ "SecretListParams", "SecretListResponse", "SecretMetadata", + "SecretProtection", "SecretReference", "SecretReferenceInput", "SecretsPublicKey", @@ -717,6 +731,7 @@ "SecretVersion", "SecretVersionDeleteResult", "UpdateSecretParams", + "WrappedSecretVersion", # volume "CreateVolumeParams", "Volume", @@ -751,6 +766,7 @@ "ScreenConfig", "Session", "SessionCredential", + "SessionVault", "SessionCredentialInput", "SessionCredentialOnePassword", "SessionCredentialSecret", diff --git a/hyperbrowser/models/credential.py b/hyperbrowser/models/credential.py index e6548035..3ed6209d 100644 --- a/hyperbrowser/models/credential.py +++ b/hyperbrowser/models/credential.py @@ -1,11 +1,11 @@ """Request and response models for filling secrets into browser pages.""" from datetime import datetime -from typing import List, Literal, Optional +from typing import List, Literal, Optional, Union from pydantic import BaseModel, ConfigDict, Field -from .secret import OnePasswordField +from .secret import OnePasswordField, SecretReference # What a fill did with each requested input. New outcomes may be added, so # results keep any string the server sends. @@ -44,8 +44,9 @@ class OnePasswordFillSource(BaseModel): """1Password fields to fill, read with an ``op_token`` secret attached to the session. - ``token`` names the op_token secret (its latest version signs in); - ``vault`` is the 1Password vault's name or ID. ``allowed_origins`` lists + ``token`` names the op_token secret (its latest version signs in), or + for a customer-protected op_token is the reference ``secrets.unwrap()`` + returns; ``vault`` is the 1Password vault's name or ID. ``allowed_origins`` lists the 1-20 origins (``scheme://host[:port]``, a leading ``*.`` for subdomains) the values may be typed on: unlike stored secrets, nothing else says where a 1Password value belongs. @@ -53,7 +54,7 @@ class OnePasswordFillSource(BaseModel): model_config = ConfigDict(populate_by_name=True, extra="forbid") - token: str + token: Union[str, SecretReference] vault: str allowed_origins: List[str] = Field(serialization_alias="allowedOrigins") diff --git a/hyperbrowser/models/sandbox.py b/hyperbrowser/models/sandbox.py index fdf6fa0b..f797f39d 100644 --- a/hyperbrowser/models/sandbox.py +++ b/hyperbrowser/models/sandbox.py @@ -18,6 +18,7 @@ normalize_secret_references, ) from .session import SessionLaunchState, SessionStatus +from .vault import VaultReference SandboxStatus = SessionStatus SandboxRegion = Literal[ @@ -257,8 +258,9 @@ class CreateSandboxParams(_SandboxLaunchCommonParams): # command only. secrets: Optional[Dict[str, SecretReference]] = None # A vault, by name, whose entries are delivered to the startup command; - # ``secrets`` are merged over it. - vault: Optional[str] = None + # ``secrets`` are merged over it. A vault with customer-protected entries + # is passed as the reference ``vaults.unwrap()`` returns. + vault: Optional[Union[str, VaultReference]] = None # Fields of a 1Password vault, delivered to the startup command. A # variable here may not also come from ``vault`` or ``secrets``. one_password: Optional[OnePasswordSource] = Field( @@ -608,8 +610,10 @@ class SandboxExecParams(SandboxBaseModel): # the control API, which has the platform decrypt them in the sandbox. secrets: Optional[Dict[str, SecretReference]] = None # A vault, by name, whose entries become environment variables; ``secrets`` - # are merged over it. Starts through the control API like ``secrets``. - vault: Optional[str] = None + # are merged over it. Starts through the control API like ``secrets``. A + # vault with customer-protected entries is passed as the reference + # ``vaults.unwrap()`` returns. + vault: Optional[Union[str, VaultReference]] = None # Fields of a 1Password vault as environment variables, resolved in the # sandbox at start. A variable here may not also come from ``vault``, # ``secrets`` or ``env``. Starts through the control API like ``secrets``. diff --git a/hyperbrowser/models/secret.py b/hyperbrowser/models/secret.py index 5009cf05..771070f5 100644 --- a/hyperbrowser/models/secret.py +++ b/hyperbrowser/models/secret.py @@ -1,6 +1,6 @@ import re from datetime import datetime -from typing import Dict, List, Literal, Optional, Union +from typing import Any, Dict, List, Literal, Optional, Union from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator @@ -11,6 +11,8 @@ MAX_SECRET_VERSION = 2**31 - 1 MAX_SECRET_BINDINGS = 32 MAX_SECRET_ENV_NAME_LENGTH = 256 +# The longest unwrapped envelope the API takes. +MAX_UNWRAPPED_ENVELOPE_LENGTH = 64 * 1024 def validate_secret_name(name: str) -> str: @@ -34,6 +36,18 @@ def validate_secret_version(version: int) -> int: return version +def validate_unwrapped_envelope(value, what: str = "the secret"): + if value is not None and ( + not isinstance(value, str) + or not 1 <= len(value) <= MAX_UNWRAPPED_ENVELOPE_LENGTH + ): + raise ValueError( + f"The unwrapped envelope of {what} must be a string of 1 to " + f"{MAX_UNWRAPPED_ENVELOPE_LENGTH} characters" + ) + return value + + class SecretBaseModel(BaseModel): model_config = ConfigDict(populate_by_name=True) @@ -41,11 +55,15 @@ class SecretBaseModel(BaseModel): class SecretReference(SecretBaseModel): """Selects a stored secret for an environment variable. - An omitted version (or ``"latest"``) means the latest version. + An omitted version (or ``"latest"``) means the latest version. A + customer-protected secret also takes ``unwrapped``, the envelope + ``secrets.unwrap()`` returns, and then ``version`` must be the version + number it was unwrapped from. """ name: str version: Optional[Union[int, Literal["latest"]]] = None + unwrapped: Optional[str] = Field(default=None, repr=False) @field_validator("name") @classmethod @@ -59,6 +77,21 @@ def validate_version(cls, value): validate_secret_version(value) return value + @field_validator("unwrapped", mode="plain") + @classmethod + def validate_unwrapped(cls, value): + return validate_unwrapped_envelope(value) + + @model_validator(mode="after") + def require_pinned_version(self): + # An unwrapped envelope is one version's value; "latest" could move on. + if self.unwrapped is not None and not isinstance(self.version, int): + raise ValueError( + f"Pin the version of secret {self.name} to the version you " + 'unwrapped when passing "unwrapped"' + ) + return self + SecretReferenceInput = Union[str, SecretReference] @@ -119,7 +152,9 @@ class OnePasswordSource(SecretBaseModel): model_config = ConfigDict(populate_by_name=True, extra="forbid") - token: str + # The op_token secret's name, or for a customer-protected op_token the + # reference ``secrets.unwrap()`` returns. + token: Union[str, SecretReference] vault: str fields: Dict[str, OnePasswordField] @@ -133,6 +168,12 @@ class OnePasswordSource(SecretBaseModel): # one_password fields SecretType = Literal["secret", "totp", "op_token"] +# Who can open a secret's stored versions; fixed when the secret is created. +# platform the platform alone (the default) +# customer only with the customer's own key as well: each version is +# wrapped with it, and each use passes the unwrapped envelope +SecretProtection = Literal["platform", "customer"] + # A secret value, encrypted locally before upload. SecretValue = Union[str, bytes] @@ -185,9 +226,14 @@ class CreateSecretParams(SecretBaseModel): # Omitted means "secret". type: Optional[SecretType] = None metadata: Optional[SecretMetadata] = None + # Omitted means "platform", or "customer" when customer_key is given. + protection: Optional[SecretProtection] = None allowed_origins: Optional[List[str]] = Field(default=None, exclude=True) # Encrypted locally and uploaded as the first version; never sent as is. value: Optional[SecretValue] = Field(default=None, exclude=True, repr=False) + # A CustomerKey that wraps the first version of a customer-protected + # secret; never sent. + customer_key: Optional[Any] = Field(default=None, exclude=True, repr=False) @field_validator("name") @classmethod @@ -268,25 +314,45 @@ class Secret(SecretBaseModel): # One of SecretType; kept as str so types the API adds later still parse. type: str = "secret" metadata: SecretMetadata = Field(default_factory=SecretMetadata) + # One of SecretProtection; kept as str like ``type``. + protection: str = "platform" encryption_context: str = Field(alias="encryptionContext") latest_version: Optional[int] = Field(default=None, alias="latestVersion") created_at: Optional[datetime] = Field(default=None, alias="createdAt") updated_at: Optional[datetime] = Field(default=None, alias="updatedAt") - @field_validator("type", "metadata", mode="before") + @field_validator("type", "metadata", "protection", mode="before") @classmethod def default_when_null(cls, value, info): if value is not None: return value - return "secret" if info.field_name == "type" else {} + return {"type": "secret", "protection": "platform"}.get(info.field_name, {}) class SecretVersion(SecretBaseModel): version: int + # The platform key the value is sealed to. kid: str + # The customer key that wrapped a customer-protected version. + outer_kid: Optional[str] = Field(default=None, alias="outerKid") + # When the platform key retires; a retired version can't be used. + retires_at: Optional[datetime] = Field(default=None, alias="retiresAt") created_at: Optional[datetime] = Field(default=None, alias="createdAt") +class WrappedSecretVersion(SecretBaseModel): + """A customer-protected version as stored: ``envelope`` is the inner + envelope (sealed to the platform key ``kid``) wrapped with the customer + key ``outer_kid``, and ``inner_digest`` identifies the inner envelope.""" + + version: int + kid: str + retires_at: Optional[datetime] = Field(default=None, alias="retiresAt") + outer_kid: str = Field(alias="outerKid") + inner_digest: str = Field(alias="innerDigest") + envelope: str = Field(repr=False) + + class SecretDetail(Secret): versions: List[SecretVersion] = Field(default_factory=list) @@ -309,6 +375,16 @@ class SecretVersionDeleteResult(SecretBaseModel): version: int +class ReplaceSecretVersionWrappingParams(SecretBaseModel): + """A customer-protected version's new outer envelope. ``inner_digest`` + must be the version's: only the wrapping changes, never the value.""" + + model_config = ConfigDict(populate_by_name=True, extra="forbid") + + envelope: str = Field(min_length=1, repr=False) + inner_digest: str = Field(min_length=1, serialization_alias="innerDigest") + + class SecretBindingSource(SecretBaseModel): """Where a delivered variable came from: ``type`` is ``"vault"`` (with the vault's ``name``), ``"secrets"`` (the request's own ``secrets``) or diff --git a/hyperbrowser/models/session.py b/hyperbrowser/models/session.py index 624f54e1..4866d533 100644 --- a/hyperbrowser/models/session.py +++ b/hyperbrowser/models/session.py @@ -264,6 +264,18 @@ class SessionCredential(BaseModel): name: str +class SessionVault(BaseModel): + """A vault attached to a session at creation. Fills read its entries as + they are when the fill runs.""" + + model_config = ConfigDict( + populate_by_alias=True, + ) + + id: str + name: str + + class SessionCredentialSecret(BaseModel): """Attaches a secret, by name, to a new session.""" @@ -319,6 +331,8 @@ class SessionDetail(Session): credentials: Optional[List[SessionCredential]] = Field( default=None, alias="credentials" ) + # The vaults attached at creation, by reference. + vaults: Optional[List[SessionVault]] = Field(default=None, alias="vaults") class SessionGetParams(BaseModel): diff --git a/hyperbrowser/models/vault.py b/hyperbrowser/models/vault.py index c2bf6f87..79f229c6 100644 --- a/hyperbrowser/models/vault.py +++ b/hyperbrowser/models/vault.py @@ -6,7 +6,15 @@ from pydantic import ConfigDict, Field, field_validator -from .secret import SecretBaseModel +from .secret import ( + MAX_SECRET_BINDINGS, + SecretBaseModel, + WrappedSecretVersion, + validate_secret_env_name, + validate_secret_name, + validate_secret_version, + validate_unwrapped_envelope, +) class StoredEntry(SecretBaseModel): @@ -29,6 +37,9 @@ class VaultEntry(StoredEntry): model_config = ConfigDict(populate_by_name=True, extra="allow") secret_id: Optional[str] = Field(default=None, alias="secretId") + # The secret's protection: a "customer" entry is used through the + # reference ``vaults.unwrap()`` returns. + protection: Optional[str] = None class CreateVaultParams(SecretBaseModel): @@ -95,6 +106,79 @@ class VaultDeleteResult(SecretBaseModel): name: Optional[str] = None +class WrappedVaultEntry(WrappedSecretVersion): + """A customer-protected entry's wrapped envelope: the version of secret + ``name`` the entry resolves to now.""" + + name: str + secret_id: str = Field(alias="secretId") + + +class WrappedVault(SecretBaseModel): + """A vault's customer-protected entries, wrapped; other entries are + left out.""" + + id: str + name: str + entries: Dict[str, WrappedVaultEntry] = Field(default_factory=dict) + + @field_validator("entries", mode="before") + @classmethod + def default_entries(cls, value): + return {} if value is None else value + + +class VaultUnwrappedEntry(SecretBaseModel): + """One customer-protected entry, unwrapped: the version it was unwrapped + from and its envelope, which only the platform can open.""" + + model_config = ConfigDict(populate_by_name=True, extra="forbid") + + version: int + unwrapped: str = Field(repr=False) + + @field_validator("version", mode="before") + @classmethod + def validate_version(cls, value): + return validate_secret_version(value) + + @field_validator("unwrapped", mode="plain") + @classmethod + def validate_unwrapped(cls, value): + if value is None: + raise ValueError("unwrapped is required") + return validate_unwrapped_envelope(value, "the vault entry") + + +class VaultReference(SecretBaseModel): + """A vault with its customer-protected entries unwrapped, as + ``vaults.unwrap()`` returns it. Pass it as a sandbox's or process's + ``vault``; entries that aren't customer-protected are delivered as + usual.""" + + model_config = ConfigDict(populate_by_name=True, extra="forbid") + + name: str + unwrapped: Dict[str, VaultUnwrappedEntry] + + @field_validator("name") + @classmethod + def validate_name(cls, value): + return validate_secret_name(value) + + @field_validator("unwrapped", mode="before") + @classmethod + def validate_entries(cls, value): + if isinstance(value, dict): + if len(value) > MAX_SECRET_BINDINGS: + raise ValueError( + f"At most {MAX_SECRET_BINDINGS} unwrapped vault entries are allowed" + ) + for env in value: + validate_secret_env_name(env, "a vault entry") + return value + + __all__ = [ "CreateVaultParams", "StoredEntry", @@ -104,4 +188,8 @@ class VaultDeleteResult(SecretBaseModel): "VaultEntry", "VaultListParams", "VaultListResponse", + "VaultReference", + "VaultUnwrappedEntry", + "WrappedVault", + "WrappedVaultEntry", ] diff --git a/hyperbrowser/secrets_common.py b/hyperbrowser/secrets_common.py index a910a104..0bb8196a 100644 --- a/hyperbrowser/secrets_common.py +++ b/hyperbrowser/secrets_common.py @@ -21,6 +21,7 @@ from cryptography.hazmat.primitives.ciphers.aead import AESGCM from .client._request import coerce_request +from .customer_key import check_customer_key from .exceptions import HyperbrowserError from .models.secret import ( SecretsPublicKey, @@ -358,6 +359,55 @@ def check_secret_version(version: int) -> int: raise HyperbrowserError(str(error), code="invalid_secret_version") from None +def check_secret_version_or_latest(version: Any) -> Union[int, str]: + """Check a version number, or ``"latest"``, before it is used in a path.""" + if version == "latest" and isinstance(version, str): + return version + return check_secret_version(version) + + +def invalid_request(message: str) -> HyperbrowserError: + return HyperbrowserError(message, code="invalid_request") + + +def create_secret_protection(params: Any) -> Optional[str]: + """The protection a create sends, after checking it fits ``customer_key``: + a customer key implies ``"customer"``, and a customer-protected value + needs one to be wrapped with.""" + customer_key = params.customer_key + protection = params.protection + if protection is None and customer_key is not None: + protection = "customer" + if customer_key is not None: + if protection != "customer": + raise invalid_request( + 'customer_key is only for secrets with protection "customer"' + ) + check_customer_key(customer_key) + if protection == "customer" and params.value is not None and customer_key is None: + raise invalid_request( + "A customer-protected secret's value is wrapped with your own key: " + "pass customer_key" + ) + return protection + + +def check_customer_protection(secret: Any, customer_key: Any) -> None: + """Raise unless ``customer_key`` is given exactly for a customer-protected + secret.""" + customer = secret.protection == "customer" + if customer and customer_key is None: + raise invalid_request( + f"Secret {secret.name} is customer-protected: pass customer_key to " + "wrap the value with" + ) + if not customer and customer_key is not None: + raise invalid_request( + f"Secret {secret.name} is not customer-protected, so its versions " + "aren't wrapped: omit customer_key" + ) + + def secret_not_found_error(key: str) -> HyperbrowserError: return HyperbrowserError( f'Secret "{key}" not found', diff --git a/hyperbrowser/types/__init__.py b/hyperbrowser/types/__init__.py index 0778d09c..f4c16b3b 100644 --- a/hyperbrowser/types/__init__.py +++ b/hyperbrowser/types/__init__.py @@ -15,6 +15,8 @@ StoredEntry, UpdateVaultParams, VaultListParams, + VaultReference, + VaultUnwrappedEntry, ) from .webmcp import ( WebMCPInvokeParams, @@ -174,9 +176,11 @@ CreateSecretParams, OnePasswordField, OnePasswordSource, + ReplaceSecretVersionWrappingParams, SecretBrowserMetadata, SecretListParams, SecretMetadata, + SecretProtection, SecretReference, SecretReferenceInput, SecretType, @@ -219,6 +223,8 @@ "StoredEntry", "UpdateVaultParams", "VaultListParams", + "VaultReference", + "VaultUnwrappedEntry", "WebMCPInvokeParams", "WebMCPStartParams", "WebMCPResultParams", @@ -367,9 +373,11 @@ "OnePasswordField", "OnePasswordFillSource", "OnePasswordSource", + "ReplaceSecretVersionWrappingParams", "SecretBrowserMetadata", "SecretListParams", "SecretMetadata", + "SecretProtection", "SecretReference", "SecretReferenceInput", "SecretType", diff --git a/hyperbrowser/types/credential.py b/hyperbrowser/types/credential.py index bb982bb5..d73f471f 100644 --- a/hyperbrowser/types/credential.py +++ b/hyperbrowser/types/credential.py @@ -1,10 +1,10 @@ """Typed dictionary requests for filling secrets into browser pages.""" -from typing import List, Optional +from typing import List, Optional, Union from typing_extensions import Required, TypedDict -from .secret import OnePasswordField +from .secret import OnePasswordField, SecretReference class CredentialFillField(TypedDict, total=False): @@ -22,7 +22,7 @@ class OnePasswordFillSource(TypedDict): (attached to the session) from ``vault``, typed only on ``allowed_origins`` (1-20 origins such as ``https://example.com``).""" - token: str + token: Union[str, SecretReference] vault: str allowed_origins: List[str] diff --git a/hyperbrowser/types/sandbox.py b/hyperbrowser/types/sandbox.py index 6fc3f3ee..09c22131 100644 --- a/hyperbrowser/types/sandbox.py +++ b/hyperbrowser/types/sandbox.py @@ -3,6 +3,7 @@ from typing_extensions import Required, TypeAlias, TypedDict from .secret import OnePasswordSource, SecretReferenceInput +from .vault import VaultReference SandboxStatus: TypeAlias = Literal["active", "closed", "error", "close-error"] @@ -100,7 +101,7 @@ class CreateSandboxFromImageParams(_CreateSandboxCommon, total=False): memory_mib: Optional[int] disk_mib: Optional[int] secrets: Optional[Dict[str, SecretReferenceInput]] - vault: Optional[str] + vault: Optional[Union[str, VaultReference]] one_password: Optional[OnePasswordSource] @@ -255,7 +256,7 @@ class SandboxExecParams(TypedDict, total=False): run_as: Optional[str] use_shell: Optional[bool] secrets: Optional[Dict[str, SecretReferenceInput]] - vault: Optional[str] + vault: Optional[Union[str, VaultReference]] one_password: Optional[OnePasswordSource] diff --git a/hyperbrowser/types/secret.py b/hyperbrowser/types/secret.py index 49e6e8a2..44dc8ddd 100644 --- a/hyperbrowser/types/secret.py +++ b/hyperbrowser/types/secret.py @@ -2,12 +2,18 @@ from typing_extensions import Required, TypeAlias, TypedDict +from ..customer_key import CustomerKey + class SecretReference(TypedDict, total=False): - """Selects a stored secret; an omitted version means the latest.""" + """Selects a stored secret; an omitted version means the latest. A + customer-protected secret also takes ``unwrapped``, the envelope + ``secrets.unwrap()`` returns, with ``version`` pinned to the version + number it was unwrapped from.""" name: Required[str] version: Optional[Union[int, Literal["latest"]]] + unwrapped: Optional[str] # A plain secret name is shorthand for {"name": name}. @@ -25,9 +31,11 @@ class OnePasswordField(TypedDict, total=False): class OnePasswordSource(TypedDict): """Environment variables from fields of one 1Password vault, signed in to - with the ``op_token`` secret named ``token``.""" + with the ``op_token`` secret named ``token`` (or, for a + customer-protected op_token, the reference ``secrets.unwrap()`` + returns).""" - token: str + token: Union[str, SecretReference] vault: str fields: Dict[str, OnePasswordField] @@ -37,6 +45,10 @@ class OnePasswordSource(TypedDict): # "op_token" a 1Password service account token. SecretType = Literal["secret", "totp", "op_token"] +# Who can open a secret's stored versions: the platform alone, or only with +# the customer's own key as well. Fixed when the secret is created. +SecretProtection = Literal["platform", "customer"] + # A secret value, encrypted locally before upload. SecretValue: TypeAlias = Union[str, bytes] @@ -59,14 +71,18 @@ class CreateSecretParams(TypedDict, total=False): ``allowed_origins`` is shorthand for ``metadata.browser.allowed_origins``; it makes a ``secret`` or ``totp`` fillable in browser sessions. + ``customer_key`` wraps the first version of a customer-protected secret, + and implies ``protection="customer"``. """ name: Required[str] description: Optional[str] type: Optional[SecretType] + protection: Optional[SecretProtection] allowed_origins: Optional[List[str]] metadata: Optional[SecretMetadata] value: Optional[SecretValue] + customer_key: Optional[CustomerKey] class UpdateSecretParams(TypedDict, total=False): @@ -77,6 +93,14 @@ class UpdateSecretParams(TypedDict, total=False): metadata: Optional[SecretMetadata] +class ReplaceSecretVersionWrappingParams(TypedDict): + """A customer-protected version's new outer envelope; ``inner_digest`` + must be the version's.""" + + envelope: str + inner_digest: str + + class SecretListParams(TypedDict, total=False): """Filters and pagination for listing secrets.""" @@ -90,9 +114,11 @@ class SecretListParams(TypedDict, total=False): "CreateSecretParams", "OnePasswordField", "OnePasswordSource", + "ReplaceSecretVersionWrappingParams", "SecretBrowserMetadata", "SecretListParams", "SecretMetadata", + "SecretProtection", "SecretReference", "SecretReferenceInput", "SecretType", diff --git a/hyperbrowser/types/vault.py b/hyperbrowser/types/vault.py index 54e15ad4..3b0dbe12 100644 --- a/hyperbrowser/types/vault.py +++ b/hyperbrowser/types/vault.py @@ -28,6 +28,22 @@ class UpdateVaultParams(TypedDict, total=False): entries: Optional[Dict[str, Optional[StoredEntry]]] +class VaultUnwrappedEntry(TypedDict): + """One customer-protected entry, unwrapped: the version it was unwrapped + from and its envelope.""" + + version: int + unwrapped: str + + +class VaultReference(TypedDict): + """A vault with its customer-protected entries unwrapped, as + ``vaults.unwrap()`` returns it.""" + + name: str + unwrapped: Dict[str, VaultUnwrappedEntry] + + class VaultListParams(TypedDict, total=False): """Filters and pagination for listing vaults.""" @@ -41,4 +57,6 @@ class VaultListParams(TypedDict, total=False): "StoredEntry", "UpdateVaultParams", "VaultListParams", + "VaultReference", + "VaultUnwrappedEntry", ] From ce990bc0cf7392fd1900bf931207e9cc839cf200 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 19:53:19 +0000 Subject: [PATCH 3/4] Test customer-protected secrets and key interop Co-authored-by: Ninad Sinha --- tests/fixtures/customer_key_interop.json | 80 +++ tests/test_customer_secrets.py | 718 +++++++++++++++++++++++ tests/typecheck/invalid_requests.py | 12 + tests/typecheck/valid_requests.py | 96 +++ 4 files changed, 906 insertions(+) create mode 100644 tests/fixtures/customer_key_interop.json create mode 100644 tests/test_customer_secrets.py diff --git a/tests/fixtures/customer_key_interop.json b/tests/fixtures/customer_key_interop.json new file mode 100644 index 00000000..0f0c742a --- /dev/null +++ b/tests/fixtures/customer_key_interop.json @@ -0,0 +1,80 @@ +{ + "about": "Throwaway test keys. Envelopes wrapped by the Node and Python SDKs; each SDK must unwrap both.", + "context": "hb-secret-v1:team_fixture:6f1d3c1e-5b8a-4e6f-9a51-0c2b7f3d9e10", + "inner": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoicGxhdGZvcm0ifQ.a2V5.aXY.Y2lwaGVydGV4dA.dGFn", + "innerDigest": "DoW8NO1f4rVoq5sMs8mrBlvpXHo-U7jdfXilx_HzvyI", + "keys": [ + { + "label": "rsa-2048", + "algorithm": "RSA-OAEP-256", + "jwk": { + "kty": "RSA", + "n": "p2kQEhw9dp076z8aM5TR4TAa_XkDIw-Xw2GO-GWOFFgEIsL1VIwtdhuQRhWdGvd6LrmLlCRs6kz3RxJPTpJ8wAb-wrbxK9cLmJ-UJMdR4QYkdN8s9UqaB4ceJUnQU6DcJ1FWrjLkPyMKMGgfFGonvS_Jeqo7zayQiJELajkELtZpgpDsywrZbSVZvv0iYP5bpjZpYjTdsxrEVc4Np5L2R0rqeMvyS5Eu4R9Ib09ZDIqX_5s0YWRmHHsAKcXmN-iJFVKz9vKOWkE5iVwVmrghaUEdABBLlANbSWbtg53F3dEJrhVziz4VQHbv5YkyLza3XunWc18b2aqSIa-didQh4Q", + "e": "AQAB", + "d": "HCkAGwvFCv7H5Xpn3eVaqJZ-88Q3Ut58mNEAS6hJjgKAL5i7y80ImKVqT1-zXaXjV5i-cdzutTrdHYdm78CUW3jRwc8kIku6F6JAOS-OBlwSJdakqV4zKrD_0SXpdSfJ4JM-EW9eFYC_ZgUdtUFmDdzL92ZLSP2OEmrTkLqmiXoheOaHgvInk8bV2qsZdqvrLxzj5GojbIVb_5-CzmJrn1o4i6WfGpIQ1gECRHW84uxmY11Lcxq1Tt5Xr4G9EwEB5NB9vaUc1znkefQO_mMPp4_37zORAZotLZiekHonHU8WE5oEkYrAuzHPKvqnPtd7cCQV_4P3DrBLTnv5BLwoQQ", + "p": "6hq-G3iWJuDLrCDOLViAHCLJ2K21RUkQMTw2K2FAS4G4N1AI10Awo__orogJ4KR6ozjuicTXvRt7eq_GNIc0ucGvNeOBzYBhy0nFuALNleGtpQsHJxwYfdrN0qRPiNjsXwPohl8hi0joJD9sh6o93NymMeZPzxvAColEmE0rF58", + "q": "txFv-Znw7F9t49Roc7ENn9xox6okAuUxY8wLAkbx1LdRfqJNcfu-pu4sv6zAbFDPdhT8k_ABgQZ8lSG4zo-twFRTjJwbDXnbEmKvy4QtGTdUUPagXBTTHSicicFhAuIx3v3F0QmSo9ZuOtFbCQuA-YrSLTLpnssfDt549xn8Vn8", + "dp": "McQ1nclowiMPqSvgKKujsFeE6VckLfJ2SsEuEtK9xE9zRe7xsjCnJnYElPW-g87zczdrHkaGRmFNQquTSx9jCgouoRoYQgOExp6MNa4C3lX3gBp0DtBeNIMLNjhP4BudRCWkjMw0aVO6ZdpFzCFYvVb6zajUVobjsFm2B1qASqk", + "dq": "AzQ37HtoPwrQhotCJLw1i9W0s8HjjXVrbt60Vp7dPqbSs0-t4U_Rn2RNvjEM0Rh8-QkW_pPVwudVKNsFPABBvzr6l1xoEM1QKzs07m_qxiU0wZH_bn0i0MDUNIkA5KcGzmtMmgL74Qgwt7DQUhE0eamXUhkxA4l0irMUFOcMhos", + "qi": "lPBPvjwZzYq-fQWVb1Kb-RPcr5VVbJD6Lm_u2OL4ahkMJa3tFdoNormISDKYzpJ8c2wv_xpO980o2pVwgd9IcSM2dkqbm1vaduUjToA3PACOZLv14BuogjQThNlaczt3YC_CzC5JiX9m-PECfFH94zUkLwwNAurbCeZtRlK2ag4" + }, + "kid": "_FBIIs2D_wVdLliJ93PRe2Da0Ul_aqRXza6VHroBiIU", + "wrappedByNode": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoiX0ZCSUlzMkRfd1ZkTGxpSjkzUFJlMkRhMFVsX2FxUlh6YTZWSHJvQmlJVSIsImN0eCI6ImhiLXNlY3JldC12MTp0ZWFtX2ZpeHR1cmU6NmYxZDNjMWUtNWI4YS00ZTZmLTlhNTEtMGMyYjdmM2Q5ZTEwIn0.EkMxha80QvplqXUQ0_C5y_ZJQGAzizYBeDg6-kg2R2UB0JPS0TDPkuGzVLehmUSWk4JaAv_wmIAvAIlGePldqZ1h3UVV9m190Q5-5eiZyLLfgs1Sk4ccUbWNwIvafC8KfcAtFmfF-NLlCxaE4zL2HAqGv_RkKufHRskgfD2bf2kM-8rt9yBL5zj9gk1PFkSxgsJTtk1Fcp7OKfrkK4vctNmVIFbvPyEZrs-frEJM3NJAHyAQJP28-6bzDmSTYdRmxRc-d5uuGZ5-VW5WkVjJg5oyvyGQm_YVpBhi67Rfrddif0gNGCahtbac4B8GJOEp6MdoSSdAphIXAMzoF0X2LQ.29_WDLi3SKkpMg-f.-c3Ol2gyxb4j32ztbpchiZGjYrE18vLgEffkwHGbHVDROjHJERu7IRzl0YZgnmapfesqKg8A0nv6W_9RoSGEGe4z3_oFp_fGh4MWZwsXV5qUvai1D8xP00VzScysU7TkpTDen5ipvA.RvO5OqZO5yfyID83M0dUcA", + "wrappedByPython": "eyJhbGciOiJSU0EtT0FFUC0yNTYiLCJlbmMiOiJBMjU2R0NNIiwia2lkIjoiX0ZCSUlzMkRfd1ZkTGxpSjkzUFJlMkRhMFVsX2FxUlh6YTZWSHJvQmlJVSIsImN0eCI6ImhiLXNlY3JldC12MTp0ZWFtX2ZpeHR1cmU6NmYxZDNjMWUtNWI4YS00ZTZmLTlhNTEtMGMyYjdmM2Q5ZTEwIn0.gYBYMs-xdCmCdbMjMFqgxb3_kSuqfD6XwOUaL4Dqx5CNd_CGPELiKXl4nvDBDHiX59-_QF6c2WSgV-YTdXM1Il_mlRpNxOXKH06tAMGrNL_lf264JeJLT1pMO70ww13yud3Dr12EzEeSJwyM78o_aw8gZFt1oO8-OSfaGPlVE_PFt-OxRd1svu5kKleqyWLVJsoKfKzp2MTwry7AQyECdggiaZ7mrWHyEyvEGeCXMDtwGmqkFEA4L6TmdnEMTisVooYD2DqP3IkBjIJsjuAQyV0QUM5sM8Ol89a4nCVrkK3pHEV4ZLW5vIFc0SBH3miTF9UO8620q1TEuz1C5Natyg.NvN09cM9LkzeChW_.tqofTXuHuJ79Pmbc_8I2RFXR9OzMjOqbDykelb9M-3Qdk_vyBNurrMOSY8CjPt0rMlj6NB-hbuuMHPsTQf8MmK8RGFuIYiAcpe4HTKYaDYIZbY-u8r1BRxTLlxmuUwM-Tkmqc1jlAg.2XXEiA1Kqz1FvVbbOwTs4A" + }, + { + "label": "p-256", + "algorithm": "ECDH-ES+A256KW", + "jwk": { + "kty": "EC", + "x": "Zr2qtLIXe3AeGL7HmhVPsFD9EYUQfkqE4WcGMZlpUnc", + "y": "_2jmh34p1jmuI-S6N8aca7KtirrPwJjq4h_jRux2QOg", + "crv": "P-256", + "d": "p5ZqhGq8alcsDcgq_zIi_B9ExkF_1suosznWw3iLjCM" + }, + "kid": "4ttAqrEVmQ3gzrQXH9vYpX1V-MxiuMWBs_CYd64dBkY", + "wrappedByNode": "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiI0dHRBcXJFVm1RM2d6clFYSDl2WXBYMVYtTXhpdU1XQnNfQ1lkNjRkQmtZIiwiY3R4IjoiaGItc2VjcmV0LXYxOnRlYW1fZml4dHVyZTo2ZjFkM2MxZS01YjhhLTRlNmYtOWE1MS0wYzJiN2YzZDllMTAiLCJlcGsiOnsiY3J2IjoiUC0yNTYiLCJrdHkiOiJFQyIsIngiOiJNMTZvczU1LVpzcy01Skx6cHh6WmNHZE5ua2NGUTlpTVBkd29xRVpHSnJvIiwieSI6IlQyclJPRldvQnB6T2R3M2NxQUtRb3VXTnBsbmQtLUtuMkhwMWV6M3d3QjQifX0.EEV9pLdbb8-mTpcIjKnLNezz8Kbi_cn8_AeD9tX2JOWkAoxkLz3JVQ.LA_2FnRQTyrLhlkw.GQZbrdURYFJU4UmzFOz81RpDD5gCfFkkmyneGbkgZfzGbu6pJnbF9b7h7aQjX3LY9itnZ-KdPaAu4CYVoiK4cNUxuvhlBT5VRVbosA2YfYzxswSCPbqq5gPowJ_NrvMIIHga7OPpug._ISWNu1ZXorq8lkOJHh5_Q", + "wrappedByPython": "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiI0dHRBcXJFVm1RM2d6clFYSDl2WXBYMVYtTXhpdU1XQnNfQ1lkNjRkQmtZIiwiY3R4IjoiaGItc2VjcmV0LXYxOnRlYW1fZml4dHVyZTo2ZjFkM2MxZS01YjhhLTRlNmYtOWE1MS0wYzJiN2YzZDllMTAiLCJlcGsiOnsiY3J2IjoiUC0yNTYiLCJrdHkiOiJFQyIsIngiOiJLbkdvc2ppeDUwZnBsUlN3bXBhWC1ENEtLZzlPeThpRndPTUFQbVdJc0pRIiwieSI6IkdPT3hKb1RsU2Jaa0Q3X0lHRzhXZDFXWTlBSllwNklXTXp2UkthdF9TWjAifX0.4O3TphALVVj_f6G0_wwIsOsiRnKhZZoCTnJ9jbB3CN1UralrLwnRnw.9RV3HqOsSzUC6VU9.FNb9SU6PwuE4zmu2dZGE2Uk4tYYieeW7m9Prr44dKt_RDD03KAb1VOsp1PZaP1CEanmIeOBnPKv4KR7obozgMGs5_YgyXKetAYprqUD6WYw3gk2xupqhNBEJDmix_7_byxV5KnXcHg.5gNOeffAiSwhB7x4_ABJRg" + }, + { + "label": "p-521", + "algorithm": "ECDH-ES", + "jwk": { + "kty": "EC", + "x": "AHobEvicT4YKcVb_A-IAm3zFz9_InDY37yh_THSqQaARHLjAH9XgPd29oBGr3kOWncm4-E5BQ0iEcG7aKS7D-dwY", + "y": "ADB02ULFoCBdxqw4BpM3htPKEwynxvsWTFyAfNWmMCNoph7PStG8t9MK8OHmhG1yrNLTTELdox_QyUHCJx70rBw_", + "crv": "P-521", + "d": "AUYKj_0wfctv6AFU6EsH00rM69kaYgmIa_XtiOZZUBbm56K1RqaYWNUEccUI1U36n4LUhCZzUHDeXFT4DfbChgVx" + }, + "kid": "UIFrQul50aGcwaugYz50xcza4YZ6VOH3BBDypCL3454", + "wrappedByNode": "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImtpZCI6IlVJRnJRdWw1MGFHY3dhdWdZejUweGN6YTRZWjZWT0gzQkJEeXBDTDM0NTQiLCJjdHgiOiJoYi1zZWNyZXQtdjE6dGVhbV9maXh0dXJlOjZmMWQzYzFlLTViOGEtNGU2Zi05YTUxLTBjMmI3ZjNkOWUxMCIsImVwayI6eyJjcnYiOiJQLTUyMSIsImt0eSI6IkVDIiwieCI6IkFHYUpCZi04MC1MaWp6UDdvYWl6eUpZaVEwb0VaWlhyQ19JeFBjRG5LTGo2QVFJekRTWFNyb0wzamJlVS1sOEd5bElMX3RGUmU0QmxnTDZJYlhOZFdvN2UiLCJ5IjoiQUFHcC1obFhmY1o0MXpvU2dKaDIxcXBmVUN4SU5qYmE5eWVtU2VxZmVEQ2tjeHpHUXM5V0YtbEJ4QlphX0xkQUhtLXVaZDdUWG5zOHBzOUU2TzkxNVp3RCJ9fQ..BXEgBGzV9uKnB8X2.OfKKiTQLgVqIQ4v40R__Tz0Yk-wb7EOWG7OOg4Z88zWrWwAfi_YMktn24tJ-Eg5WD64x9fx9rUCwcX8o0t0SzuIbLEW8bGVVVlr5niPsZoaCYDLpQ156litd3r0Hf2gnFoQdeOPcww._1vT9N9rkXxKYjmxcn8dmw", + "wrappedByPython": "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImtpZCI6IlVJRnJRdWw1MGFHY3dhdWdZejUweGN6YTRZWjZWT0gzQkJEeXBDTDM0NTQiLCJjdHgiOiJoYi1zZWNyZXQtdjE6dGVhbV9maXh0dXJlOjZmMWQzYzFlLTViOGEtNGU2Zi05YTUxLTBjMmI3ZjNkOWUxMCIsImVwayI6eyJjcnYiOiJQLTUyMSIsImt0eSI6IkVDIiwieCI6IkFOZlBCUHRUUmo5RW5jNmdXUVc4SGZDQmFvRnZqNGVnVDhaVjRad0Nyc2pFVWc2c25LX2FYQTFkTXR4NTQ3MWoxQWU0ZWQwU1NaSlo3WmtwVGpQTjhxOHUiLCJ5IjoiQUZlMXZSTVhCWHRPSmVUTmpzR1RaN05tV0d2eWpvaVNsSHEyMTBJT0RLbGRWRThzUVBFWFJ3dmhLQmVvbEkxTi1qc3VlSmtVUXlheHgxVGFBODhBaG1rRyJ9fQ..JuMmlFpA1DyD_4_l.M0TbQp146nJRVIJQZ0sKqEsRpF4FYevWfYyS_Z2DTHsLs5GIsYEKJ4PUvYHBIHuJ1D7UrE4-otqYLGcQJW-uT_-OqSa6BIVlNAqBjTMnVVeUUBu3XV9xqDb68d7Xpj9MfrAw-zC7MA.fIF6VPqxhJCrA5MjPQ459w" + }, + { + "label": "x25519", + "algorithm": "ECDH-ES+A256KW", + "jwk": { + "crv": "X25519", + "d": "UIVv3o0M6-jv_pLf77pnaSR1HPXSMLe0k5UcYpukMVs", + "x": "cLzaeMuTZwtFbGJodc98KKvv7ShLfCB-yoav0HQaIQQ", + "kty": "OKP" + }, + "kid": "shputQF0o-yH6jz5npiZHcFvPB8oyC4fPBU8y8udGn8", + "wrappedByNode": "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiJzaHB1dFFGMG8teUg2ano1bnBpWkhjRnZQQjhveUM0ZlBCVTh5OHVkR244IiwiY3R4IjoiaGItc2VjcmV0LXYxOnRlYW1fZml4dHVyZTo2ZjFkM2MxZS01YjhhLTRlNmYtOWE1MS0wYzJiN2YzZDllMTAiLCJlcGsiOnsiY3J2IjoiWDI1NTE5Iiwia3R5IjoiT0tQIiwieCI6IkFma3g1VklfX2RicGdOY29feF9VTVVDMV8tUzVwU2NkRnJGZndZSlRCMWcifX0.VEcsB_DKjDKzudxxwyKNWpfGQmOnhmr8R22o-sIbQRV6U2AEXKd9aA.zeGhRuiZKphU5CmR.WpK2y2paHyLDYaHKdaI1k9KW4j4Wwc2TTRx9_bf1J0EKu7_u7QJhJeEWuAmIudZ05s2HIGAR6g48hgS56Qwxj-lYzjIlGqqzULeXw5mBp2yUyX99uFEFC_FUzpbKniSte66G3CD7ug.ta9TOCb_0A9SUVjKzCufLA", + "wrappedByPython": "eyJhbGciOiJFQ0RILUVTK0EyNTZLVyIsImVuYyI6IkEyNTZHQ00iLCJraWQiOiJzaHB1dFFGMG8teUg2ano1bnBpWkhjRnZQQjhveUM0ZlBCVTh5OHVkR244IiwiY3R4IjoiaGItc2VjcmV0LXYxOnRlYW1fZml4dHVyZTo2ZjFkM2MxZS01YjhhLTRlNmYtOWE1MS0wYzJiN2YzZDllMTAiLCJlcGsiOnsiY3J2IjoiWDI1NTE5Iiwia3R5IjoiT0tQIiwieCI6IkFsZFlhdGJHU1ZVTXlEdHpiLVlvamRvMUZ1Mk90c09fQXQ4QkRoWUpTQkEifX0.evwJ-ewF8MS_PVouBBDMi10iHyi-Tg60z7O5kZPK47nbGzo1EWTblA.Mj3l-XzynRSue44w.4kZc9WY0vX8hACPwvVQvq0bFfQ9lxuNvE8Z366Z0r9IOPaFGxxuPmIojZAFCJ4LKYkAIuiMtH2AfydsnguGbrq8kcEgLyrLrowsG9viqpFm6U3Q6UWGAVlpED6OFqGm9EF168iwjew.QJ0baAoToXU4pz7tJZ2BRg" + }, + { + "label": "x448", + "algorithm": "ECDH-ES", + "jwk": { + "crv": "X448", + "d": "GJ0gpEJEC-COQUPfcl6UAuVDDrdQaxSwL43RtDh49v4_c_a0hSCCgmXpUce83PQbj9q-axJajbw", + "x": "pCb-B4PIc_VaYouhZTnXuA8YkBMvbdgP0QJ_b_JtCO6IV_hVO_2q9l5GNfDJXTLx8550xkd3X0A", + "kty": "OKP" + }, + "kid": "lxvyEWaOabx7FJbA5vbCwhvLMARQUlf8fq0lDCIkw7w", + "wrappedByNode": "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImtpZCI6Imx4dnlFV2FPYWJ4N0ZKYkE1dmJDd2h2TE1BUlFVbGY4ZnEwbERDSWt3N3ciLCJjdHgiOiJoYi1zZWNyZXQtdjE6dGVhbV9maXh0dXJlOjZmMWQzYzFlLTViOGEtNGU2Zi05YTUxLTBjMmI3ZjNkOWUxMCIsImVwayI6eyJjcnYiOiJYNDQ4Iiwia3R5IjoiT0tQIiwieCI6IktPT0lXS2tSQzVuQ1hXcWZ2Qzc3UzVhODRhaTB4Q1JibkZfVTI0WnZ6VWFmX3JIM2RDRHAwRUk5VXNvQ1lhWDl3M0w0alhvVUtCZyJ9fQ..SLdO9ul1cGuZ5CLx.TN3Hp5fEf4L33_blTzP8PUnf4ABBoFXPw-IThcA5fzUVTsNEfIjfIjbonNejuEPOBtkbrfs06oN1xljqoBllmV6bMsgQ4uFSMtMmLET49xz5h-PB-hkqzOKP-tSt2iy7sytGyVGqaQ.YmyQ3TgrHcCGRdOufvdbpg", + "wrappedByPython": "eyJhbGciOiJFQ0RILUVTIiwiZW5jIjoiQTI1NkdDTSIsImtpZCI6Imx4dnlFV2FPYWJ4N0ZKYkE1dmJDd2h2TE1BUlFVbGY4ZnEwbERDSWt3N3ciLCJjdHgiOiJoYi1zZWNyZXQtdjE6dGVhbV9maXh0dXJlOjZmMWQzYzFlLTViOGEtNGU2Zi05YTUxLTBjMmI3ZjNkOWUxMCIsImVwayI6eyJjcnYiOiJYNDQ4Iiwia3R5IjoiT0tQIiwieCI6ImRELXAtdDl0S0JQRC1aVkcwRlRVTEFXcjAxbU5PNnNQOWhYdE00MWVweVRycTZweEVLY0J3MjBkLW5Ha3kxdFBPbWxwV1NiVGV5NCJ9fQ..kWMdqtLyWFgWwsph.xdQOXYPg1zODw0BVVzQCNhxDBBdvjrK3LzJabgIuzUVTIJV_xMzI3ua-E65XZpNfElLmIqwaSldamDaI41TR_K8yT0BdtN_gR_fTyG2dJM29pohSK0sPZmuSMnAdpFopxQ8EdMcPMw.zI1rPy3AuMP0Uh-VHqsR0A" + } + ] +} diff --git a/tests/test_customer_secrets.py b/tests/test_customer_secrets.py new file mode 100644 index 00000000..f627deab --- /dev/null +++ b/tests/test_customer_secrets.py @@ -0,0 +1,718 @@ +"""Customer-protected secrets: customer keys, wrapped versions, unwrapping, +rewrapping, and passing unwrapped references to sandboxes and fills.""" + +import base64 +import hashlib +import json +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec, ed25519, rsa, x448, x25519 + +from hyperbrowser import AsyncHyperbrowser, create_customer_key, secret_envelope_digest +from hyperbrowser.client.managers.sandboxes.shared import ( + _normalize_exec_params, + _secret_process_payload, +) +from hyperbrowser.client.managers.sync_manager.sandboxes.sandbox_processes import ( + SandboxProcessesApi, +) +from hyperbrowser.credentials_common import fill_credential_payload +from hyperbrowser.customer_key import CustomerKey +from hyperbrowser.exceptions import HyperbrowserError +from hyperbrowser.models import ( + CreateSandboxParams, + OnePasswordSource, + SecretDetail, + SecretReference, + SessionDetail, + VaultReference, + WrappedSecretVersion, +) +from hyperbrowser.secrets_common import SecretsSealer +from tests.test_credentials import SESSION, mock_clients, respond +from tests.test_secrets import ( + AGENT_PROCESS, + CONTEXT, + SECRET_ID, + RuntimeScript, + _open, + _public_key_payload, +) + +VAULT_ID = "3f1d2c4b-5a6e-4f70-8a9b-0c1d2e3f4a5b" +FIXTURE = json.loads( + (Path(__file__).parent / "fixtures" / "customer_key_interop.json").read_text() +) +UNWRAPPED = "eyJhbGciOiJSU0EtT0FFUC0yNTYifQ.key.iv.ciphertext.tag" + + +@pytest.fixture(scope="module") +def platform_key(): + return rsa.generate_private_key(public_exponent=65537, key_size=3072) + + +@pytest.fixture(scope="module") +def rsa_key(): + return create_customer_key(rsa.generate_private_key(65537, 2048)) + + +@pytest.fixture(scope="module") +def ec_key(): + return create_customer_key(ec.generate_private_key(ec.SECP256R1())) + + +@pytest.fixture(params=[False, True], ids=["sync", "async"]) +def sdk(request): + yield from mock_clients(request.param) + + +def _body(request): + return json.loads(request.content) + + +def _header(envelope): + segment = envelope.split(".")[0] + return json.loads(base64.urlsafe_b64decode(segment + "=" * (-len(segment) % 4))) + + +def _secret(protection="customer", **overrides): + return dict( + { + "id": SECRET_ID, + "name": "db-password", + "description": "", + "type": "secret", + "metadata": {}, + "protection": protection, + "encryptionContext": CONTEXT, + "latestVersion": None, + "createdAt": "2026-11-01T00:00:00Z", + "updatedAt": "2026-11-01T00:00:00Z", + }, + **overrides, + ) + + +def _stored(platform_key, key, value="hunter2", version=1): + """A stored customer-protected version: ``value`` sealed to the platform + and wrapped with ``key``.""" + sealer = SecretsSealer(_public_key_payload(platform_key)) + inner = sealer.seal(CONTEXT, value) + return inner, { + "version": version, + "kid": sealer.kid, + "retiresAt": None, + "outerKid": key.kid, + "innerDigest": secret_envelope_digest(inner), + "envelope": key.wrap(inner, CONTEXT), + } + + +# --- customer keys --- + + +@pytest.mark.parametrize( + "generate, algorithm, expected_alg", + [ + (lambda: rsa.generate_private_key(65537, 2048), None, "RSA-OAEP-256"), + (lambda: ec.generate_private_key(ec.SECP384R1()), None, "ECDH-ES+A256KW"), + (lambda: ec.generate_private_key(ec.SECP521R1()), "ECDH-ES", "ECDH-ES"), + (x25519.X25519PrivateKey.generate, None, "ECDH-ES+A256KW"), + (x448.X448PrivateKey.generate, "ECDH-ES", "ECDH-ES"), + ], + ids=["rsa", "p-384", "p-521", "x25519", "x448"], +) +def test_keys_wrap_to_the_secrets_context_and_unwrap(generate, algorithm, expected_alg): + key = create_customer_key(generate(), algorithm=algorithm) + assert isinstance(key, CustomerKey) + wrapped = key.wrap("a.b.c.d.e", CONTEXT) + header = _header(wrapped) + assert header["alg"] == expected_alg + assert (header["enc"], header["kid"], header["ctx"]) == ( + "A256GCM", + key.kid, + CONTEXT, + ) + assert set(header) == ( + {"alg", "enc", "kid", "ctx"} + if expected_alg == "RSA-OAEP-256" + else {"alg", "enc", "kid", "ctx", "epk"} + ) + if expected_alg == "ECDH-ES": + assert wrapped.split(".")[1] == "" + assert key.unwrap(wrapped) == "a.b.c.d.e" + + +def test_the_kid_is_the_rfc_7638_thumbprint_unless_named(): + private_key = ec.generate_private_key(ec.SECP256R1()) + numbers = private_key.public_key().public_numbers() + + def b64(value): + return base64.urlsafe_b64encode(value.to_bytes(32, "big")).rstrip(b"=").decode() + + members = '{"crv":"P-256","kty":"EC","x":"%s","y":"%s"}' % ( + b64(numbers.x), + b64(numbers.y), + ) + thumbprint = ( + base64.urlsafe_b64encode(hashlib.sha256(members.encode()).digest()) + .rstrip(b"=") + .decode() + ) + pem = private_key.public_key().public_bytes( + serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo + ) + assert create_customer_key(private_key).kid == thumbprint + assert create_customer_key(private_key.public_key()).kid == thumbprint + assert create_customer_key(pem).kid == thumbprint + assert create_customer_key(pem.decode()).kid == thumbprint + assert create_customer_key(private_key, kid="kms/key-1").kid == "kms/key-1" + jwk = {"kty": "EC", "crv": "P-256", "x": b64(numbers.x), "y": b64(numbers.y)} + assert create_customer_key(jwk).kid == thumbprint + assert create_customer_key(dict(jwk, kid="team-key")).kid == "team-key" + + +def test_public_keys_wrap_and_private_keys_unwrap(): + private_key = rsa.generate_private_key(65537, 2048) + der = private_key.private_bytes( + serialization.Encoding.DER, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + public_only = create_customer_key(private_key.public_key()) + from_der = create_customer_key(der) + assert from_der.can_unwrap and not public_only.can_unwrap + wrapped = public_only.wrap("a.b.c.d.e", CONTEXT) + assert from_der.unwrap(wrapped) == "a.b.c.d.e" + with pytest.raises(HyperbrowserError) as error: + public_only.unwrap(wrapped) + assert error.value.code == "customer_key_private_key_required" + + +@pytest.mark.parametrize( + "key, options, message", + [ + (lambda: rsa.generate_private_key(65537, 1024), {}, "at least 2048 bits"), + (lambda: ec.generate_private_key(ec.SECP256K1()), {}, "P-256, P-384 or P-521"), + (ed25519.Ed25519PrivateKey.generate, {}, "must be RSA"), + (lambda: "not a key", {}, "not a PEM or DER key"), + (lambda: {"kty": "oct", "k": "AAAA"}, {}, "must be RSA"), + ( + lambda: rsa.generate_private_key(65537, 2048), + {"algorithm": "ECDH-ES"}, + "RSA-OAEP-256", + ), + ( + x25519.X25519PrivateKey.generate, + {"algorithm": "RSA-OAEP-256"}, + "ECDH-ES", + ), + (x25519.X25519PrivateKey.generate, {"kid": "caf\u00e9"}, "printable ASCII"), + (x25519.X25519PrivateKey.generate, {"kid": "x" * 257}, "1-256"), + ], +) +def test_keys_the_api_would_refuse_are_rejected(key, options, message): + with pytest.raises(HyperbrowserError, match=message) as error: + create_customer_key(key(), **options) + assert error.value.code == "invalid_customer_key" + + +def test_unwrap_names_a_key_mismatch_and_refuses_tampering(rsa_key, ec_key): + wrapped = rsa_key.wrap("a.b.c.d.e", CONTEXT) + with pytest.raises(HyperbrowserError) as error: + ec_key.unwrap(wrapped) + assert error.value.code == "customer_key_mismatch" + + segments = wrapped.split(".") + tag = bytearray(base64.urlsafe_b64decode(segments[4] + "==")) + tag[0] ^= 1 + segments[4] = base64.urlsafe_b64encode(bytes(tag)).rstrip(b"=").decode() + with pytest.raises(HyperbrowserError) as error: + rsa_key.unwrap(".".join(segments)) + assert error.value.code == "customer_key_unwrap_failed" + with pytest.raises(HyperbrowserError, match="five segments"): + rsa_key.unwrap("a.b.c") + + +@pytest.mark.parametrize("item", FIXTURE["keys"], ids=lambda item: item["label"]) +def test_envelopes_wrapped_by_either_sdk_unwrap(item): + key = create_customer_key(item["jwk"], algorithm=item["algorithm"]) + assert key.kid == item["kid"] + for wrapped in (item["wrappedByNode"], item["wrappedByPython"]): + assert _header(wrapped)["ctx"] == FIXTURE["context"] + assert key.unwrap(wrapped) == FIXTURE["inner"] + assert secret_envelope_digest(FIXTURE["inner"]) == FIXTURE["innerDigest"] + + +# --- secrets --- + + +def test_create_wraps_the_first_value_with_the_customer_key(sdk, platform_key, rsa_key): + client, call, calls, outcomes = sdk + respond(outcomes, _public_key_payload(platform_key)) + respond(outcomes, _secret(), 201) + respond(outcomes, {"version": 1, "kid": "p", "outerKid": rsa_key.kid}, 201) + + created = call( + client.secrets.create, + {"name": "db-password", "value": "hunter2", "customer_key": rsa_key}, + ) + + assert created.protection == "customer" and created.latest_version == 1 + assert [(c.method, c.url.path) for c in calls] == [ + ("GET", "/api/secrets/public-key"), + ("POST", "/api/secrets"), + ("POST", f"/api/secrets/{SECRET_ID}/versions"), + ] + assert _body(calls[1]) == {"name": "db-password", "protection": "customer"} + upload = _body(calls[2]) + assert set(upload) == {"envelope", "innerDigest", "innerKid"} + assert _header(upload["envelope"])["ctx"] == CONTEXT + inner = rsa_key.unwrap(upload["envelope"]) + assert secret_envelope_digest(inner) == upload["innerDigest"] + header, value = _open(platform_key, inner) + assert (header["kid"], value) == (upload["innerKid"], b"hunter2") + + +def test_create_checks_protection_before_any_request(sdk, rsa_key): + client, call, calls, outcomes = sdk + respond(outcomes, _secret(), 201) + call(client.secrets.create, {"name": "db-password", "protection": "customer"}) + assert _body(calls[0]) == {"name": "db-password", "protection": "customer"} + + for params in [ + {"name": "db-password", "protection": "customer", "value": "v"}, + {"name": "db-password", "protection": "platform", "customer_key": rsa_key}, + {"name": "db-password", "customer_key": object()}, + ]: + with pytest.raises(HyperbrowserError) as error: + call(client.secrets.create, params) + assert error.value.code == "invalid_request" + assert len(calls) == 1 + + +def test_add_version_wraps_and_matches_the_secrets_protection( + sdk, platform_key, ec_key +): + client, call, calls, outcomes = sdk + respond(outcomes, dict(_secret(), versions=[])) + respond(outcomes, _public_key_payload(platform_key)) + respond(outcomes, {"version": 2, "kid": "p", "outerKid": ec_key.kid}, 201) + version = call(client.secrets.add_version, SECRET_ID, "v2", customer_key=ec_key) + assert version.outer_kid == ec_key.kid + upload = _body(calls[-1]) + assert _open(platform_key, ec_key.unwrap(upload["envelope"]))[1] == b"v2" + + respond(outcomes, dict(_secret(), versions=[])) + with pytest.raises(HyperbrowserError, match="pass customer_key"): + call(client.secrets.add_version, SECRET_ID, "v3") + respond(outcomes, dict(_secret("platform"), versions=[])) + with pytest.raises(HyperbrowserError, match="omit customer_key"): + call(client.secrets.add_version, SECRET_ID, "v3", customer_key=ec_key) + assert [c.method for c in calls].count("POST") == 1 + + +def test_unwrap_returns_a_pinned_reference_checked_against_the_digest( + sdk, platform_key, rsa_key, ec_key +): + client, call, calls, outcomes = sdk + inner, stored = _stored(platform_key, rsa_key, version=4) + respond(outcomes, dict(_secret(latestVersion=4), versions=[])) + respond(outcomes, stored) + + reference = call(client.secrets.unwrap, SECRET_ID, [ec_key, rsa_key]) + + assert isinstance(reference, SecretReference) + assert (reference.name, reference.version, reference.unwrapped) == ( + "db-password", + 4, + inner, + ) + assert "unwrapped" not in repr(reference) + assert calls[1].url.path == f"/api/secrets/{SECRET_ID}/versions/latest/wrapped" + + respond(outcomes, dict(_secret(), versions=[])) + respond(outcomes, stored) + call(client.secrets.unwrap, SECRET_ID, rsa_key, version=4) + assert calls[-1].url.path == f"/api/secrets/{SECRET_ID}/versions/4/wrapped" + + respond(outcomes, dict(_secret(), versions=[])) + respond(outcomes, stored) + with pytest.raises(HyperbrowserError) as error: + call(client.secrets.unwrap, SECRET_ID, ec_key) + assert error.value.code == "customer_key_mismatch" + + respond(outcomes, dict(_secret(), versions=[])) + respond(outcomes, dict(stored, innerDigest=secret_envelope_digest("other"))) + with pytest.raises(HyperbrowserError, match="doesn't match its innerDigest"): + call(client.secrets.unwrap, SECRET_ID, rsa_key) + + count = len(calls) + with pytest.raises(HyperbrowserError, match="at least one customer key"): + call(client.secrets.unwrap, SECRET_ID, []) + with pytest.raises(HyperbrowserError, match="Invalid secret version"): + call(client.secrets.unwrap, SECRET_ID, rsa_key, version=0) + assert len(calls) == count + + +def test_get_wrapped_version_returns_the_outer_envelope(sdk, platform_key, rsa_key): + client, call, calls, outcomes = sdk + _, stored = _stored(platform_key, rsa_key, version=2) + respond(outcomes, dict(_secret(), versions=[])) + respond(outcomes, stored) + wrapped = call(client.secrets.get_wrapped_version, SECRET_ID, 2) + assert isinstance(wrapped, WrappedSecretVersion) + assert (wrapped.outer_kid, wrapped.inner_digest) == ( + rsa_key.kid, + stored["innerDigest"], + ) + assert calls[-1].url.path == f"/api/secrets/{SECRET_ID}/versions/2/wrapped" + + +def test_rewrap_moves_versions_to_the_new_key_and_keeps_the_inner_envelope( + sdk, platform_key, rsa_key, ec_key +): + client, call, calls, outcomes = sdk + inner_2, v2 = _stored(platform_key, rsa_key, "two", 2) + inner_1, v1 = _stored(platform_key, rsa_key, "one", 1) + _, v3 = _stored(platform_key, ec_key, "three", 3) + versions = [ + {key: item[key] for key in ("version", "kid", "outerKid")} + for item in (v3, v2, v1) + ] + respond(outcomes, dict(_secret(latestVersion=3), versions=versions)) + respond(outcomes, v2) + respond(outcomes, dict(v2, outerKid=ec_key.kid)) + respond(outcomes, v1) + respond(outcomes, dict(v1, outerKid=ec_key.kid)) + + rewrapped = call(client.secrets.rewrap, SECRET_ID, from_key=rsa_key, to_key=ec_key) + + assert [(c.method, c.url.path) for c in calls[1:]] == [ + ("GET", f"/api/secrets/{SECRET_ID}/versions/2/wrapped"), + ("PUT", f"/api/secrets/{SECRET_ID}/versions/2/wrapping"), + ("GET", f"/api/secrets/{SECRET_ID}/versions/1/wrapped"), + ("PUT", f"/api/secrets/{SECRET_ID}/versions/1/wrapping"), + ] + assert [(item.version, item.outer_kid) for item in rewrapped] == [ + (2, ec_key.kid), + (1, ec_key.kid), + ] + for request, inner, stored in ((calls[2], inner_2, v2), (calls[4], inner_1, v1)): + body = _body(request) + assert body["innerDigest"] == stored["innerDigest"] + assert _header(body["envelope"])["kid"] == ec_key.kid + assert ec_key.unwrap(body["envelope"]) == inner + + +def test_rewrap_refuses_platform_secrets_and_replace_wrapping_sends_as_given( + sdk, rsa_key, ec_key +): + client, call, calls, outcomes = sdk + respond(outcomes, dict(_secret("platform"), versions=[])) + with pytest.raises(HyperbrowserError, match="not customer-protected"): + call(client.secrets.rewrap, SECRET_ID, from_key=rsa_key, to_key=ec_key) + + respond(outcomes, dict(_secret(), versions=[])) + respond( + outcomes, + { + "version": 5, + "kid": "p", + "outerKid": "k", + "innerDigest": "d", + "envelope": "e", + }, + ) + call( + client.secrets.replace_version_wrapping, + SECRET_ID, + 5, + {"envelope": "outer", "inner_digest": "digest"}, + ) + assert calls[-1].method == "PUT" + assert _body(calls[-1]) == {"envelope": "outer", "innerDigest": "digest"} + + +def test_versions_report_outer_kid_and_retires_at(): + detail = SecretDetail.model_validate( + dict( + _secret(), + versions=[ + { + "version": 2, + "kid": "p", + "outerKid": "k", + "retiresAt": "2027-01-01T00:00:00Z", + } + ], + ) + ) + assert detail.versions[0].outer_kid == "k" + assert detail.versions[0].retires_at is not None + assert SecretDetail.model_validate(dict(_secret(), protection=None)).protection == ( + "platform" + ) + + +def test_the_async_client_awaits_customer_keys_and_the_sync_one_refuses_them( + platform_key, rsa_key +): + class KmsKey: + kid = rsa_key.kid + + async def wrap(self, inner_envelope, encryption_context): + return rsa_key.wrap(inner_envelope, encryption_context) + + async def unwrap(self, wrapped_envelope): + return rsa_key.unwrap(wrapped_envelope) + + inner, stored = _stored(platform_key, rsa_key, version=3) + for is_async in (True, False): + clients = mock_clients(is_async) + client, call, _, outcomes = next(clients) + respond(outcomes, dict(_secret(), versions=[])) + respond(outcomes, stored) + if is_async: + assert isinstance(client, AsyncHyperbrowser) + assert call(client.secrets.unwrap, SECRET_ID, KmsKey()).unwrapped == inner + else: + with pytest.raises(HyperbrowserError, match="use the async client"): + call(client.secrets.unwrap, SECRET_ID, KmsKey()) + clients.close() + + +# --- vaults --- + + +def _vault(): + return { + "id": VAULT_ID, + "name": "app-env", + "description": "", + "entries": { + "DB_PASSWORD": { + "name": "db-password", + "secretId": SECRET_ID, + "version": None, + "protection": "customer", + }, + }, + "createdAt": "2026-11-01T00:00:00Z", + "updatedAt": "2026-11-01T00:00:00Z", + } + + +def test_vault_unwrap_returns_the_reference_sandboxes_take( + sdk, platform_key, rsa_key, ec_key +): + client, call, calls, outcomes = sdk + inner, stored = _stored(platform_key, ec_key, version=7) + wrapped_vault = { + "id": VAULT_ID, + "name": "app-env", + "entries": { + "DB_PASSWORD": dict(stored, name="db-password", secretId=SECRET_ID) + }, + } + respond(outcomes, _vault()) + respond(outcomes, wrapped_vault) + + reference = call(client.vaults.unwrap, VAULT_ID, [rsa_key, ec_key]) + + assert isinstance(reference, VaultReference) + assert reference.model_dump() == { + "name": "app-env", + "unwrapped": {"DB_PASSWORD": {"version": 7, "unwrapped": inner}}, + } + assert [c.url.path for c in calls] == [ + f"/api/vaults/{VAULT_ID}", + f"/api/vaults/{VAULT_ID}/wrapped", + ] + + respond(outcomes, _vault()) + respond(outcomes, wrapped_vault) + with pytest.raises( + HyperbrowserError, match="Entry DB_PASSWORD of vault app-env" + ) as error: + call(client.vaults.unwrap, VAULT_ID, rsa_key) + assert error.value.code == "customer_key_mismatch" + + +def test_vault_entries_report_their_protection(sdk): + client, call, calls, outcomes = sdk + respond(outcomes, _vault()) + vault = call(client.vaults.get, VAULT_ID) + assert vault.entries["DB_PASSWORD"].protection == "customer" + + +# --- uses --- + + +def test_unwrapped_references_must_pin_a_version(): + assert SecretReference(name="db", version=3, unwrapped=UNWRAPPED).version == 3 + for params in [ + {"name": "db", "unwrapped": UNWRAPPED}, + {"name": "db", "version": "latest", "unwrapped": UNWRAPPED}, + {"name": "db", "version": 1, "unwrapped": ""}, + {"name": "db", "version": 1, "unwrapped": "x" * (64 * 1024 + 1)}, + ]: + with pytest.raises(ValueError): + SecretReference.model_validate(params) + + +def test_sandbox_create_sends_unwrapped_references(): + params = CreateSandboxParams( + image_name="node", + secrets={ + "API_KEY": {"name": "provider-key", "version": 4, "unwrapped": UNWRAPPED} + }, + vault={ + "name": "app-env", + "unwrapped": {"DB": {"version": 7, "unwrapped": UNWRAPPED}}, + }, + one_password={ + "token": {"name": "op-token", "version": 2, "unwrapped": UNWRAPPED}, + "vault": "Engineering", + "fields": {"DB_PASS": {"item": "Postgres", "field": "password"}}, + }, + ) + assert params.model_dump(by_alias=True, exclude_none=True) == { + "imageName": "node", + "secrets": { + "API_KEY": {"name": "provider-key", "version": 4, "unwrapped": UNWRAPPED} + }, + "vault": { + "name": "app-env", + "unwrapped": {"DB": {"version": 7, "unwrapped": UNWRAPPED}}, + }, + "onePassword": { + "token": {"name": "op-token", "version": 2, "unwrapped": UNWRAPPED}, + "vault": "Engineering", + "fields": {"DB_PASS": {"item": "Postgres", "field": "password"}}, + }, + } + + +@pytest.mark.parametrize( + "vault, message", + [ + ({"name": "app env", "unwrapped": {}}, "Invalid secret name"), + ({"name": "app-env"}, "unwrapped"), + ( + {"name": "app-env", "unwrapped": {"1A": {"version": 1, "unwrapped": "e"}}}, + "1A", + ), + ( + { + "name": "app-env", + "unwrapped": {"A": {"version": "latest", "unwrapped": "e"}}, + }, + "version", + ), + ({"name": "app-env", "unwrapped": {"A": {"version": 1}}}, "unwrapped"), + ( + { + "name": "app-env", + "unwrapped": {"A": {"version": 1, "unwrapped": "e", "x": 1}}, + }, + "x", + ), + ( + { + "name": "app-env", + "unwrapped": { + f"E{i}": {"version": 1, "unwrapped": "e"} for i in range(33) + }, + }, + "At most 32", + ), + ], +) +def test_bad_vault_references_are_refused_locally(vault, message): + with pytest.raises(ValueError, match=message): + CreateSandboxParams(image_name="node", vault=vault) + + +def test_processes_send_vault_references_and_unwrapped_tokens(): + reference = VaultReference( + name="app-env", unwrapped={"DB": {"version": 7, "unwrapped": UNWRAPPED}} + ) + token = SecretReference(name="op-token", version=2, unwrapped=UNWRAPPED) + payload = _secret_process_payload( + _normalize_exec_params( + "node app.js", + vault=reference, + one_password=OnePasswordSource(token=token, vault="Eng", fields={}), + ) + ) + assert payload == { + "command": "node app.js", + "vault": { + "name": "app-env", + "unwrapped": {"DB": {"version": 7, "unwrapped": UNWRAPPED}}, + }, + "onePassword": { + "token": {"name": "op-token", "version": 2, "unwrapped": UNWRAPPED}, + "vault": "Eng", + "fields": {}, + }, + } + + starts = [] + + def start(body): + starts.append(body) + return {"process": AGENT_PROCESS, "secrets": []} + + api = SandboxProcessesApi(RuntimeScript(), start, "sbx_123") + api.start( + "node app.js", + secrets={"API_KEY": {"name": "k", "version": 1, "unwrapped": UNWRAPPED}}, + vault={"name": "app-env", "unwrapped": {}}, + ) + assert starts[-1] == { + "command": "node app.js", + "secrets": {"API_KEY": {"name": "k", "version": 1, "unwrapped": UNWRAPPED}}, + "vault": {"name": "app-env", "unwrapped": {}}, + } + + +def test_fills_send_an_unwrapped_op_token(): + body = fill_credential_payload( + { + "one_password": { + "token": {"name": "op-token", "version": 2, "unwrapped": UNWRAPPED}, + "vault": "Eng", + "allowed_origins": ["https://example.com"], + }, + "fields": [{"selector": "#p", "ref": {"item": "i", "field": "f"}}], + } + ) + assert body["onePassword"]["token"] == { + "name": "op-token", + "version": 2, + "unwrapped": UNWRAPPED, + } + with pytest.raises(HyperbrowserError, match="Pin the version"): + fill_credential_payload( + { + "one_password": { + "token": {"name": "op-token", "unwrapped": UNWRAPPED}, + "vault": "Eng", + "allowed_origins": ["https://example.com"], + }, + "fields": [{"selector": "#p", "ref": {"item": "i", "field": "f"}}], + } + ) + + +def test_sessions_list_the_vaults_attached_by_reference(sdk): + client, call, calls, outcomes = sdk + vaults = [{"id": VAULT_ID, "name": "app-env"}] + respond(outcomes, dict(SESSION, vaults=vaults)) + session = call(client.sessions.create, {"credentials": [{"vault": "app-env"}]}) + assert isinstance(session, SessionDetail) + assert [(v.id, v.name) for v in session.vaults or []] == [(VAULT_ID, "app-env")] diff --git a/tests/typecheck/invalid_requests.py b/tests/typecheck/invalid_requests.py index b103780a..fc6aa7aa 100644 --- a/tests/typecheck/invalid_requests.py +++ b/tests/typecheck/invalid_requests.py @@ -146,3 +146,15 @@ async def invalid_async_credential_requests(client: AsyncHyperbrowser) -> None: await client.vaults.create({"entries": {}}) # M,P sandbox = await client.sandboxes.get("s") await sandbox.exec("x", one_password={"token": "t", "vault": "v", "fields": {"A": {"item": "i"}}}) # M,P + + +def invalid_customer_protected_requests(client: Hyperbrowser) -> None: + client.secrets.create({"name": "g", "protection": "vendor"}) # M,P + client.secrets.create({"name": "g", "customer_key": "pem"}) # M,P + client.secrets.unwrap("g", "not a key") # M,P + client.secrets.unwrap("g", [], version="newest") # M,P + client.secrets.replace_version_wrapping("g", 1, {"envelope": "e"}) # M,P + client.sandboxes.create({"image_name": "node", "vault": {"name": "v"}}) # M,P + sandbox = client.sandboxes.get("s") + sandbox.exec("x", vault={"name": "v", "unwrapped": {"A": {"version": 1}}}) # M,P + sandbox.exec("x", secrets={"A": {"name": "a", "unwrapped": 1}}) # M,P diff --git a/tests/typecheck/valid_requests.py b/tests/typecheck/valid_requests.py index 3bb213f3..702209ab 100644 --- a/tests/typecheck/valid_requests.py +++ b/tests/typecheck/valid_requests.py @@ -833,3 +833,99 @@ async def valid_async_credential_requests(client: AsyncHyperbrowser) -> None: client, session.id, {"credential": "x"} ) print(text) + + +class KmsCustomerKey: + kid = "kms/customer-key-1" + + async def wrap(self, inner_envelope: str, encryption_context: str) -> str: + return inner_envelope + + async def unwrap(self, wrapped_envelope: str) -> str: + return wrapped_envelope + + +def valid_customer_protected_requests(client: Hyperbrowser) -> None: + from hyperbrowser import create_customer_key + from hyperbrowser.models import ( + OnePasswordSource, + ReplaceSecretVersionWrappingParams, + VaultReference, + VaultUnwrappedEntry, + WrappedSecretVersion, + WrappedVault, + ) + + key = create_customer_key("-----BEGIN PRIVATE KEY-----", kid="team-key") + can_unwrap: bool = key.can_unwrap + client.secrets.create({"name": "db-pass", "value": "pw", "customer_key": key}) + client.secrets.create( + {"name": "db-pass", "protection": "customer" if can_unwrap else "platform"} + ) + client.secrets.create( + LegacyCreateSecretParams(name="db-pass", value="pw", customer_key=key) + ) + client.secrets.add_version("db-pass", "pw2", customer_key=key) + wrapped: WrappedSecretVersion = client.secrets.get_wrapped_version("db-pass", 2) + outer_kid: str = wrapped.outer_kid + db_pass = client.secrets.unwrap( + "db-pass", [key] if outer_kid == key.kid else [], version=wrapped.version + ) + client.secrets.rewrap("db-pass", from_key=[key], to_key=key, versions=[1, 2]) + client.secrets.replace_version_wrapping( + "db-pass", 1, {"envelope": "e", "inner_digest": "d"} + ) + client.secrets.replace_version_wrapping( + "db-pass", 1, ReplaceSecretVersionWrappingParams(envelope="e", inner_digest="d") + ) + vault_envelopes: WrappedVault = client.vaults.get_wrapped("app-env") + app_env = client.vaults.unwrap(vault_envelopes.name, key) + client.sandboxes.create( + { + "image_name": "node", + "secrets": {"A": {"name": "a", "version": 1, "unwrapped": "e"}}, + "vault": { + "name": "app-env", + "unwrapped": {"B": {"version": 2, "unwrapped": "e"}}, + }, + "one_password": { + "token": {"name": "op-token", "version": 1, "unwrapped": "e"}, + "vault": "Engineering", + "fields": {"C": {"item": "i", "field": "f"}}, + }, + } + ) + sandbox = client.sandboxes.get("sandbox_123") + sandbox.exec("node app.js", secrets={"DB_PASS": db_pass}, vault=app_env) + sandbox.exec( + "node app.js", + vault=VaultReference( + name="app-env", + unwrapped={"B": VaultUnwrappedEntry(version=2, unwrapped="e")}, + ), + one_password=OnePasswordSource(token=db_pass, vault="v", fields={}), + ) + client.sessions.credentials.fill( + "session_123", + { + "one_password": { + "token": {"name": "op-token", "version": 1, "unwrapped": "e"}, + "vault": "v", + "allowed_origins": ["https://example.com"], + }, + "fields": [{"selector": "#p", "ref": {"item": "i", "field": "f"}}], + }, + ) + session = client.sessions.get("session_123") + vault_names = [vault.name for vault in session.vaults or []] + client.sessions.create({"credentials": [{"vault": name} for name in vault_names]}) + + +async def valid_async_customer_protected_requests(client: AsyncHyperbrowser) -> None: + kms = KmsCustomerKey() + await client.secrets.create({"name": "db-pass", "value": "pw", "customer_key": kms}) + reference = await client.secrets.unwrap("db-pass", kms) + await client.vaults.unwrap("app-env", [kms]) + await client.secrets.rewrap("db-pass", from_key=kms, to_key=kms) + sandbox = await client.sandboxes.get("sandbox_123") + await sandbox.processes.start("node app.js", secrets={"DB_PASS": reference}) From 8f380b61384f6b4acdbe6c4da3ab93b9216fab1d Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Mon, 9 Nov 2026 19:53:19 +0000 Subject: [PATCH 4/4] Document customer-protected secrets and bump to 1.15.0 Co-authored-by: Ninad Sinha --- README.md | 112 +++++++++++++++++++++++++++++++++++++++++++++++-- pyproject.toml | 2 +- 2 files changed, 109 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 5b5b730f..078a24cf 100644 --- a/README.md +++ b/README.md @@ -239,7 +239,9 @@ Things to know: - Attaching secrets needs an API key with `secrets.use`; filling also needs `browser.sessions.update`. The team needs the secrets feature. Sessions with credentials run as Firecracker browsers with Chrome's password manager off. - A vault attaches the secrets its entries hold when the session is created. + A vault is attached by reference, so each fill uses the secrets its entries + name at that moment; `session.vaults` lists the attached vaults as `id` and + `name`. - Fills are recorded in the session's event log as `credential_filled` and `credential_fill_refused`. Their metadata names the `credential` or `vault`; for 1Password fills, `onePasswordToken` (the op_token's name) and its @@ -253,9 +255,12 @@ Things to know: (409) is the same for frames. - `CREDENTIAL_ORIGIN_NOT_ALLOWED` (403): the page's origin (in `details`) isn't allowed; nothing was typed. - - `CREDENTIAL_NOT_ATTACHED` (403): the secret (or a 1Password fill's - op_token) wasn't attached when the session was created, or a vault entry - now points at another secret. + - `CREDENTIAL_NOT_ATTACHED` (403): the secret, vault or 1Password fill's + op_token wasn't attached to the session, directly or as an entry of an + attached vault. + - `SECRET_REQUIRES_CUSTOMER_UNWRAP` (400): a customer-protected secret + can't be typed into a page (see + [Customer-protected secrets](#customer-protected-secrets)). - `CREDENTIAL_NOT_READY` (409): the secret has no allowed origins or no value. - `SECRET_TYPE_MISMATCH` (409): an `op_token` can't be attached or filled @@ -828,6 +833,105 @@ Things to know: `SECRET_ONEPASSWORD_FAILED` (502/503) are retryable. - `retryable` is the API's flag when it sends one. +### Customer-protected secrets + +A secret created with `protection="customer"` is also wrapped with your own +key, so the platform stores nothing it can open alone. Each version is sealed +to the platform key as usual, then wrapped locally with your key. To use one, +unwrap it locally and pass the result. Only the platform can open the +unwrapped envelope, and it checks that the envelope belongs to the version +you pinned. + +```python +import os + +from hyperbrowser import Hyperbrowser, create_customer_key + +client = Hyperbrowser() + +# RSA (2048 bits or more), EC P-256/P-384/P-521, X25519 or X448: a +# cryptography key object, PEM/DER or a JWK dict. A public key can wrap; +# unwrapping needs the private key. +customer_key = create_customer_key(os.environ["HB_CUSTOMER_KEY_PEM"]) + +client.secrets.create({"name": "db-pass", "value": "hunter2", "customer_key": customer_key}) +client.secrets.add_version("db-pass", "hunter3", customer_key=customer_key) + +# A reference pinned to the version unwrapped: name, version and unwrapped. +db_pass = client.secrets.unwrap("db-pass", customer_key) +sandbox = client.sandboxes.create({"image_name": "my-image", "secrets": {"DB_PASS": db_pass}}) +sandbox.exec("python migrate.py", secrets={"DB_PASS": db_pass}) + +# A vault's customer-protected entries, unwrapped together. Its other entries +# are delivered as usual. +app_env = client.vaults.unwrap("app-env", customer_key) +sandbox.processes.start("python worker.py", vault=app_env) + +# A customer-protected op_token, for sandboxes and 1Password fills. +token = client.secrets.unwrap("op-token", customer_key) +sandbox.exec( + "python app.py", + one_password={ + "token": token, + "vault": "Engineering", + "fields": {"DB_PASS": {"item": "Postgres", "field": "password"}}, + }, +) +``` + +- `protection` is `"platform"` (the default) or `"customer"`, and is fixed when + the secret is created. Passing `customer_key` to `create` implies + `"customer"`. Creating one without a value gives an empty secret; add its + first version with `add_version(secret, value, customer_key=...)`. +- The key's `kid` is its RFC 7638 thumbprint unless the JWK has a `kid` or you + pass `create_customer_key(key, kid=...)`. RSA keys wrap with `RSA-OAEP-256`. + EC and OKP keys default to `ECDH-ES+A256KW`; pass `algorithm="ECDH-ES"` for + direct key agreement. To keep the private key in a KMS or HSM, implement the + `CustomerKey` protocol yourself: `kid`, `wrap(inner_envelope, + encryption_context)` and `unwrap(wrapped_envelope)` produce and open a + compact JWE with protected header `{"alg", "enc": "A256GCM", "kid", "ctx"}`. + `ctx` must be the secret's `encryption_context`. With `AsyncHyperbrowser`, + either method may be a coroutine; the sync client refuses one. +- `unwrap(secret, keys, version=...)` unwraps the latest version by default. + `vaults.unwrap(vault, keys)` unwraps the versions the vault's entries + resolve to now. Both take a list of keys, such as during a rotation, and use + the one whose `kid` wrapped each version (`customer_key_mismatch` if none + did). The unwrapped envelope is checked against the version's + `inner_digest` locally, and again by the API. +- An unwrapped reference must pin a number, never `"latest"`. A vault + reference is refused with `SECRET_VAULT_CHANGED` when an entry was repointed + or moved to a newer version since it was unwrapped; unwrap it again. +- Customer-protected secrets can't be typed into browser pages, including as + vault entries in a fill (`SECRET_REQUIRES_CUSTOMER_UNWRAP`). A + customer-protected `op_token` can still sign 1Password fills: pass the + unwrapped reference as `one_password`'s `token`. +- Rotate your key with `rewrap(secret, from_key=..., to_key=...)`. It unwraps + each version still wrapped with another key and rewraps it with `to_key`, + all locally; the value and the version numbers don't change. It skips + versions already wrapped with `to_key`, so an interrupted rotation resumes + where it stopped. `get_wrapped_version` and `replace_version_wrapping` are + the single-version steps, for wrapping done elsewhere. +- Version details include `outer_kid`, the customer key that wrapped them, and + `retires_at`. A version whose platform key is retired is refused with + `SECRET_KEY_RETIRED`: add a new version. +- Fetching wrapped versions needs `secrets.use`, and rewrapping needs + `secrets.manage`. Signed-in users must be team owners or admins. +- Error codes from the API: + - `SECRET_REQUIRES_CUSTOMER_UNWRAP` (400): a customer-protected secret was + used without its unwrapped envelope, unwrapped with `"latest"` instead of a + pinned version, or used where it can't be (a fill). + - `SECRET_PROTECTION_MISMATCH` (400): an unwrapped envelope for a secret + that isn't customer-protected, or a version uploaded in the other + protection's form. + - `SECRET_DIGEST_MISMATCH` (409): the unwrapped envelope (or a rewrap's + `inner_digest`) doesn't match the version. + - `SECRET_VERSION_DUPLICATE` (409): another version already holds this + inner envelope; rewrap that version instead. + - `SECRET_VAULT_CHANGED` (409): a vault entry resolves to another secret or + version than the one unwrapped; unwrap the vault again. + - `SECRET_KEY_RETIRED` (409): the version was sealed to a retired platform + key; add a new version. + ### List sandboxes with filters ```python diff --git a/pyproject.toml b/pyproject.toml index 540fd11d..37ca417d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [tool.poetry] name = "hyperbrowser" -version = "1.14.1" +version = "1.15.0" description = "Python SDK for hyperbrowser" authors = ["Nikhil Shahi "] license = "MIT"