Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions nextmv/nextmv/cli/cloud/secrets/update.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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,
Expand All @@ -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:
Expand Down Expand Up @@ -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 \\
Expand All @@ -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
Expand All @@ -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 "
Expand Down
79 changes: 64 additions & 15 deletions nextmv/nextmv/cloud/application/_secrets.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -234,6 +235,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,
unless `keep_existing` is set, in which case the existing secrets that
are not provided are kept in the collection.

Parameters
----------
secrets_collection_id : str
Expand All @@ -243,8 +254,13 @@ 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.
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
-------
Expand All @@ -254,17 +270,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",
Expand All @@ -274,30 +296,57 @@ def update_secrets_collection(
... )
>>> 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,
... )
"""

collection = self.secrets_collection(secrets_collection_id)
collection_dict = collection.to_dict()
payload = collection_dict.copy()
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")

payload: dict[str, Any] = {}
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 = []
new_secrets: list[Secret] = []
for ix, secret in enumerate(secrets):
if isinstance(secret, dict):
secrets_dicts.append(secret)
new_secrets.append(Secret.from_dict(secret))
elif isinstance(secret, Secret):
secrets_dicts.append(secret.to_dict())
new_secrets.append(secret)
else:
raise ValueError(f"secret at index {ix} must be either a Secret or dict object")

payload["secrets"] = secrets_dicts
# 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}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Minor · non-blocking

If the caller passes the same (type, location) twice (e.g. a copy-paste in --secrets '[...]'), this emits two update/create ops for the same key. With the old PUT the server just got the list. Now the result depends on how C2 handles duplicate ops in one PATCH: an error, last-one-wins, or a partially applied request if it isn't atomic. A cheap client-side check would make this deterministic, e.g. raising ValueError("duplicate secret ...") when len(new_keys) != len(new_secrets), before the GET. Non-blocking: fine to skip if C2 already rejects duplicates atomically.

🤖 Kevin (PR review bot)


operations = [
{
"op": "update" if (secret.secret_type, secret.location) in existing_keys else "create",
**secret.to_dict(),
}
for secret in new_secrets
]
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(
method="PUT",
method="PATCH",
endpoint=f"{self.endpoint}/secrets/{secrets_collection_id}",
payload=payload,
)
Expand Down
136 changes: 136 additions & 0 deletions nextmv/tests/cloud/test_secrets.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
import unittest
from unittest.mock import MagicMock, patch

from nextmv.cloud import Application, Client
from nextmv.cloud.secrets import Secret, 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 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_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:
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()
Loading