From 7ee1204cb4be4ce64d0db517ec1467f13b53932d Mon Sep 17 00:00:00 2001 From: Ronessa Acquesta Date: Mon, 12 Oct 2026 19:34:35 -0400 Subject: [PATCH 1/4] feat(secrets): route secrets collection updates through the partial-update endpoint [NMV-1073] Remove PUT from update_secrets_collection: metadata-only updates and full replacements both go through PATCH, so previously fetched (soon-to-be-masked) secret values are never resent. Full replacements are expressed as create/update/delete operations against the keys of the existing secrets. Add patch_secrets_collection and SecretOperation wrapping the new PATCH endpoint, --create/--update/--delete on `nextmv cloud secrets update`, and the cloud_update_secrets_collection MCP tool. Co-Authored-By: Claude (claude-opus-5-5[1m]) --- nextmv/nextmv/cli/cloud/secrets/update.py | 240 +++++++++++++++++--- nextmv/nextmv/cli/mcp/tools/secrets.py | 44 ++++ nextmv/nextmv/cloud/__init__.py | 2 + nextmv/nextmv/cloud/application/_secrets.py | 215 +++++++++++++++--- nextmv/nextmv/cloud/secrets.py | 120 ++++++++++ nextmv/tests/cli/test_mcp.py | 37 ++- nextmv/tests/cli/test_secrets.py | 104 +++++++++ nextmv/tests/cloud/test_secrets.py | 222 ++++++++++++++++++ 8 files changed, 917 insertions(+), 67 deletions(-) create mode 100644 nextmv/tests/cli/test_secrets.py create mode 100644 nextmv/tests/cloud/test_secrets.py diff --git a/nextmv/nextmv/cli/cloud/secrets/update.py b/nextmv/nextmv/cli/cloud/secrets/update.py index 75a024c1..d5e082ac 100644 --- a/nextmv/nextmv/cli/cloud/secrets/update.py +++ b/nextmv/nextmv/cli/cloud/secrets/update.py @@ -11,7 +11,7 @@ from nextmv.cli.configuration.config import build_cloud_app from nextmv.cli.message import enum_values, error, in_progress, print_json, success from nextmv.cli.options import AppIDOption, DebugOption, ProfileOption, SecretsCollectionIDOption -from nextmv.cloud.secrets import SecretType +from nextmv.cloud.secrets import SecretOperation, SecretOperationType, SecretType # Set up subcommand application. app = typer.Typer() @@ -21,6 +21,34 @@ def update( app_id: AppIDOption, secrets_collection_id: SecretsCollectionIDOption, + create: Annotated[ + list[str] | None, + typer.Option( + "--create", + "-c", + help="Secrets to add to the collection. Data should be valid [magenta]json[/magenta]. " + "Pass multiple secrets by repeating the flag, or providing a list of objects. " + "Allowed values for [magenta]type[/magenta] are: " + f"{enum_values(SecretType)}. " + "Object format: [dim]{'type': type, 'location': location, 'value': value}[/dim]. " + "Fails if a secret with the same type and location already exists.", + metavar="SECRETS", + ), + ] = None, + delete: Annotated[ + list[str] | None, + typer.Option( + "--delete", + "-x", + help="Secrets to remove from the collection. Data should be valid [magenta]json[/magenta]. " + "Pass multiple secrets by repeating the flag, or providing a list of objects. " + "Allowed values for [magenta]type[/magenta] are: " + f"{enum_values(SecretType)}. " + "Object format: [dim]{'type': type, 'location': location}[/dim]. " + "Secrets that do not exist are ignored.", + metavar="SECRETS", + ), + ] = None, description: Annotated[ str | None, typer.Option( @@ -58,7 +86,22 @@ def update( "Allowed values for [magenta]type[/magenta] are: " f"{enum_values(SecretType)}. " "Object format: [dim]{'type': type, 'location': location, 'value': value}[/dim]. " - "This will replace all existing secrets in the collection.", + "This will replace all existing secrets in the collection. " + "Cannot be combined with --create, --update, or --delete.", + metavar="SECRETS", + ), + ] = None, + update: Annotated[ + list[str] | None, + typer.Option( + "--update", + "-t", + help="Secrets whose value should be replaced. Data should be valid [magenta]json[/magenta]. " + "Pass multiple secrets by repeating the flag, or providing a list of objects. " + "Allowed values for [magenta]type[/magenta] are: " + f"{enum_values(SecretType)}. " + "Object format: [dim]{'type': type, 'location': location, 'value': value}[/dim]. " + "Fails if no secret with the same type and location exists.", metavar="SECRETS", ), ] = None, @@ -68,74 +111,103 @@ def update( """ Update a Nextmv Cloud secrets collection. - You can update the name, description, and/or secrets of an existing - secrets collection. When updating secrets, all existing secrets will be - replaced with the new ones provided. + You can update the name and/or description of a secrets collection, and + create, update, or delete individual secrets, without resending the + values of the secrets you are not changing. Secrets are identified by + their [magenta]type[/magenta] and [magenta]location[/magenta]. The + changes are applied all together, or not at all. - Secrets are provided as JSON objects using the --secrets flag, - following the same format as the create command. You can provide secrets as: + Alternatively, use --secrets to replace all the existing secrets in the + collection with the ones provided. + + Secrets are provided as JSON objects, following the same format as the + create command. You can provide secrets as: - A single secret as a JSON object - - Multiple secrets by repeating the --secrets flag - - Multiple secrets as a JSON array in a single --secrets flag + - Multiple secrets by repeating the flag + - Multiple secrets as a JSON array in a single flag [bold][underline]Examples[/underline][/bold] - - Update the name of a secrets collection. + - Update the name of a secrets collection, keeping its secrets as they are. $ [dim]nextmv cloud secrets update --app-id hare-app \\ --secrets-collection-id api-keys --name "Updated API Keys"[/dim] - - Update the description of a secrets collection. + - Update both name and description. + + $ [dim]nextmv cloud secrets update --app-id hare-app \\ + --secrets-collection-id api-keys --name "Production API Keys" \\ + --description "API keys for production environment"[/dim] + + - Add a new secret to a collection. $ [dim]nextmv cloud secrets update --app-id hare-app \\ --secrets-collection-id api-keys \\ - --description "Updated collection of API keys"[/dim] + --create '{"type": "env", "location": "NEW_KEY", "value": "new-value"}'[/dim] - - Update both name and description. + - Rotate the value of an existing secret. $ [dim]nextmv cloud secrets update --app-id hare-app \\ - --secrets-collection-id api-keys --name "Production API Keys" \\ - --description "API keys for production environment"[/dim] + --secrets-collection-id api-keys \\ + --update '{"type": "env", "location": "API_KEY", "value": "rotated-value"}'[/dim] - - Replace all secrets in a collection with new secrets. + - Remove a secret from a collection. $ [dim]nextmv cloud secrets update --app-id hare-app \\ --secrets-collection-id api-keys \\ - --secrets '{"type": "env", "location": "API_KEY", "value": "new-value"}' \\ - --secrets '{"type": "env", "location": "DATABASE_URL", "value": "postgres://newhost"}'[/dim] + --delete '{"type": "env", "location": "OLD_KEY"}'[/dim] - - Replace all secrets with a JSON array. + - Replace all secrets in a collection with new secrets. $ [dim]nextmv cloud secrets update --app-id hare-app \\ --secrets-collection-id api-keys \\ - --secrets '[{"type": "env", "location": "API_KEY", "value": "new-value"}, {...}]'[/dim] + --secrets '{"type": "env", "location": "API_KEY", "value": "new-value"}' \\ + --secrets '{"type": "env", "location": "DATABASE_URL", "value": "postgres://newhost"}'[/dim] - - Update multiple attributes at once and save the result. + - Combine several changes and save the result. $ [dim]nextmv cloud secrets update --app-id hare-app \\ - --secrets-collection-id api-keys --name "New Name" \\ - --description "New Description" \\ - --secrets '{"type": "env", "location": "NEW_KEY", "value": "new-value"}' \\ + --secrets-collection-id api-keys --description "Rotated keys" \\ + --update '{"type": "env", "location": "API_KEY", "value": "rotated-value"}' \\ + --delete '{"type": "env", "location": "OLD_KEY"}' \\ --output updated.json[/dim] """ - if name is None and description is None and secrets is None: - error("Provide at least one option to update: --name, --description, or --secrets.") + has_operations = create is not None or update is not None or delete is not None + if name is None and description is None and secrets is None and not has_operations: + error( + "Provide at least one option to update: --name, --description, --create, --update, --delete, or --secrets." + ) - cloud_app, _ = build_cloud_app(app_id=app_id, profile=profile) + if secrets is not None and has_operations: + error("--secrets cannot be combined with --create, --update, or --delete.") - # Build the secrets list if provided secrets_list = None if secrets is not None: secrets_list = build_secrets(secrets) + operations = None + if has_operations: + operations = build_operations(create=create, update=update, delete=delete) + + cloud_app, _ = build_cloud_app(app_id=app_id, profile=profile) + in_progress(msg="Updating secrets collection...") - collection = cloud_app.update_secrets_collection( - secrets_collection_id=secrets_collection_id, - name=name, - description=description, - secrets=secrets_list, - ) + if secrets_list is not None: + collection = cloud_app.update_secrets_collection( + secrets_collection_id=secrets_collection_id, + name=name, + description=description, + secrets=secrets_list, + ) + else: + collection = cloud_app.patch_secrets_collection( + secrets_collection_id=secrets_collection_id, + name=name, + description=description, + operations=operations, + ) + success( f"Secrets collection [magenta]{secrets_collection_id}[/magenta] updated successfully " f"in application [magenta]{app_id}[/magenta]." @@ -150,3 +222,103 @@ def update( return print_json(collection.to_dict()) + + +def build_operations( + create: list[str] | None, + update: list[str] | None, + delete: list[str] | None, +) -> list[SecretOperation]: + """ + Builds the secret operations list from the CLI options. + + Parameters + ---------- + create : list[str] | None + Secrets to create, provided via the CLI. + update : list[str] | None + Secrets to update, provided via the CLI. + delete : list[str] | None + Secrets to delete, provided via the CLI. + + Returns + ------- + list[SecretOperation] + The built operations list. + """ + + operations = [] + for op, secrets in ((SecretOperationType.CREATE, create), (SecretOperationType.UPDATE, update)): + if secrets is None: + continue + + for secret in build_secrets(secrets): + operations.append( + SecretOperation( + op=op, + secret_type=secret.secret_type, + location=secret.location, + value=secret.value, + ) + ) + + if delete is not None: + operations.extend(build_delete_operations(delete)) + + return operations + + +def build_delete_operations(secrets: list[str]) -> list[SecretOperation]: + """ + Builds the delete operations list from the CLI option(s). + + Parameters + ---------- + secrets : list[str] + List of secrets to delete provided via the CLI. + + Returns + ------- + list[SecretOperation] + The built delete operations list. + """ + + operations = [] + + for secret_str in secrets: + try: + # NOTE: never echo the raw secret string back to the terminal - it + # may contain a secret value. Reference the offending entry by + # index only (CWE-522). + secret_data = json.loads(secret_str) + items = secret_data if isinstance(secret_data, list) else [secret_data] + + for ix, item in enumerate(items): + if not isinstance(item, dict): + error("Invalid secret format. Expected a [magenta]json[/magenta] object or array.") + + if item.get("type") is None or item.get("location") is None: + error( + f"Invalid secret format at index [magenta]{ix}[/magenta]. " + "Each secret to delete must have [magenta]type[/magenta] and " + "[magenta]location[/magenta] fields." + ) + + if item.get("value") is not None: + error( + f"Invalid secret format at index [magenta]{ix}[/magenta]. " + "Secrets to delete must not have a [magenta]value[/magenta] field." + ) + + operations.append( + SecretOperation( + op=SecretOperationType.DELETE, + secret_type=SecretType(item["type"]), + location=item["location"], + ) + ) + + except (json.JSONDecodeError, KeyError, ValueError) as e: + error(f"Invalid secret format. Error: {e}") + + return operations diff --git a/nextmv/nextmv/cli/mcp/tools/secrets.py b/nextmv/nextmv/cli/mcp/tools/secrets.py index c5cd3152..bd2f8319 100644 --- a/nextmv/nextmv/cli/mcp/tools/secrets.py +++ b/nextmv/nextmv/cli/mcp/tools/secrets.py @@ -83,6 +83,50 @@ def cloud_create_secrets_collection( ) return collection.to_dict() + @mcp.tool() + def cloud_update_secrets_collection( + app_id: str, + secrets_collection_id: str, + name: str | None = None, + description: str | None = None, + operations: list[dict[str, str]] | None = None, + ) -> dict[str, Any]: + """Partially update a secrets collection. + + Updates the collection name and/or description, and/or creates, + updates, or deletes individual secrets, without resending the + values of the secrets that are not changing. Secrets are + identified by their ``type`` and ``location``. The changes are + applied all together, or not at all. Returns the updated + collection without secret values. + + Args: + app_id: The application ID. + secrets_collection_id: The secrets collection ID to update. + name: Optional new name. + description: Optional new description. + operations: Optional list of secret operations. Each is a + dict with keys: ``op`` (``"create"``, ``"update"``, or + ``"delete"``), ``type`` (``"env"`` or ``"file"``), + ``location`` (env var name or file path), and ``value`` + (the secret, required for ``create`` and ``update``, + omitted for ``delete``). ``create`` fails if the secret + already exists, ``update`` fails if it does not, and + ``delete`` ignores missing secrets. + """ + + name = _helpers._none_if_empty(name) + description = _helpers._none_if_empty(description) + + app = _helpers._get_app(app_id) + collection = app.patch_secrets_collection( + secrets_collection_id=secrets_collection_id, + name=name, + description=description, + operations=operations, + ) + return collection.to_dict() + @mcp.tool() def cloud_delete_secrets_collection( app_id: str, diff --git a/nextmv/nextmv/cloud/__init__.py b/nextmv/nextmv/cloud/__init__.py index fb5b60ff..ec0e93ab 100644 --- a/nextmv/nextmv/cloud/__init__.py +++ b/nextmv/nextmv/cloud/__init__.py @@ -58,6 +58,8 @@ from .scenario import ScenarioInput as ScenarioInput from .scenario import ScenarioInputType as ScenarioInputType from .secrets import Secret as Secret +from .secrets import SecretOperation as SecretOperation +from .secrets import SecretOperationType as SecretOperationType from .secrets import SecretsCollection as SecretsCollection from .secrets import SecretsCollectionSummary as SecretsCollectionSummary from .secrets import SecretType as SecretType diff --git a/nextmv/nextmv/cloud/application/_secrets.py b/nextmv/nextmv/cloud/application/_secrets.py index 583bffab..f54dda78 100644 --- a/nextmv/nextmv/cloud/application/_secrets.py +++ b/nextmv/nextmv/cloud/application/_secrets.py @@ -4,7 +4,13 @@ from typing import TYPE_CHECKING, Any -from nextmv.cloud.secrets import Secret, SecretsCollection, SecretsCollectionSummary +from nextmv.cloud.secrets import ( + Secret, + SecretOperation, + SecretOperationType, + SecretsCollection, + SecretsCollectionSummary, +) from nextmv.safe import safe_id if TYPE_CHECKING: @@ -175,6 +181,112 @@ def new_secrets_collection( return SecretsCollectionSummary.from_dict(response.json()) + def patch_secrets_collection( + self: "Application", + secrets_collection_id: str, + name: str | None = None, + description: str | None = None, + operations: list[SecretOperation | dict[str, Any]] | None = None, + ) -> SecretsCollection: + """ + Partially update a secrets collection. + + This method updates the name and/or description of a secrets + collection, and/or creates, updates, or deletes individual secrets, + without resending the values of the secrets that are not being + changed. Secrets are identified by their `(type, location)` pair. The + request is applied completely or not at all. + + Parameters + ---------- + secrets_collection_id : str + ID of the secrets collection to update. + name : Optional[str], default=None + Optional new name for the secrets collection. + description : Optional[str], default=None + Optional new description for the secrets collection. + operations : Optional[list[SecretOperation | dict[str, Any]]], default=None + Optional list of operations to apply to individual secrets. Each + operation should be an instance of the SecretOperation class, or a + dict with the same fields. + + Returns + ------- + SecretsCollection + The updated secrets collection. Secret values are masked in the + response. + + Raises + ------ + ValueError + If there is nothing to update, if `operations` is an empty list, + if an operation is not a SecretOperation or dict, or if more than + one operation targets the same secret. + requests.HTTPError + If the response status code is not 2xx. + + Examples + -------- + >>> from nextmv.cloud import SecretOperation, SecretOperationType, SecretType + >>> # Rename a collection without touching its secrets + >>> collection = app.patch_secrets_collection("api-secrets", name="API Secrets") + >>> # Rotate one secret and remove another + >>> collection = app.patch_secrets_collection( + ... secrets_collection_id="api-secrets", + ... operations=[ + ... SecretOperation( + ... op=SecretOperationType.UPDATE, + ... secret_type=SecretType.ENV, + ... location="API_KEY", + ... value="new-api-key", + ... ), + ... SecretOperation( + ... op=SecretOperationType.DELETE, + ... secret_type=SecretType.ENV, + ... location="OLD_API_KEY", + ... ), + ... ], + ... ) + """ + + if name is None and description is None and operations is None: + raise ValueError("at least one of name, description, or operations must be provided") + + payload: dict[str, Any] = {} + if name is not None: + payload["name"] = name + if description is not None: + payload["description"] = description + + if operations is not None: + if len(operations) == 0: + raise ValueError("operations must not be an empty list") + + operations_dicts = [] + seen = set() + for ix, operation in enumerate(operations): + if isinstance(operation, dict): + operation = SecretOperation.from_dict(operation) + elif not isinstance(operation, SecretOperation): + raise ValueError(f"operation at index {ix} must be either a SecretOperation or dict object") + + key = (operation.secret_type, operation.location) + if key in seen: + raise ValueError(f"operation at index {ix} targets the same secret as a previous operation") + seen.add(key) + + operations_dicts.append(operation.to_dict()) + + payload["operations"] = operations_dicts + + response = self.client.request( + method="PATCH", + endpoint=f"{self.endpoint}/secrets/{secrets_collection_id}", + payload=payload, + ) + + return SecretsCollection.from_dict(response.json()) + def secrets_collection(self: "Application", secrets_collection_id: str) -> SecretsCollection: """ Get a secrets collection. @@ -234,6 +346,16 @@ def update_secrets_collection( description, and secrets. A secrets collection is a group of key-value pairs that can be used by your application instances during execution. + The update is done through the partial-update (PATCH) endpoint, so + previously fetched secret values are never sent back to the server. + If `secrets` is not provided, only the name and/or description are + updated, and the secrets in the collection are left untouched. If + `secrets` is provided, all the existing secrets in the collection are + replaced with the given ones: secrets with a matching type and + location are updated, new ones are created, and the rest are deleted. + To create, update, or delete individual secrets without resending the + values of the others, use `patch_secrets_collection` instead. + Parameters ---------- secrets_collection_id : str @@ -243,8 +365,9 @@ def update_secrets_collection( description : Optional[str], default=None Optional new description for the secrets collection. secrets : Optional[list[Secret | dict[str, Any]]], default=None - Optional list of secrets to update. Each secret should be an - instance of the Secret class containing a key and value. + Optional list of secrets that replaces all the existing secrets in + the collection. Each secret should be an instance of the Secret + class containing a type, location, and value. Returns ------- @@ -254,17 +377,23 @@ def update_secrets_collection( Raises ------ ValueError - If no secrets are provided. + If there is nothing to update, or if a secret is not a Secret or + dict object. requests.HTTPError If the response status code is not 2xx. Examples -------- - >>> # Update an existing secrets collection - >>> from nextmv.cloud import Secret + >>> # Rename a secrets collection, keeping its secrets as they are + >>> updated_collection = app.update_secrets_collection( + ... secrets_collection_id="api-secrets", + ... name="Updated API Secrets", + ... ) + >>> # Replace all the secrets in a collection + >>> from nextmv.cloud import Secret, SecretType >>> updated_secrets = [ - ... Secret(key="API_KEY", value="new-api-key"), - ... Secret(key="DATABASE_URL", value="new-database-url") + ... Secret(secret_type=SecretType.ENV, location="API_KEY", value="new-api-key"), + ... Secret(secret_type=SecretType.ENV, location="DATABASE_URL", value="new-database-url"), ... ] >>> updated_collection = app.update_secrets_collection( ... secrets_collection_id="api-secrets", @@ -276,30 +405,52 @@ def update_secrets_collection( 'api-secrets' """ + if secrets is None or len(secrets) == 0: + if name is None and description is None: + raise ValueError("at least one of name, description, or secrets must be provided") + + return self.patch_secrets_collection( + secrets_collection_id=secrets_collection_id, + name=name, + description=description, + ) + + new_secrets: list[Secret] = [] + for ix, secret in enumerate(secrets): + if isinstance(secret, dict): + new_secrets.append(Secret.from_dict(secret)) + elif isinstance(secret, Secret): + new_secrets.append(secret) + else: + raise ValueError(f"secret at index {ix} must be either a Secret or dict object") + + # Replacing all the secrets is expressed as partial-update operations + # against the keys of the existing secrets. Only the keys of the + # fetched secrets are used: their values, which may be masked, are + # never sent back to the server. collection = self.secrets_collection(secrets_collection_id) - collection_dict = collection.to_dict() - payload = collection_dict.copy() - - if name is not None: - payload["name"] = name - if description is not None: - payload["description"] = description - if secrets is not None and len(secrets) > 0: - secrets_dicts = [] - for ix, secret in enumerate(secrets): - if isinstance(secret, dict): - secrets_dicts.append(secret) - elif isinstance(secret, Secret): - secrets_dicts.append(secret.to_dict()) - else: - raise ValueError(f"secret at index {ix} must be either a Secret or dict object") - - payload["secrets"] = secrets_dicts - - response = self.client.request( - method="PUT", - endpoint=f"{self.endpoint}/secrets/{secrets_collection_id}", - payload=payload, + existing_keys = {(secret.secret_type, secret.location) for secret in collection.secrets} + new_keys = {(secret.secret_type, secret.location) for secret in new_secrets} + + operations = [ + SecretOperation( + op=SecretOperationType.UPDATE + if (secret.secret_type, secret.location) in existing_keys + else SecretOperationType.CREATE, + secret_type=secret.secret_type, + location=secret.location, + value=secret.value, + ) + for secret in new_secrets + ] + operations.extend( + SecretOperation(op=SecretOperationType.DELETE, secret_type=secret_type, location=location) + for secret_type, location in sorted(existing_keys - new_keys) ) - return SecretsCollectionSummary.from_dict(response.json()) + return self.patch_secrets_collection( + secrets_collection_id=secrets_collection_id, + name=name, + description=description, + operations=operations, + ) diff --git a/nextmv/nextmv/cloud/secrets.py b/nextmv/nextmv/cloud/secrets.py index a7514b83..1add9deb 100644 --- a/nextmv/nextmv/cloud/secrets.py +++ b/nextmv/nextmv/cloud/secrets.py @@ -10,6 +10,11 @@ Representation of a sensitive piece of information. SecretsCollection Collection of secrets hosted in the Nextmv Cloud. +SecretOperationType + Enumeration of operations for partially updating a secrets collection. +SecretOperation + Single operation applied to a secret when partially updating a secrets + collection. """ @@ -232,3 +237,118 @@ class SecretsCollection(SecretsCollectionSummary, BaseModel): secrets: list[Secret] """List of secrets in the collection.""" + + +class SecretOperationType(str, Enum): + """Type of operation applied to a single secret when partially updating a + secrets collection. + + You can import the `SecretOperationType` class directly from `cloud`: + + ```python + from nextmv.cloud import SecretOperationType + ``` + + Secrets are identified by their `(type, location)` pair. + + Attributes + ---------- + CREATE : str + Adds a new secret. Fails if a secret with the same type and location + already exists in the collection. + UPDATE : str + Replaces the value of an existing secret. Fails if no secret with the + same type and location exists in the collection. + DELETE : str + Removes a secret. It is a no-op if the secret does not exist. + + Examples + -------- + >>> op = SecretOperationType.CREATE + >>> print(op.value) + create + + """ + + CREATE = "create" + """Create a new secret.""" + UPDATE = "update" + """Update the value of an existing secret.""" + DELETE = "delete" + """Delete an existing secret.""" + + +class SecretOperation(BaseModel): + """An operation applied to a single secret when partially updating a + secrets collection. + + You can import the `SecretOperation` class directly from `cloud`: + + ```python + from nextmv.cloud import SecretOperation + ``` + + Operations are sent to the partial-update (PATCH) endpoint of a secrets + collection, so that individual secrets can be created, updated, or deleted + without resending the values of the other secrets in the collection. + + Parameters + ---------- + op : SecretOperationType + The operation to apply. + secret_type : SecretType + The type of the secret. This is aliased from `type` for serialization + and validation. + location : str + The location of the secret. Together with `secret_type`, it identifies + the secret within the collection. + value : str, optional + The value of the secret. Required for `create` and `update` + operations, and must not be set for `delete` operations. + + Examples + -------- + >>> create_op = SecretOperation( + ... op=SecretOperationType.CREATE, + ... secret_type=SecretType.ENV, + ... location="API_KEY", + ... value="supersecretapikey123", + ... ) + >>> delete_op = SecretOperation( + ... op=SecretOperationType.DELETE, + ... secret_type=SecretType.ENV, + ... location="OLD_API_KEY", + ... ) + + """ + + op: SecretOperationType + """Operation to apply to the secret.""" + secret_type: SecretType = Field( + serialization_alias="type", + validation_alias=AliasChoices("type", "secret_type"), + ) + """Type of the secret.""" + location: str + """Location of the secret.""" + value: str | None = None + """Value of the secret. Not used for `delete` operations.""" + + def model_post_init(self, __context) -> None: + """ + Validations done after parsing the model. + + Raises + ------ + ValueError + If `value` is missing for a `create` or `update` operation, or set + for a `delete` operation. + """ + + if self.op == SecretOperationType.DELETE: + if self.value is not None: + raise ValueError("value must not be set for a `delete` operation.") + return + + if self.value is None: + raise ValueError(f"value is required for a `{self.op.value}` operation.") diff --git a/nextmv/tests/cli/test_mcp.py b/nextmv/tests/cli/test_mcp.py index f0bc2044..1a3fab5c 100644 --- a/nextmv/tests/cli/test_mcp.py +++ b/nextmv/tests/cli/test_mcp.py @@ -222,6 +222,7 @@ def test_server_has_all_admin_tools(self): "cloud_list_secrets_collections", "cloud_get_secrets_collection", "cloud_create_secrets_collection", + "cloud_update_secrets_collection", "cloud_delete_secrets_collection", "cloud_get_account", "cloud_get_queue", @@ -288,7 +289,7 @@ def test_total_tool_count(self): server = create_server() tool_names = list(server._tool_manager._tools.keys()) - self.assertEqual(len(tool_names), 89, f"Expected 89 tools, got {len(tool_names)}") + self.assertEqual(len(tool_names), 90, f"Expected 90 tools, got {len(tool_names)}") @patch("nextmv.cli.mcp.tools._helpers._get_client") def test_cloud_list_apps_calls_sdk(self, mock_get_client): @@ -345,6 +346,40 @@ def test_cloud_list_runs_calls_sdk(self, mock_get_app): asyncio.run(tool.run({"app_id": "my-app"}, None)) mock_app_instance.list_runs.assert_called_once_with(status=None) + @patch("nextmv.cli.mcp.tools._helpers._get_app") + def test_cloud_update_secrets_collection_calls_sdk(self, mock_get_app): + """Test that cloud_update_secrets_collection delegates to the PATCH-backed SDK method.""" + + mock_app_instance = MagicMock() + mock_app_instance.patch_secrets_collection.return_value.to_dict.return_value = {"id": "sc-1"} + mock_get_app.return_value = mock_app_instance + + operations = [ + {"op": "update", "type": "env", "location": "API_KEY", "value": "new-value"}, + {"op": "delete", "type": "env", "location": "OLD_KEY"}, + ] + server = create_server() + tool = server._tool_manager._tools["cloud_update_secrets_collection"] + asyncio.run( + tool.run( + { + "app_id": "my-app", + "secrets_collection_id": "sc-1", + "name": "", + "description": "Rotated keys", + "operations": operations, + }, + None, + ) + ) + mock_app_instance.patch_secrets_collection.assert_called_once_with( + secrets_collection_id="sc-1", + name=None, + description="Rotated keys", + operations=operations, + ) + mock_app_instance.update_secrets_collection.assert_not_called() + class TestGetClient(unittest.TestCase): """Tests for the _get_client helper.""" diff --git a/nextmv/tests/cli/test_secrets.py b/nextmv/tests/cli/test_secrets.py new file mode 100644 index 00000000..e2ac6612 --- /dev/null +++ b/nextmv/tests/cli/test_secrets.py @@ -0,0 +1,104 @@ +import unittest +from unittest.mock import MagicMock, patch + +from nextmv.cli.cloud.secrets import app +from nextmv.cloud.secrets import Secret, SecretOperation, SecretOperationType, SecretType +from typer.testing import CliRunner + + +class TestSecretsUpdateCommand(unittest.TestCase): + """Test the `nextmv cloud secrets update` command.""" + + def setUp(self): + self.runner = CliRunner() + self.cloud_app = MagicMock() + self.cloud_app.patch_secrets_collection.return_value.to_dict.return_value = {"id": "sc-1"} + + def _invoke(self, *args: str): + with patch( + "nextmv.cli.cloud.secrets.update.build_cloud_app", + return_value=(self.cloud_app, False), + ): + return self.runner.invoke(app, ["update", "--app-id", "my-app", "--secrets-collection-id", "sc-1", *args]) + + def test_builds_operations(self): + result = self._invoke( + "--name", + "New Name", + "--create", + '{"type": "env", "location": "NEW_KEY", "value": "a"}', + "--update", + '[{"type": "env", "location": "API_KEY", "value": "b"}]', + "--delete", + '{"type": "file", "location": "/old.pem"}', + ) + + self.assertEqual(result.exit_code, 0, result.output) + self.cloud_app.patch_secrets_collection.assert_called_once_with( + secrets_collection_id="sc-1", + name="New Name", + description=None, + operations=[ + SecretOperation( + op=SecretOperationType.CREATE, secret_type=SecretType.ENV, location="NEW_KEY", value="a" + ), + SecretOperation( + op=SecretOperationType.UPDATE, secret_type=SecretType.ENV, location="API_KEY", value="b" + ), + SecretOperation(op=SecretOperationType.DELETE, secret_type=SecretType.FILE, location="/old.pem"), + ], + ) + + def test_metadata_only_sends_no_operations(self): + result = self._invoke("--description", "New Description") + + self.assertEqual(result.exit_code, 0, result.output) + self.cloud_app.patch_secrets_collection.assert_called_once_with( + secrets_collection_id="sc-1", + name=None, + description="New Description", + operations=None, + ) + + def test_no_options_errors(self): + result = self._invoke() + + self.assertEqual(result.exit_code, 1) + self.cloud_app.patch_secrets_collection.assert_not_called() + + def test_delete_with_value_errors_without_echoing_it(self): + result = self._invoke("--delete", '{"type": "env", "location": "API_KEY", "value": "super-secret"}') + + self.assertEqual(result.exit_code, 1) + self.assertNotIn("super-secret", result.output) + self.cloud_app.patch_secrets_collection.assert_not_called() + + def test_secrets_replaces_all_via_sdk(self): + self.cloud_app.update_secrets_collection.return_value.to_dict.return_value = {"id": "sc-1"} + + result = self._invoke("--secrets", '{"type": "env", "location": "API_KEY", "value": "a"}') + + self.assertEqual(result.exit_code, 0, result.output) + self.cloud_app.update_secrets_collection.assert_called_once_with( + secrets_collection_id="sc-1", + name=None, + description=None, + secrets=[Secret(secret_type=SecretType.ENV, location="API_KEY", value="a")], + ) + self.cloud_app.patch_secrets_collection.assert_not_called() + + def test_secrets_cannot_be_combined_with_operations(self): + result = self._invoke( + "--secrets", + '{"type": "env", "location": "API_KEY", "value": "a"}', + "--delete", + '{"type": "env", "location": "OLD_KEY"}', + ) + + self.assertEqual(result.exit_code, 1) + self.cloud_app.update_secrets_collection.assert_not_called() + self.cloud_app.patch_secrets_collection.assert_not_called() + + +if __name__ == "__main__": + unittest.main() diff --git a/nextmv/tests/cloud/test_secrets.py b/nextmv/tests/cloud/test_secrets.py new file mode 100644 index 00000000..70032f77 --- /dev/null +++ b/nextmv/tests/cloud/test_secrets.py @@ -0,0 +1,222 @@ +import unittest +from unittest.mock import MagicMock, patch + +from nextmv.cloud import Application, Client +from nextmv.cloud.secrets import ( + Secret, + SecretOperation, + SecretOperationType, + SecretsCollection, + SecretType, +) + +MASKED_VALUE = "***************" + +COLLECTION_SUMMARY = { + "id": "sc-1", + "application_id": "my-app", + "name": "API Keys", + "description": "Keys for external services", + "created_at": "2026-08-12T15:04:05Z", + "updated_at": "2026-09-10T09:21:33Z", +} + +MASKED_COLLECTION = { + **COLLECTION_SUMMARY, + "secrets": [ + {"type": "env", "location": "API_KEY", "value": MASKED_VALUE}, + {"type": "env", "location": "DATABASE_URL", "value": MASKED_VALUE}, + ], +} + + +def _response(data: dict) -> MagicMock: + response = MagicMock() + response.json.return_value = data + return response + + +class TestSecretOperation(unittest.TestCase): + """Test validation and serialization of SecretOperation.""" + + def test_create_and_update_serialize_with_value(self): + for op in (SecretOperationType.CREATE, SecretOperationType.UPDATE): + with self.subTest(op=op): + operation = SecretOperation(op=op, secret_type=SecretType.ENV, location="API_KEY", value="v") + self.assertEqual( + operation.to_dict(), + {"op": op.value, "type": "env", "location": "API_KEY", "value": "v"}, + ) + + def test_delete_serializes_without_value(self): + operation = SecretOperation(op=SecretOperationType.DELETE, secret_type=SecretType.FILE, location="/a.pem") + self.assertEqual(operation.to_dict(), {"op": "delete", "type": "file", "location": "/a.pem"}) + + def test_create_and_update_require_value(self): + for op in ("create", "update"): + with self.subTest(op=op): + with self.assertRaises(ValueError) as context: + SecretOperation.from_dict({"op": op, "type": "env", "location": "API_KEY"}) + self.assertIn(f"value is required for a `{op}` operation", str(context.exception)) + + def test_delete_rejects_value(self): + with self.assertRaises(ValueError) as context: + SecretOperation.from_dict({"op": "delete", "type": "env", "location": "API_KEY", "value": "v"}) + self.assertIn("value must not be set for a `delete` operation", str(context.exception)) + + +class TestPatchSecretsCollection(unittest.TestCase): + """Test the PATCH-backed partial update of a secrets collection.""" + + def setUp(self): + self.app = Application(id="my-app", client=Client(api_key="test-key")) + + def test_metadata_only(self): + with patch.object(Client, "request", return_value=_response(MASKED_COLLECTION)) as mock_request: + collection = self.app.patch_secrets_collection("sc-1", name="New Name", description="New Description") + + mock_request.assert_called_once_with( + method="PATCH", + endpoint="v1/applications/my-app/secrets/sc-1", + payload={"name": "New Name", "description": "New Description"}, + ) + self.assertIsInstance(collection, SecretsCollection) + + def test_operations_from_models_and_dicts(self): + operations = [ + SecretOperation(op=SecretOperationType.CREATE, secret_type=SecretType.ENV, location="NEW", value="a"), + {"op": "update", "type": "env", "location": "API_KEY", "value": "b"}, + {"op": "delete", "type": "file", "location": "/old.pem"}, + ] + with patch.object(Client, "request", return_value=_response(MASKED_COLLECTION)) as mock_request: + self.app.patch_secrets_collection("sc-1", operations=operations) + + mock_request.assert_called_once_with( + method="PATCH", + endpoint="v1/applications/my-app/secrets/sc-1", + payload={ + "operations": [ + {"op": "create", "type": "env", "location": "NEW", "value": "a"}, + {"op": "update", "type": "env", "location": "API_KEY", "value": "b"}, + {"op": "delete", "type": "file", "location": "/old.pem"}, + ] + }, + ) + + def test_same_location_with_different_types_is_allowed(self): + operations = [ + {"op": "delete", "type": "env", "location": "KEY"}, + {"op": "create", "type": "file", "location": "KEY", "value": "a"}, + ] + with patch.object(Client, "request", return_value=_response(MASKED_COLLECTION)) as mock_request: + self.app.patch_secrets_collection("sc-1", operations=operations) + + mock_request.assert_called_once() + + def test_invalid_requests_raise_without_calling_api(self): + cases = { + "nothing to change": ({}, "at least one of name, description, or operations"), + "empty operations": ({"operations": []}, "operations must not be an empty list"), + "duplicate secret": ( + { + "operations": [ + {"op": "delete", "type": "env", "location": "API_KEY"}, + {"op": "create", "type": "env", "location": "API_KEY", "value": "a"}, + ] + }, + "operation at index 1 targets the same secret", + ), + "invalid operation type": ( + {"operations": ["not-an-operation"]}, + "operation at index 0 must be either a SecretOperation or dict object", + ), + } + for case, (kwargs, message) in cases.items(): + with self.subTest(case=case): + with patch.object(Client, "request") as mock_request: + with self.assertRaises(ValueError) as context: + self.app.patch_secrets_collection("sc-1", **kwargs) + + self.assertIn(message, str(context.exception)) + mock_request.assert_not_called() + + +class TestUpdateSecretsCollection(unittest.TestCase): + """Test that update_secrets_collection never resends fetched secret values.""" + + def setUp(self): + self.app = Application(id="my-app", client=Client(api_key="test-key")) + + def test_metadata_only_uses_patch_without_secrets(self): + for secrets in (None, []): + with self.subTest(secrets=secrets): + with patch.object(Client, "request", return_value=_response(MASKED_COLLECTION)) as mock_request: + self.app.update_secrets_collection("sc-1", name="New Name", secrets=secrets) + + mock_request.assert_called_once_with( + method="PATCH", + endpoint="v1/applications/my-app/secrets/sc-1", + payload={"name": "New Name"}, + ) + + def test_nothing_to_update_raises(self): + with patch.object(Client, "request") as mock_request: + with self.assertRaises(ValueError): + self.app.update_secrets_collection("sc-1") + + mock_request.assert_not_called() + + def test_with_secrets_replaces_via_patch_operations(self): + responses = [_response(MASKED_COLLECTION), _response(MASKED_COLLECTION)] + with patch.object(Client, "request", side_effect=responses) as mock_request: + self.app.update_secrets_collection( + "sc-1", + description="New Description", + secrets=[ + Secret(secret_type=SecretType.ENV, location="API_KEY", value="new-api-key"), + {"type": "file", "location": "/cert.pem", "value": "cert"}, + ], + ) + + self.assertEqual(mock_request.call_count, 2) + get_call, patch_call = mock_request.call_args_list + self.assertEqual(get_call.kwargs["method"], "GET") + self.assertEqual(patch_call.kwargs["method"], "PATCH") + self.assertEqual(patch_call.kwargs["endpoint"], "v1/applications/my-app/secrets/sc-1") + + payload = patch_call.kwargs["payload"] + self.assertEqual( + payload, + { + "description": "New Description", + "operations": [ + {"op": "update", "type": "env", "location": "API_KEY", "value": "new-api-key"}, + {"op": "create", "type": "file", "location": "/cert.pem", "value": "cert"}, + {"op": "delete", "type": "env", "location": "DATABASE_URL"}, + ], + }, + ) + self.assertNotIn(MASKED_VALUE, str(payload)) + + def test_never_uses_put(self): + responses = [_response(MASKED_COLLECTION), _response(MASKED_COLLECTION), _response(MASKED_COLLECTION)] + with patch.object(Client, "request", side_effect=responses) as mock_request: + self.app.update_secrets_collection("sc-1", name="New Name") + self.app.update_secrets_collection( + "sc-1", + secrets=[Secret(secret_type=SecretType.ENV, location="API_KEY", value="v")], + ) + + methods = [call.kwargs["method"] for call in mock_request.call_args_list] + self.assertNotIn("PUT", methods) + + def test_invalid_secret_raises_before_any_request(self): + with patch.object(Client, "request") as mock_request: + with self.assertRaises(ValueError): + self.app.update_secrets_collection("sc-1", secrets=["not-a-secret"]) + + mock_request.assert_not_called() + + +if __name__ == "__main__": + unittest.main() From 5796050b70e5af0327312205210865d197271d44 Mon Sep 17 00:00:00 2001 From: Ronessa Acquesta Date: Sat, 17 Oct 2026 15:46:30 -0400 Subject: [PATCH 2/4] refactor(secrets): keep secrets collection update as a full replace [NMV-1073] Drop the explicit create/update/delete operations surface so that updating a secrets collection behaves exactly as before: - Remove --create/--update/--delete from `nextmv cloud secrets update`. - Remove the cloud_update_secrets_collection MCP tool. - Remove patch_secrets_collection, SecretOperation, and SecretOperationType from the public SDK. update_secrets_collection still goes through the PATCH endpoint so masked values are never resent: metadata-only updates send no secrets, and --secrets replaces the whole collection, with the operations derived internally from the keys returned by GET. Co-Authored-By: Claude Opus 5.5 (1M context) --- nextmv/nextmv/cli/cloud/secrets/update.py | 240 +++----------------- nextmv/nextmv/cli/mcp/tools/secrets.py | 44 ---- nextmv/nextmv/cloud/__init__.py | 2 - nextmv/nextmv/cloud/application/_secrets.py | 202 ++++------------ nextmv/nextmv/cloud/secrets.py | 120 ---------- nextmv/tests/cli/test_mcp.py | 37 +-- nextmv/tests/cli/test_secrets.py | 104 --------- nextmv/tests/cloud/test_secrets.py | 113 +-------- 8 files changed, 79 insertions(+), 783 deletions(-) delete mode 100644 nextmv/tests/cli/test_secrets.py diff --git a/nextmv/nextmv/cli/cloud/secrets/update.py b/nextmv/nextmv/cli/cloud/secrets/update.py index d5e082ac..75a024c1 100644 --- a/nextmv/nextmv/cli/cloud/secrets/update.py +++ b/nextmv/nextmv/cli/cloud/secrets/update.py @@ -11,7 +11,7 @@ from nextmv.cli.configuration.config import build_cloud_app from nextmv.cli.message import enum_values, error, in_progress, print_json, success from nextmv.cli.options import AppIDOption, DebugOption, ProfileOption, SecretsCollectionIDOption -from nextmv.cloud.secrets import SecretOperation, SecretOperationType, SecretType +from nextmv.cloud.secrets import SecretType # Set up subcommand application. app = typer.Typer() @@ -21,34 +21,6 @@ def update( app_id: AppIDOption, secrets_collection_id: SecretsCollectionIDOption, - create: Annotated[ - list[str] | None, - typer.Option( - "--create", - "-c", - help="Secrets to add to the collection. Data should be valid [magenta]json[/magenta]. " - "Pass multiple secrets by repeating the flag, or providing a list of objects. " - "Allowed values for [magenta]type[/magenta] are: " - f"{enum_values(SecretType)}. " - "Object format: [dim]{'type': type, 'location': location, 'value': value}[/dim]. " - "Fails if a secret with the same type and location already exists.", - metavar="SECRETS", - ), - ] = None, - delete: Annotated[ - list[str] | None, - typer.Option( - "--delete", - "-x", - help="Secrets to remove from the collection. Data should be valid [magenta]json[/magenta]. " - "Pass multiple secrets by repeating the flag, or providing a list of objects. " - "Allowed values for [magenta]type[/magenta] are: " - f"{enum_values(SecretType)}. " - "Object format: [dim]{'type': type, 'location': location}[/dim]. " - "Secrets that do not exist are ignored.", - metavar="SECRETS", - ), - ] = None, description: Annotated[ str | None, typer.Option( @@ -86,22 +58,7 @@ def update( "Allowed values for [magenta]type[/magenta] are: " f"{enum_values(SecretType)}. " "Object format: [dim]{'type': type, 'location': location, 'value': value}[/dim]. " - "This will replace all existing secrets in the collection. " - "Cannot be combined with --create, --update, or --delete.", - metavar="SECRETS", - ), - ] = None, - update: Annotated[ - list[str] | None, - typer.Option( - "--update", - "-t", - help="Secrets whose value should be replaced. Data should be valid [magenta]json[/magenta]. " - "Pass multiple secrets by repeating the flag, or providing a list of objects. " - "Allowed values for [magenta]type[/magenta] are: " - f"{enum_values(SecretType)}. " - "Object format: [dim]{'type': type, 'location': location, 'value': value}[/dim]. " - "Fails if no secret with the same type and location exists.", + "This will replace all existing secrets in the collection.", metavar="SECRETS", ), ] = None, @@ -111,103 +68,74 @@ def update( """ Update a Nextmv Cloud secrets collection. - You can update the name and/or description of a secrets collection, and - create, update, or delete individual secrets, without resending the - values of the secrets you are not changing. Secrets are identified by - their [magenta]type[/magenta] and [magenta]location[/magenta]. The - changes are applied all together, or not at all. + You can update the name, description, and/or secrets of an existing + secrets collection. When updating secrets, all existing secrets will be + replaced with the new ones provided. - Alternatively, use --secrets to replace all the existing secrets in the - collection with the ones provided. - - Secrets are provided as JSON objects, following the same format as the - create command. You can provide secrets as: + Secrets are provided as JSON objects using the --secrets flag, + following the same format as the create command. You can provide secrets as: - A single secret as a JSON object - - Multiple secrets by repeating the flag - - Multiple secrets as a JSON array in a single flag + - Multiple secrets by repeating the --secrets flag + - Multiple secrets as a JSON array in a single --secrets flag [bold][underline]Examples[/underline][/bold] - - Update the name of a secrets collection, keeping its secrets as they are. + - Update the name of a secrets collection. $ [dim]nextmv cloud secrets update --app-id hare-app \\ --secrets-collection-id api-keys --name "Updated API Keys"[/dim] - - Update both name and description. - - $ [dim]nextmv cloud secrets update --app-id hare-app \\ - --secrets-collection-id api-keys --name "Production API Keys" \\ - --description "API keys for production environment"[/dim] - - - Add a new secret to a collection. + - Update the description of a secrets collection. $ [dim]nextmv cloud secrets update --app-id hare-app \\ --secrets-collection-id api-keys \\ - --create '{"type": "env", "location": "NEW_KEY", "value": "new-value"}'[/dim] + --description "Updated collection of API keys"[/dim] - - Rotate the value of an existing secret. + - Update both name and description. $ [dim]nextmv cloud secrets update --app-id hare-app \\ - --secrets-collection-id api-keys \\ - --update '{"type": "env", "location": "API_KEY", "value": "rotated-value"}'[/dim] + --secrets-collection-id api-keys --name "Production API Keys" \\ + --description "API keys for production environment"[/dim] - - Remove a secret from a collection. + - Replace all secrets in a collection with new secrets. $ [dim]nextmv cloud secrets update --app-id hare-app \\ --secrets-collection-id api-keys \\ - --delete '{"type": "env", "location": "OLD_KEY"}'[/dim] + --secrets '{"type": "env", "location": "API_KEY", "value": "new-value"}' \\ + --secrets '{"type": "env", "location": "DATABASE_URL", "value": "postgres://newhost"}'[/dim] - - Replace all secrets in a collection with new secrets. + - Replace all secrets with a JSON array. $ [dim]nextmv cloud secrets update --app-id hare-app \\ --secrets-collection-id api-keys \\ - --secrets '{"type": "env", "location": "API_KEY", "value": "new-value"}' \\ - --secrets '{"type": "env", "location": "DATABASE_URL", "value": "postgres://newhost"}'[/dim] + --secrets '[{"type": "env", "location": "API_KEY", "value": "new-value"}, {...}]'[/dim] - - Combine several changes and save the result. + - Update multiple attributes at once and save the result. $ [dim]nextmv cloud secrets update --app-id hare-app \\ - --secrets-collection-id api-keys --description "Rotated keys" \\ - --update '{"type": "env", "location": "API_KEY", "value": "rotated-value"}' \\ - --delete '{"type": "env", "location": "OLD_KEY"}' \\ + --secrets-collection-id api-keys --name "New Name" \\ + --description "New Description" \\ + --secrets '{"type": "env", "location": "NEW_KEY", "value": "new-value"}' \\ --output updated.json[/dim] """ - has_operations = create is not None or update is not None or delete is not None - if name is None and description is None and secrets is None and not has_operations: - error( - "Provide at least one option to update: --name, --description, --create, --update, --delete, or --secrets." - ) + if name is None and description is None and secrets is None: + error("Provide at least one option to update: --name, --description, or --secrets.") - if secrets is not None and has_operations: - error("--secrets cannot be combined with --create, --update, or --delete.") + cloud_app, _ = build_cloud_app(app_id=app_id, profile=profile) + # Build the secrets list if provided secrets_list = None if secrets is not None: secrets_list = build_secrets(secrets) - operations = None - if has_operations: - operations = build_operations(create=create, update=update, delete=delete) - - cloud_app, _ = build_cloud_app(app_id=app_id, profile=profile) - in_progress(msg="Updating secrets collection...") - if secrets_list is not None: - collection = cloud_app.update_secrets_collection( - secrets_collection_id=secrets_collection_id, - name=name, - description=description, - secrets=secrets_list, - ) - else: - collection = cloud_app.patch_secrets_collection( - secrets_collection_id=secrets_collection_id, - name=name, - description=description, - operations=operations, - ) - + collection = cloud_app.update_secrets_collection( + secrets_collection_id=secrets_collection_id, + name=name, + description=description, + secrets=secrets_list, + ) success( f"Secrets collection [magenta]{secrets_collection_id}[/magenta] updated successfully " f"in application [magenta]{app_id}[/magenta]." @@ -222,103 +150,3 @@ def update( return print_json(collection.to_dict()) - - -def build_operations( - create: list[str] | None, - update: list[str] | None, - delete: list[str] | None, -) -> list[SecretOperation]: - """ - Builds the secret operations list from the CLI options. - - Parameters - ---------- - create : list[str] | None - Secrets to create, provided via the CLI. - update : list[str] | None - Secrets to update, provided via the CLI. - delete : list[str] | None - Secrets to delete, provided via the CLI. - - Returns - ------- - list[SecretOperation] - The built operations list. - """ - - operations = [] - for op, secrets in ((SecretOperationType.CREATE, create), (SecretOperationType.UPDATE, update)): - if secrets is None: - continue - - for secret in build_secrets(secrets): - operations.append( - SecretOperation( - op=op, - secret_type=secret.secret_type, - location=secret.location, - value=secret.value, - ) - ) - - if delete is not None: - operations.extend(build_delete_operations(delete)) - - return operations - - -def build_delete_operations(secrets: list[str]) -> list[SecretOperation]: - """ - Builds the delete operations list from the CLI option(s). - - Parameters - ---------- - secrets : list[str] - List of secrets to delete provided via the CLI. - - Returns - ------- - list[SecretOperation] - The built delete operations list. - """ - - operations = [] - - for secret_str in secrets: - try: - # NOTE: never echo the raw secret string back to the terminal - it - # may contain a secret value. Reference the offending entry by - # index only (CWE-522). - secret_data = json.loads(secret_str) - items = secret_data if isinstance(secret_data, list) else [secret_data] - - for ix, item in enumerate(items): - if not isinstance(item, dict): - error("Invalid secret format. Expected a [magenta]json[/magenta] object or array.") - - if item.get("type") is None or item.get("location") is None: - error( - f"Invalid secret format at index [magenta]{ix}[/magenta]. " - "Each secret to delete must have [magenta]type[/magenta] and " - "[magenta]location[/magenta] fields." - ) - - if item.get("value") is not None: - error( - f"Invalid secret format at index [magenta]{ix}[/magenta]. " - "Secrets to delete must not have a [magenta]value[/magenta] field." - ) - - operations.append( - SecretOperation( - op=SecretOperationType.DELETE, - secret_type=SecretType(item["type"]), - location=item["location"], - ) - ) - - except (json.JSONDecodeError, KeyError, ValueError) as e: - error(f"Invalid secret format. Error: {e}") - - return operations diff --git a/nextmv/nextmv/cli/mcp/tools/secrets.py b/nextmv/nextmv/cli/mcp/tools/secrets.py index bd2f8319..c5cd3152 100644 --- a/nextmv/nextmv/cli/mcp/tools/secrets.py +++ b/nextmv/nextmv/cli/mcp/tools/secrets.py @@ -83,50 +83,6 @@ def cloud_create_secrets_collection( ) return collection.to_dict() - @mcp.tool() - def cloud_update_secrets_collection( - app_id: str, - secrets_collection_id: str, - name: str | None = None, - description: str | None = None, - operations: list[dict[str, str]] | None = None, - ) -> dict[str, Any]: - """Partially update a secrets collection. - - Updates the collection name and/or description, and/or creates, - updates, or deletes individual secrets, without resending the - values of the secrets that are not changing. Secrets are - identified by their ``type`` and ``location``. The changes are - applied all together, or not at all. Returns the updated - collection without secret values. - - Args: - app_id: The application ID. - secrets_collection_id: The secrets collection ID to update. - name: Optional new name. - description: Optional new description. - operations: Optional list of secret operations. Each is a - dict with keys: ``op`` (``"create"``, ``"update"``, or - ``"delete"``), ``type`` (``"env"`` or ``"file"``), - ``location`` (env var name or file path), and ``value`` - (the secret, required for ``create`` and ``update``, - omitted for ``delete``). ``create`` fails if the secret - already exists, ``update`` fails if it does not, and - ``delete`` ignores missing secrets. - """ - - name = _helpers._none_if_empty(name) - description = _helpers._none_if_empty(description) - - app = _helpers._get_app(app_id) - collection = app.patch_secrets_collection( - secrets_collection_id=secrets_collection_id, - name=name, - description=description, - operations=operations, - ) - return collection.to_dict() - @mcp.tool() def cloud_delete_secrets_collection( app_id: str, diff --git a/nextmv/nextmv/cloud/__init__.py b/nextmv/nextmv/cloud/__init__.py index ec0e93ab..fb5b60ff 100644 --- a/nextmv/nextmv/cloud/__init__.py +++ b/nextmv/nextmv/cloud/__init__.py @@ -58,8 +58,6 @@ from .scenario import ScenarioInput as ScenarioInput from .scenario import ScenarioInputType as ScenarioInputType from .secrets import Secret as Secret -from .secrets import SecretOperation as SecretOperation -from .secrets import SecretOperationType as SecretOperationType from .secrets import SecretsCollection as SecretsCollection from .secrets import SecretsCollectionSummary as SecretsCollectionSummary from .secrets import SecretType as SecretType diff --git a/nextmv/nextmv/cloud/application/_secrets.py b/nextmv/nextmv/cloud/application/_secrets.py index f54dda78..96247c1d 100644 --- a/nextmv/nextmv/cloud/application/_secrets.py +++ b/nextmv/nextmv/cloud/application/_secrets.py @@ -4,13 +4,7 @@ from typing import TYPE_CHECKING, Any -from nextmv.cloud.secrets import ( - Secret, - SecretOperation, - SecretOperationType, - SecretsCollection, - SecretsCollectionSummary, -) +from nextmv.cloud.secrets import Secret, SecretsCollection, SecretsCollectionSummary from nextmv.safe import safe_id if TYPE_CHECKING: @@ -181,112 +175,6 @@ def new_secrets_collection( return SecretsCollectionSummary.from_dict(response.json()) - def patch_secrets_collection( - self: "Application", - secrets_collection_id: str, - name: str | None = None, - description: str | None = None, - operations: list[SecretOperation | dict[str, Any]] | None = None, - ) -> SecretsCollection: - """ - Partially update a secrets collection. - - This method updates the name and/or description of a secrets - collection, and/or creates, updates, or deletes individual secrets, - without resending the values of the secrets that are not being - changed. Secrets are identified by their `(type, location)` pair. The - request is applied completely or not at all. - - Parameters - ---------- - secrets_collection_id : str - ID of the secrets collection to update. - name : Optional[str], default=None - Optional new name for the secrets collection. - description : Optional[str], default=None - Optional new description for the secrets collection. - operations : Optional[list[SecretOperation | dict[str, Any]]], default=None - Optional list of operations to apply to individual secrets. Each - operation should be an instance of the SecretOperation class, or a - dict with the same fields. - - Returns - ------- - SecretsCollection - The updated secrets collection. Secret values are masked in the - response. - - Raises - ------ - ValueError - If there is nothing to update, if `operations` is an empty list, - if an operation is not a SecretOperation or dict, or if more than - one operation targets the same secret. - requests.HTTPError - If the response status code is not 2xx. - - Examples - -------- - >>> from nextmv.cloud import SecretOperation, SecretOperationType, SecretType - >>> # Rename a collection without touching its secrets - >>> collection = app.patch_secrets_collection("api-secrets", name="API Secrets") - >>> # Rotate one secret and remove another - >>> collection = app.patch_secrets_collection( - ... secrets_collection_id="api-secrets", - ... operations=[ - ... SecretOperation( - ... op=SecretOperationType.UPDATE, - ... secret_type=SecretType.ENV, - ... location="API_KEY", - ... value="new-api-key", - ... ), - ... SecretOperation( - ... op=SecretOperationType.DELETE, - ... secret_type=SecretType.ENV, - ... location="OLD_API_KEY", - ... ), - ... ], - ... ) - """ - - if name is None and description is None and operations is None: - raise ValueError("at least one of name, description, or operations must be provided") - - payload: dict[str, Any] = {} - if name is not None: - payload["name"] = name - if description is not None: - payload["description"] = description - - if operations is not None: - if len(operations) == 0: - raise ValueError("operations must not be an empty list") - - operations_dicts = [] - seen = set() - for ix, operation in enumerate(operations): - if isinstance(operation, dict): - operation = SecretOperation.from_dict(operation) - elif not isinstance(operation, SecretOperation): - raise ValueError(f"operation at index {ix} must be either a SecretOperation or dict object") - - key = (operation.secret_type, operation.location) - if key in seen: - raise ValueError(f"operation at index {ix} targets the same secret as a previous operation") - seen.add(key) - - operations_dicts.append(operation.to_dict()) - - payload["operations"] = operations_dicts - - response = self.client.request( - method="PATCH", - endpoint=f"{self.endpoint}/secrets/{secrets_collection_id}", - payload=payload, - ) - - return SecretsCollection.from_dict(response.json()) - def secrets_collection(self: "Application", secrets_collection_id: str) -> SecretsCollection: """ Get a secrets collection. @@ -353,8 +241,6 @@ def update_secrets_collection( `secrets` is provided, all the existing secrets in the collection are replaced with the given ones: secrets with a matching type and location are updated, new ones are created, and the rest are deleted. - To create, update, or delete individual secrets without resending the - values of the others, use `patch_secrets_collection` instead. Parameters ---------- @@ -405,52 +291,50 @@ class containing a type, location, and value. 'api-secrets' """ - if secrets is None or len(secrets) == 0: - if name is None and description is None: - raise ValueError("at least one of name, description, or secrets must be provided") + if name is None and description is None and (secrets is None or len(secrets) == 0): + raise ValueError("at least one of name, description, or secrets must be provided") - return self.patch_secrets_collection( - secrets_collection_id=secrets_collection_id, - name=name, - description=description, - ) + payload: dict[str, Any] = {} + if name is not None: + payload["name"] = name + if description is not None: + payload["description"] = description - new_secrets: list[Secret] = [] - for ix, secret in enumerate(secrets): - if isinstance(secret, dict): - new_secrets.append(Secret.from_dict(secret)) - elif isinstance(secret, Secret): - new_secrets.append(secret) - else: - raise ValueError(f"secret at index {ix} must be either a Secret or dict object") - - # Replacing all the secrets is expressed as partial-update operations - # against the keys of the existing secrets. Only the keys of the - # fetched secrets are used: their values, which may be masked, are - # never sent back to the server. - collection = self.secrets_collection(secrets_collection_id) - existing_keys = {(secret.secret_type, secret.location) for secret in collection.secrets} - new_keys = {(secret.secret_type, secret.location) for secret in new_secrets} - - operations = [ - SecretOperation( - op=SecretOperationType.UPDATE - if (secret.secret_type, secret.location) in existing_keys - else SecretOperationType.CREATE, - secret_type=secret.secret_type, - location=secret.location, - value=secret.value, + if secrets is not None and len(secrets) > 0: + new_secrets: list[Secret] = [] + for ix, secret in enumerate(secrets): + if isinstance(secret, dict): + new_secrets.append(Secret.from_dict(secret)) + elif isinstance(secret, Secret): + new_secrets.append(secret) + else: + raise ValueError(f"secret at index {ix} must be either a Secret or dict object") + + # Replacing all the secrets is expressed as partial-update + # operations against the keys of the existing secrets. Only the + # keys of the fetched secrets are used: their values, which are + # masked, are never sent back to the server. + collection = self.secrets_collection(secrets_collection_id) + existing_keys = {(secret.secret_type, secret.location) for secret in collection.secrets} + new_keys = {(secret.secret_type, secret.location) for secret in new_secrets} + + operations = [ + { + "op": "update" if (secret.secret_type, secret.location) in existing_keys else "create", + **secret.to_dict(), + } + for secret in new_secrets + ] + operations.extend( + {"op": "delete", "type": secret_type.value, "location": location} + for secret_type, location in sorted(existing_keys - new_keys) ) - for secret in new_secrets - ] - operations.extend( - SecretOperation(op=SecretOperationType.DELETE, secret_type=secret_type, location=location) - for secret_type, location in sorted(existing_keys - new_keys) - ) + payload["operations"] = operations - return self.patch_secrets_collection( - secrets_collection_id=secrets_collection_id, - name=name, - description=description, - operations=operations, + response = self.client.request( + method="PATCH", + endpoint=f"{self.endpoint}/secrets/{secrets_collection_id}", + payload=payload, ) + + return SecretsCollectionSummary.from_dict(response.json()) diff --git a/nextmv/nextmv/cloud/secrets.py b/nextmv/nextmv/cloud/secrets.py index 1add9deb..a7514b83 100644 --- a/nextmv/nextmv/cloud/secrets.py +++ b/nextmv/nextmv/cloud/secrets.py @@ -10,11 +10,6 @@ Representation of a sensitive piece of information. SecretsCollection Collection of secrets hosted in the Nextmv Cloud. -SecretOperationType - Enumeration of operations for partially updating a secrets collection. -SecretOperation - Single operation applied to a secret when partially updating a secrets - collection. """ @@ -237,118 +232,3 @@ class SecretsCollection(SecretsCollectionSummary, BaseModel): secrets: list[Secret] """List of secrets in the collection.""" - - -class SecretOperationType(str, Enum): - """Type of operation applied to a single secret when partially updating a - secrets collection. - - You can import the `SecretOperationType` class directly from `cloud`: - - ```python - from nextmv.cloud import SecretOperationType - ``` - - Secrets are identified by their `(type, location)` pair. - - Attributes - ---------- - CREATE : str - Adds a new secret. Fails if a secret with the same type and location - already exists in the collection. - UPDATE : str - Replaces the value of an existing secret. Fails if no secret with the - same type and location exists in the collection. - DELETE : str - Removes a secret. It is a no-op if the secret does not exist. - - Examples - -------- - >>> op = SecretOperationType.CREATE - >>> print(op.value) - create - - """ - - CREATE = "create" - """Create a new secret.""" - UPDATE = "update" - """Update the value of an existing secret.""" - DELETE = "delete" - """Delete an existing secret.""" - - -class SecretOperation(BaseModel): - """An operation applied to a single secret when partially updating a - secrets collection. - - You can import the `SecretOperation` class directly from `cloud`: - - ```python - from nextmv.cloud import SecretOperation - ``` - - Operations are sent to the partial-update (PATCH) endpoint of a secrets - collection, so that individual secrets can be created, updated, or deleted - without resending the values of the other secrets in the collection. - - Parameters - ---------- - op : SecretOperationType - The operation to apply. - secret_type : SecretType - The type of the secret. This is aliased from `type` for serialization - and validation. - location : str - The location of the secret. Together with `secret_type`, it identifies - the secret within the collection. - value : str, optional - The value of the secret. Required for `create` and `update` - operations, and must not be set for `delete` operations. - - Examples - -------- - >>> create_op = SecretOperation( - ... op=SecretOperationType.CREATE, - ... secret_type=SecretType.ENV, - ... location="API_KEY", - ... value="supersecretapikey123", - ... ) - >>> delete_op = SecretOperation( - ... op=SecretOperationType.DELETE, - ... secret_type=SecretType.ENV, - ... location="OLD_API_KEY", - ... ) - - """ - - op: SecretOperationType - """Operation to apply to the secret.""" - secret_type: SecretType = Field( - serialization_alias="type", - validation_alias=AliasChoices("type", "secret_type"), - ) - """Type of the secret.""" - location: str - """Location of the secret.""" - value: str | None = None - """Value of the secret. Not used for `delete` operations.""" - - def model_post_init(self, __context) -> None: - """ - Validations done after parsing the model. - - Raises - ------ - ValueError - If `value` is missing for a `create` or `update` operation, or set - for a `delete` operation. - """ - - if self.op == SecretOperationType.DELETE: - if self.value is not None: - raise ValueError("value must not be set for a `delete` operation.") - return - - if self.value is None: - raise ValueError(f"value is required for a `{self.op.value}` operation.") diff --git a/nextmv/tests/cli/test_mcp.py b/nextmv/tests/cli/test_mcp.py index 1a3fab5c..f0bc2044 100644 --- a/nextmv/tests/cli/test_mcp.py +++ b/nextmv/tests/cli/test_mcp.py @@ -222,7 +222,6 @@ def test_server_has_all_admin_tools(self): "cloud_list_secrets_collections", "cloud_get_secrets_collection", "cloud_create_secrets_collection", - "cloud_update_secrets_collection", "cloud_delete_secrets_collection", "cloud_get_account", "cloud_get_queue", @@ -289,7 +288,7 @@ def test_total_tool_count(self): server = create_server() tool_names = list(server._tool_manager._tools.keys()) - self.assertEqual(len(tool_names), 90, f"Expected 90 tools, got {len(tool_names)}") + self.assertEqual(len(tool_names), 89, f"Expected 89 tools, got {len(tool_names)}") @patch("nextmv.cli.mcp.tools._helpers._get_client") def test_cloud_list_apps_calls_sdk(self, mock_get_client): @@ -346,40 +345,6 @@ def test_cloud_list_runs_calls_sdk(self, mock_get_app): asyncio.run(tool.run({"app_id": "my-app"}, None)) mock_app_instance.list_runs.assert_called_once_with(status=None) - @patch("nextmv.cli.mcp.tools._helpers._get_app") - def test_cloud_update_secrets_collection_calls_sdk(self, mock_get_app): - """Test that cloud_update_secrets_collection delegates to the PATCH-backed SDK method.""" - - mock_app_instance = MagicMock() - mock_app_instance.patch_secrets_collection.return_value.to_dict.return_value = {"id": "sc-1"} - mock_get_app.return_value = mock_app_instance - - operations = [ - {"op": "update", "type": "env", "location": "API_KEY", "value": "new-value"}, - {"op": "delete", "type": "env", "location": "OLD_KEY"}, - ] - server = create_server() - tool = server._tool_manager._tools["cloud_update_secrets_collection"] - asyncio.run( - tool.run( - { - "app_id": "my-app", - "secrets_collection_id": "sc-1", - "name": "", - "description": "Rotated keys", - "operations": operations, - }, - None, - ) - ) - mock_app_instance.patch_secrets_collection.assert_called_once_with( - secrets_collection_id="sc-1", - name=None, - description="Rotated keys", - operations=operations, - ) - mock_app_instance.update_secrets_collection.assert_not_called() - class TestGetClient(unittest.TestCase): """Tests for the _get_client helper.""" diff --git a/nextmv/tests/cli/test_secrets.py b/nextmv/tests/cli/test_secrets.py deleted file mode 100644 index e2ac6612..00000000 --- a/nextmv/tests/cli/test_secrets.py +++ /dev/null @@ -1,104 +0,0 @@ -import unittest -from unittest.mock import MagicMock, patch - -from nextmv.cli.cloud.secrets import app -from nextmv.cloud.secrets import Secret, SecretOperation, SecretOperationType, SecretType -from typer.testing import CliRunner - - -class TestSecretsUpdateCommand(unittest.TestCase): - """Test the `nextmv cloud secrets update` command.""" - - def setUp(self): - self.runner = CliRunner() - self.cloud_app = MagicMock() - self.cloud_app.patch_secrets_collection.return_value.to_dict.return_value = {"id": "sc-1"} - - def _invoke(self, *args: str): - with patch( - "nextmv.cli.cloud.secrets.update.build_cloud_app", - return_value=(self.cloud_app, False), - ): - return self.runner.invoke(app, ["update", "--app-id", "my-app", "--secrets-collection-id", "sc-1", *args]) - - def test_builds_operations(self): - result = self._invoke( - "--name", - "New Name", - "--create", - '{"type": "env", "location": "NEW_KEY", "value": "a"}', - "--update", - '[{"type": "env", "location": "API_KEY", "value": "b"}]', - "--delete", - '{"type": "file", "location": "/old.pem"}', - ) - - self.assertEqual(result.exit_code, 0, result.output) - self.cloud_app.patch_secrets_collection.assert_called_once_with( - secrets_collection_id="sc-1", - name="New Name", - description=None, - operations=[ - SecretOperation( - op=SecretOperationType.CREATE, secret_type=SecretType.ENV, location="NEW_KEY", value="a" - ), - SecretOperation( - op=SecretOperationType.UPDATE, secret_type=SecretType.ENV, location="API_KEY", value="b" - ), - SecretOperation(op=SecretOperationType.DELETE, secret_type=SecretType.FILE, location="/old.pem"), - ], - ) - - def test_metadata_only_sends_no_operations(self): - result = self._invoke("--description", "New Description") - - self.assertEqual(result.exit_code, 0, result.output) - self.cloud_app.patch_secrets_collection.assert_called_once_with( - secrets_collection_id="sc-1", - name=None, - description="New Description", - operations=None, - ) - - def test_no_options_errors(self): - result = self._invoke() - - self.assertEqual(result.exit_code, 1) - self.cloud_app.patch_secrets_collection.assert_not_called() - - def test_delete_with_value_errors_without_echoing_it(self): - result = self._invoke("--delete", '{"type": "env", "location": "API_KEY", "value": "super-secret"}') - - self.assertEqual(result.exit_code, 1) - self.assertNotIn("super-secret", result.output) - self.cloud_app.patch_secrets_collection.assert_not_called() - - def test_secrets_replaces_all_via_sdk(self): - self.cloud_app.update_secrets_collection.return_value.to_dict.return_value = {"id": "sc-1"} - - result = self._invoke("--secrets", '{"type": "env", "location": "API_KEY", "value": "a"}') - - self.assertEqual(result.exit_code, 0, result.output) - self.cloud_app.update_secrets_collection.assert_called_once_with( - secrets_collection_id="sc-1", - name=None, - description=None, - secrets=[Secret(secret_type=SecretType.ENV, location="API_KEY", value="a")], - ) - self.cloud_app.patch_secrets_collection.assert_not_called() - - def test_secrets_cannot_be_combined_with_operations(self): - result = self._invoke( - "--secrets", - '{"type": "env", "location": "API_KEY", "value": "a"}', - "--delete", - '{"type": "env", "location": "OLD_KEY"}', - ) - - self.assertEqual(result.exit_code, 1) - self.cloud_app.update_secrets_collection.assert_not_called() - self.cloud_app.patch_secrets_collection.assert_not_called() - - -if __name__ == "__main__": - unittest.main() diff --git a/nextmv/tests/cloud/test_secrets.py b/nextmv/tests/cloud/test_secrets.py index 70032f77..3669b415 100644 --- a/nextmv/tests/cloud/test_secrets.py +++ b/nextmv/tests/cloud/test_secrets.py @@ -2,13 +2,7 @@ from unittest.mock import MagicMock, patch from nextmv.cloud import Application, Client -from nextmv.cloud.secrets import ( - Secret, - SecretOperation, - SecretOperationType, - SecretsCollection, - SecretType, -) +from nextmv.cloud.secrets import Secret, SecretType MASKED_VALUE = "***************" @@ -36,111 +30,6 @@ def _response(data: dict) -> MagicMock: return response -class TestSecretOperation(unittest.TestCase): - """Test validation and serialization of SecretOperation.""" - - def test_create_and_update_serialize_with_value(self): - for op in (SecretOperationType.CREATE, SecretOperationType.UPDATE): - with self.subTest(op=op): - operation = SecretOperation(op=op, secret_type=SecretType.ENV, location="API_KEY", value="v") - self.assertEqual( - operation.to_dict(), - {"op": op.value, "type": "env", "location": "API_KEY", "value": "v"}, - ) - - def test_delete_serializes_without_value(self): - operation = SecretOperation(op=SecretOperationType.DELETE, secret_type=SecretType.FILE, location="/a.pem") - self.assertEqual(operation.to_dict(), {"op": "delete", "type": "file", "location": "/a.pem"}) - - def test_create_and_update_require_value(self): - for op in ("create", "update"): - with self.subTest(op=op): - with self.assertRaises(ValueError) as context: - SecretOperation.from_dict({"op": op, "type": "env", "location": "API_KEY"}) - self.assertIn(f"value is required for a `{op}` operation", str(context.exception)) - - def test_delete_rejects_value(self): - with self.assertRaises(ValueError) as context: - SecretOperation.from_dict({"op": "delete", "type": "env", "location": "API_KEY", "value": "v"}) - self.assertIn("value must not be set for a `delete` operation", str(context.exception)) - - -class TestPatchSecretsCollection(unittest.TestCase): - """Test the PATCH-backed partial update of a secrets collection.""" - - def setUp(self): - self.app = Application(id="my-app", client=Client(api_key="test-key")) - - def test_metadata_only(self): - with patch.object(Client, "request", return_value=_response(MASKED_COLLECTION)) as mock_request: - collection = self.app.patch_secrets_collection("sc-1", name="New Name", description="New Description") - - mock_request.assert_called_once_with( - method="PATCH", - endpoint="v1/applications/my-app/secrets/sc-1", - payload={"name": "New Name", "description": "New Description"}, - ) - self.assertIsInstance(collection, SecretsCollection) - - def test_operations_from_models_and_dicts(self): - operations = [ - SecretOperation(op=SecretOperationType.CREATE, secret_type=SecretType.ENV, location="NEW", value="a"), - {"op": "update", "type": "env", "location": "API_KEY", "value": "b"}, - {"op": "delete", "type": "file", "location": "/old.pem"}, - ] - with patch.object(Client, "request", return_value=_response(MASKED_COLLECTION)) as mock_request: - self.app.patch_secrets_collection("sc-1", operations=operations) - - mock_request.assert_called_once_with( - method="PATCH", - endpoint="v1/applications/my-app/secrets/sc-1", - payload={ - "operations": [ - {"op": "create", "type": "env", "location": "NEW", "value": "a"}, - {"op": "update", "type": "env", "location": "API_KEY", "value": "b"}, - {"op": "delete", "type": "file", "location": "/old.pem"}, - ] - }, - ) - - def test_same_location_with_different_types_is_allowed(self): - operations = [ - {"op": "delete", "type": "env", "location": "KEY"}, - {"op": "create", "type": "file", "location": "KEY", "value": "a"}, - ] - with patch.object(Client, "request", return_value=_response(MASKED_COLLECTION)) as mock_request: - self.app.patch_secrets_collection("sc-1", operations=operations) - - mock_request.assert_called_once() - - def test_invalid_requests_raise_without_calling_api(self): - cases = { - "nothing to change": ({}, "at least one of name, description, or operations"), - "empty operations": ({"operations": []}, "operations must not be an empty list"), - "duplicate secret": ( - { - "operations": [ - {"op": "delete", "type": "env", "location": "API_KEY"}, - {"op": "create", "type": "env", "location": "API_KEY", "value": "a"}, - ] - }, - "operation at index 1 targets the same secret", - ), - "invalid operation type": ( - {"operations": ["not-an-operation"]}, - "operation at index 0 must be either a SecretOperation or dict object", - ), - } - for case, (kwargs, message) in cases.items(): - with self.subTest(case=case): - with patch.object(Client, "request") as mock_request: - with self.assertRaises(ValueError) as context: - self.app.patch_secrets_collection("sc-1", **kwargs) - - self.assertIn(message, str(context.exception)) - mock_request.assert_not_called() - - class TestUpdateSecretsCollection(unittest.TestCase): """Test that update_secrets_collection never resends fetched secret values.""" From 445c0ed1deb9c9e64e510e07da2ebb832daea9df Mon Sep 17 00:00:00 2001 From: Ronessa Acquesta Date: Mon, 19 Oct 2026 07:16:15 -0400 Subject: [PATCH 3/4] feat(secrets): add --keep-existing to secrets collection update [NMV-1073] Add a keep_existing option to update_secrets_collection and a --keep-existing flag to `nextmv cloud secrets update`. When set, the provided secrets are upserted (updated if they exist, created otherwise) and existing secrets that are not provided are kept instead of deleted. The default remains a full replace. Co-Authored-By: Claude Opus 5.5 (1M context) --- nextmv/nextmv/cli/cloud/secrets/update.py | 22 ++++++++++++++++-- nextmv/nextmv/cloud/application/_secrets.py | 24 +++++++++++++++----- nextmv/tests/cloud/test_secrets.py | 25 +++++++++++++++++++++ 3 files changed, 64 insertions(+), 7 deletions(-) diff --git a/nextmv/nextmv/cli/cloud/secrets/update.py b/nextmv/nextmv/cli/cloud/secrets/update.py index 75a024c1..a2f4a63d 100644 --- a/nextmv/nextmv/cli/cloud/secrets/update.py +++ b/nextmv/nextmv/cli/cloud/secrets/update.py @@ -30,6 +30,10 @@ def update( metavar="DESCRIPTION", ), ] = None, + keep_existing: Annotated[ + bool, + typer.Option("--keep-existing", "-k", help="Keep the existing secrets that are not provided with --secrets."), + ] = False, name: Annotated[ str | None, typer.Option( @@ -58,7 +62,8 @@ def update( "Allowed values for [magenta]type[/magenta] are: " f"{enum_values(SecretType)}. " "Object format: [dim]{'type': type, 'location': location, 'value': value}[/dim]. " - "This will replace all existing secrets in the collection.", + "This will replace all existing secrets in the collection: existing secrets " + "not provided here will be removed, unless --keep-existing is set.", metavar="SECRETS", ), ] = None, @@ -70,7 +75,10 @@ def update( You can update the name, description, and/or secrets of an existing secrets collection. When updating secrets, all existing secrets will be - replaced with the new ones provided. + replaced with the new ones provided: existing secrets that are not + provided will be removed, unless --keep-existing is set. Use + --keep-existing to only add or update the provided secrets, keeping the + rest of the existing ones. Secrets are provided as JSON objects using the --secrets flag, following the same format as the create command. You can provide secrets as: @@ -110,6 +118,12 @@ def update( --secrets-collection-id api-keys \\ --secrets '[{"type": "env", "location": "API_KEY", "value": "new-value"}, {...}]'[/dim] + - Add or update a secret, keeping the rest of the existing secrets. + + $ [dim]nextmv cloud secrets update --app-id hare-app \\ + --secrets-collection-id api-keys --keep-existing \\ + --secrets '{"type": "env", "location": "NEW_KEY", "value": "new-value"}'[/dim] + - Update multiple attributes at once and save the result. $ [dim]nextmv cloud secrets update --app-id hare-app \\ @@ -122,6 +136,9 @@ def update( if name is None and description is None and secrets is None: error("Provide at least one option to update: --name, --description, or --secrets.") + if keep_existing and secrets is None: + error("--keep-existing can only be used together with --secrets.") + cloud_app, _ = build_cloud_app(app_id=app_id, profile=profile) # Build the secrets list if provided @@ -135,6 +152,7 @@ def update( name=name, description=description, secrets=secrets_list, + keep_existing=keep_existing, ) success( f"Secrets collection [magenta]{secrets_collection_id}[/magenta] updated successfully " diff --git a/nextmv/nextmv/cloud/application/_secrets.py b/nextmv/nextmv/cloud/application/_secrets.py index 96247c1d..f1ecf75c 100644 --- a/nextmv/nextmv/cloud/application/_secrets.py +++ b/nextmv/nextmv/cloud/application/_secrets.py @@ -226,6 +226,7 @@ def update_secrets_collection( name: str | None = None, description: str | None = None, secrets: list[Secret | dict[str, Any]] | None = None, + keep_existing: bool = False, ) -> SecretsCollectionSummary: """ Update a secrets collection. @@ -240,7 +241,9 @@ def update_secrets_collection( updated, and the secrets in the collection are left untouched. If `secrets` is provided, all the existing secrets in the collection are replaced with the given ones: secrets with a matching type and - location are updated, new ones are created, and the rest are deleted. + location are updated, new ones are created, and the rest are deleted, + unless `keep_existing` is set, in which case the existing secrets that + are not provided are kept in the collection. Parameters ---------- @@ -254,6 +257,10 @@ def update_secrets_collection( Optional list of secrets that replaces all the existing secrets in the collection. Each secret should be an instance of the Secret class containing a type, location, and value. + keep_existing : bool, default=False + Whether to keep the existing secrets that are not provided in + `secrets`, instead of deleting them. Has no effect if `secrets` is + not provided. Returns ------- @@ -289,6 +296,12 @@ class containing a type, location, and value. ... ) >>> print(updated_collection.id) 'api-secrets' + >>> # Add or update a secret, keeping the rest of the existing secrets + >>> updated_collection = app.update_secrets_collection( + ... secrets_collection_id="api-secrets", + ... secrets=[Secret(secret_type=SecretType.ENV, location="NEW_KEY", value="new-value")], + ... keep_existing=True, + ... ) """ if name is None and description is None and (secrets is None or len(secrets) == 0): @@ -325,10 +338,11 @@ class containing a type, location, and value. } for secret in new_secrets ] - operations.extend( - {"op": "delete", "type": secret_type.value, "location": location} - for secret_type, location in sorted(existing_keys - new_keys) - ) + if not keep_existing: + operations.extend( + {"op": "delete", "type": secret_type.value, "location": location} + for secret_type, location in sorted(existing_keys - new_keys) + ) payload["operations"] = operations response = self.client.request( diff --git a/nextmv/tests/cloud/test_secrets.py b/nextmv/tests/cloud/test_secrets.py index 3669b415..2a39eb33 100644 --- a/nextmv/tests/cloud/test_secrets.py +++ b/nextmv/tests/cloud/test_secrets.py @@ -87,6 +87,31 @@ def test_with_secrets_replaces_via_patch_operations(self): ) self.assertNotIn(MASKED_VALUE, str(payload)) + def test_with_secrets_keep_existing_skips_deletes(self): + responses = [_response(MASKED_COLLECTION), _response(MASKED_COLLECTION)] + with patch.object(Client, "request", side_effect=responses) as mock_request: + self.app.update_secrets_collection( + "sc-1", + secrets=[ + Secret(secret_type=SecretType.ENV, location="API_KEY", value="new-api-key"), + {"type": "file", "location": "/cert.pem", "value": "cert"}, + ], + keep_existing=True, + ) + + _, patch_call = mock_request.call_args_list + payload = patch_call.kwargs["payload"] + self.assertEqual( + payload, + { + "operations": [ + {"op": "update", "type": "env", "location": "API_KEY", "value": "new-api-key"}, + {"op": "create", "type": "file", "location": "/cert.pem", "value": "cert"}, + ], + }, + ) + self.assertNotIn(MASKED_VALUE, str(payload)) + def test_never_uses_put(self): responses = [_response(MASKED_COLLECTION), _response(MASKED_COLLECTION), _response(MASKED_COLLECTION)] with patch.object(Client, "request", side_effect=responses) as mock_request: From c155759faf257c1989afd2596c333ab2c6ce2601 Mon Sep 17 00:00:00 2001 From: Ronessa Acquesta Date: Mon, 19 Oct 2026 08:55:56 -0400 Subject: [PATCH 4/4] fix(secrets): reject duplicate secrets in secrets collection update [NMV-1073] Each secret becomes its own PATCH operation, so passing the same (type, location) twice would rely on how the server handles several operations on the same key. Raise ValueError before any request instead. Co-Authored-By: Claude Opus 5.5 (1M context) --- nextmv/nextmv/cloud/application/_secrets.py | 16 +++++++++++++--- nextmv/tests/cloud/test_secrets.py | 11 +++++++++++ 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/nextmv/nextmv/cloud/application/_secrets.py b/nextmv/nextmv/cloud/application/_secrets.py index f1ecf75c..deb37a9a 100644 --- a/nextmv/nextmv/cloud/application/_secrets.py +++ b/nextmv/nextmv/cloud/application/_secrets.py @@ -2,6 +2,7 @@ Application mixin for managing app secrets. """ +from collections import Counter from typing import TYPE_CHECKING, Any from nextmv.cloud.secrets import Secret, SecretsCollection, SecretsCollectionSummary @@ -270,8 +271,8 @@ class containing a type, location, and value. Raises ------ ValueError - If there is nothing to update, or if a secret is not a Secret or - dict object. + If there is nothing to update, if a secret is not a Secret or + dict object, or if two secrets share the same type and location. requests.HTTPError If the response status code is not 2xx. @@ -323,13 +324,22 @@ class containing a type, location, and value. else: raise ValueError(f"secret at index {ix} must be either a Secret or dict object") + # Each secret becomes its own operation, so duplicated keys are + # rejected upfront instead of relying on how the server handles + # several operations on the same key. + keys = [(secret.secret_type.value, secret.location) for secret in new_secrets] + if len(set(keys)) != len(keys): + duplicates = sorted(key for key, count in Counter(keys).items() if count > 1) + raise ValueError(f"duplicate secrets (type, location) are not allowed: {duplicates}") + + new_keys = {(secret.secret_type, secret.location) for secret in new_secrets} + # Replacing all the secrets is expressed as partial-update # operations against the keys of the existing secrets. Only the # keys of the fetched secrets are used: their values, which are # masked, are never sent back to the server. collection = self.secrets_collection(secrets_collection_id) existing_keys = {(secret.secret_type, secret.location) for secret in collection.secrets} - new_keys = {(secret.secret_type, secret.location) for secret in new_secrets} operations = [ { diff --git a/nextmv/tests/cloud/test_secrets.py b/nextmv/tests/cloud/test_secrets.py index 2a39eb33..958dd4ad 100644 --- a/nextmv/tests/cloud/test_secrets.py +++ b/nextmv/tests/cloud/test_secrets.py @@ -131,6 +131,17 @@ def test_invalid_secret_raises_before_any_request(self): mock_request.assert_not_called() + def test_duplicate_secret_raises_before_any_request(self): + secrets = [ + Secret(secret_type=SecretType.ENV, location="API_KEY", value="v1"), + {"type": "env", "location": "API_KEY", "value": "v2"}, + ] + with patch.object(Client, "request") as mock_request: + with self.assertRaisesRegex(ValueError, "duplicate secret"): + self.app.update_secrets_collection("sc-1", secrets=secrets) + + mock_request.assert_not_called() + if __name__ == "__main__": unittest.main()