Skip to content

Commit e00edc4

Browse files
authored
Merge pull request #31 from nitrictech/feature/secrets
feat: add secrets service support
2 parents 4aeca36 + f3c6f04 commit e00edc4

4 files changed

Lines changed: 250 additions & 1 deletion

File tree

contracts

nitric/api/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
from nitric.api.queues import Queues, Task, FailedTask
2222
from nitric.api.storage import Storage
2323
from nitric.api.documents import Documents
24+
from nitric.api.secrets import Secrets
2425

2526
__all__ = [
2627
"Events",
@@ -31,4 +32,5 @@
3132
"Task",
3233
"FailedTask",
3334
"Topic",
35+
"Secrets",
3436
]

nitric/api/secrets.py

Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
#
2+
# Copyright (c) 2021 Nitric Technologies Pty Ltd.
3+
#
4+
# This file is part of Nitric Python 3 SDK.
5+
# See https://github.com/nitrictech/python-sdk for further info.
6+
#
7+
# Licensed under the Apache License, Version 2.0 (the "License");
8+
# you may not use this file except in compliance with the License.
9+
# You may obtain a copy of the License at
10+
#
11+
# http://www.apache.org/licenses/LICENSE-2.0
12+
#
13+
# Unless required by applicable law or agreed to in writing, software
14+
# distributed under the License is distributed on an "AS IS" BASIS,
15+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
# See the License for the specific language governing permissions and
17+
# limitations under the License.
18+
#
19+
from __future__ import annotations
20+
from dataclasses import dataclass
21+
from typing import Union
22+
23+
from nitric.utils import new_default_channel
24+
from nitric.proto.nitric.secret.v1 import SecretServiceStub, Secret as SecretMessage, SecretVersion as VersionMessage
25+
26+
27+
class Secrets(object):
28+
"""
29+
Nitric secrets management client.
30+
31+
This client insulates application code from stack specific secrets managements services.
32+
"""
33+
34+
def __init__(self):
35+
"""Construct a Nitric Storage Client."""
36+
self._channel = new_default_channel()
37+
self._secrets_stub = SecretServiceStub(channel=self._channel)
38+
39+
def __del__(self):
40+
# close the channel when this client is destroyed
41+
if self._channel is not None:
42+
self._channel.close()
43+
44+
def secret(self, name: str):
45+
"""Return a reference to a secret container from the connected secrets management service."""
46+
return SecretContainer(_secrets=self, name=name)
47+
48+
49+
def _secret_to_wire(secret: SecretContainer) -> SecretMessage:
50+
return SecretMessage(name=secret.name)
51+
52+
53+
@dataclass(frozen=True)
54+
class SecretContainer(object):
55+
"""A reference to a secret container, used to store and retrieve secret versions."""
56+
57+
_secrets: Secrets
58+
name: str
59+
60+
async def put(self, value: Union[str, bytes]) -> SecretVersion:
61+
"""
62+
Create a new secret version, making it the latest and storing the provided value.
63+
64+
:param value: the secret value to store
65+
"""
66+
if isinstance(value, str):
67+
value = bytes(value, "utf-8")
68+
69+
secret_message = _secret_to_wire(self)
70+
71+
response = await self._secrets._secrets_stub.put(secret=secret_message, value=value)
72+
return self.version(version=response.secret_version.version)
73+
74+
def version(self, version: str):
75+
"""
76+
Return a reference to a specific version of a secret.
77+
78+
Can be used to retrieve the secret value associated with the version.
79+
"""
80+
return SecretVersion(_secrets=self._secrets, secret=self, id=version)
81+
82+
def latest(self):
83+
"""
84+
Return a reference to the 'latest' secret version.
85+
86+
Note: using 'access' on this reference may return different values between requests if a
87+
new version is created between access calls.
88+
"""
89+
return self.version("latest")
90+
91+
92+
def _secret_version_to_wire(version: SecretVersion) -> VersionMessage:
93+
return VersionMessage(_secret_to_wire(version.secret), version=version.id)
94+
95+
96+
@dataclass(frozen=True)
97+
class SecretVersion(object):
98+
"""A reference to a version of a secret, used to access the value of the version."""
99+
100+
_secrets: Secrets
101+
secret: SecretContainer
102+
id: str
103+
104+
async def access(self) -> SecretValue:
105+
"""Return the value stored against this version of the secret."""
106+
version_message = _secret_version_to_wire(self)
107+
response = await self._secrets._secrets_stub.access(secret_version=version_message)
108+
109+
# Construct a new SecretVersion if the response version id doesn't match this reference.
110+
# This ensures calls to access from the 'latest' version return new version objects
111+
# with a fixed version id.
112+
static_version = (
113+
self
114+
if response.secret_version.version == self.id
115+
else SecretVersion(_secrets=self._secrets, secret=self.secret, id=response.secret_version.version)
116+
)
117+
118+
return SecretValue(version=static_version, value=response.value)
119+
120+
121+
@dataclass(frozen=True)
122+
class SecretValue(object):
123+
"""Represents the value of a secret, tied to a specific version."""
124+
125+
# The version containing this value. Never 'latest', always a specific version.
126+
version: SecretVersion
127+
value: bytes
128+
129+
def __str__(self) -> str:
130+
return self.value.decode("utf-8")
131+
132+
def __bytes__(self) -> bytes:
133+
return self.value
134+
135+
def as_string(self):
136+
"""Return the content of this secret value as a string."""
137+
return str(self)
138+
139+
def as_bytes(self):
140+
"""Return the content of this secret value."""
141+
return bytes(self)

tests/api/test_secrets.py

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
#
2+
# Copyright (c) 2021 Nitric Technologies Pty Ltd.
3+
#
4+
# This file is part of Nitric Python 3 SDK.
5+
# See https://github.com/nitrictech/python-sdk for further info.
6+
#
7+
# Licensed under the Apache License, Version 2.0 (the "License");
8+
# you may not use this file except in compliance with the License.
9+
# You may obtain a copy of the License at
10+
#
11+
# http://www.apache.org/licenses/LICENSE-2.0
12+
#
13+
# Unless required by applicable law or agreed to in writing, software
14+
# distributed under the License is distributed on an "AS IS" BASIS,
15+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
# See the License for the specific language governing permissions and
17+
# limitations under the License.
18+
#
19+
from unittest import IsolatedAsyncioTestCase
20+
from unittest.mock import patch, AsyncMock
21+
22+
from nitric.api import Secrets
23+
from nitric.api.secrets import SecretValue
24+
from nitric.proto.nitric.secret.v1 import SecretPutResponse, SecretVersion, Secret, SecretAccessResponse
25+
26+
27+
class Object(object):
28+
pass
29+
30+
31+
class SecretsClientTest(IsolatedAsyncioTestCase):
32+
async def test_put(self):
33+
mock_put = AsyncMock()
34+
mock_response = SecretPutResponse(
35+
secret_version=SecretVersion(secret=Secret(name="test-secret"), version="test-version")
36+
)
37+
mock_put.return_value = mock_response
38+
39+
with patch("nitric.proto.nitric.secret.v1.SecretServiceStub.put", mock_put):
40+
secret = Secrets().secret("test-secret")
41+
result = await secret.put(b"a test secret value")
42+
43+
# Check expected values were passed to Stub
44+
mock_put.assert_called_once()
45+
assert mock_put.call_args.kwargs["secret"] == Secret(name="test-secret")
46+
assert mock_put.call_args.kwargs["value"] == b"a test secret value"
47+
48+
# Check the returned value
49+
assert result.id == "test-version"
50+
assert result.secret.name == "test-secret"
51+
52+
async def test_put_string(self):
53+
mock_put = AsyncMock()
54+
mock_response = SecretPutResponse(
55+
secret_version=SecretVersion(secret=Secret(name="test-secret"), version="test-version")
56+
)
57+
mock_put.return_value = mock_response
58+
59+
with patch("nitric.proto.nitric.secret.v1.SecretServiceStub.put", mock_put):
60+
secret = Secrets().secret("test-secret")
61+
await secret.put("a test secret value") # string, not bytes
62+
63+
# Check expected values were passed to Stub
64+
mock_put.assert_called_once()
65+
assert mock_put.call_args.kwargs["value"] == b"a test secret value" # value should still be bytes when sent.
66+
67+
async def test_latest(self):
68+
version = Secrets().secret("test-secret").latest()
69+
70+
assert version.secret.name == "test-secret"
71+
assert version.id == "latest"
72+
73+
async def test_access(self):
74+
mock_access = AsyncMock()
75+
mock_response = SecretAccessResponse(
76+
secret_version=SecretVersion(secret=Secret(name="test-secret"), version="response-version"),
77+
value=b"super secret value",
78+
)
79+
mock_access.return_value = mock_response
80+
81+
with patch("nitric.proto.nitric.secret.v1.SecretServiceStub.access", mock_access):
82+
version = Secrets().secret("test-secret").latest()
83+
result = await version.access()
84+
85+
# Check expected values were passed to Stub
86+
mock_access.assert_called_once()
87+
assert mock_access.call_args.kwargs["secret_version"] == SecretVersion(
88+
secret=Secret(name="test-secret"),
89+
version="latest",
90+
)
91+
92+
# Check the returned value
93+
assert result.version.id == "response-version"
94+
assert result.value == b"super secret value"
95+
96+
async def test_value_to_string(self):
97+
value = SecretValue(version=None, value=b"secret value")
98+
99+
assert value.as_string() == "secret value"
100+
assert str(value) == "secret value"
101+
102+
async def test_value_to_bytes(self):
103+
value = SecretValue(version=None, value=b"secret value")
104+
105+
assert value.as_bytes() == b"secret value"
106+
assert bytes(value) == b"secret value"

0 commit comments

Comments
 (0)