Skip to content

Commit a2be0e2

Browse files
committed
Use TLS in CLI client
Signed-off-by: Mathias L. Baumann <[email protected]>
1 parent fb20314 commit a2be0e2

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

RELEASE_NOTES.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
## New Features
1313

14-
<!-- Here goes the main new features and examples or instructions on how to use them -->
14+
* TLS is now enabled by default for the CLI client.
1515

1616
## Bug Fixes
1717

src/frequenz/client/dispatch/__main__.py

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,46 @@
3636
DEFAULT_DISPATCH_API_PORT = 50051
3737

3838

39+
def ssl_channel_credentials_from_files(
40+
root_cert_path: str | None = None,
41+
client_cert_path: str | None = None,
42+
client_key_path: str | None = None,
43+
) -> grpc.ChannelCredentials:
44+
"""Create credentials for use with an SSL-enabled Channel.
45+
46+
Using the provided certificate and key files.
47+
48+
Args:
49+
root_cert_path: Path to the PEM-encoded root certificates file,
50+
or None to retrieve them from a default location chosen by gRPC runtime.
51+
client_cert_path: Path to the PEM-encoded client certificate file.
52+
client_key_path: Path to the PEM-encoded client private key file.
53+
54+
Returns:
55+
A ChannelCredentials for use with an SSL-enabled Channel.
56+
"""
57+
root_certificates = None
58+
if root_cert_path is not None:
59+
with open(root_cert_path, "rb") as f:
60+
root_certificates = f.read()
61+
62+
certificate_chain = None
63+
if client_cert_path is not None:
64+
with open(client_cert_path, "rb") as f:
65+
certificate_chain = f.read()
66+
67+
private_key = None
68+
if client_key_path is not None:
69+
with open(client_key_path, "rb") as f:
70+
private_key = f.read()
71+
72+
return grpc.ssl_channel_credentials(
73+
root_certificates=root_certificates,
74+
private_key=private_key,
75+
certificate_chain=certificate_chain,
76+
)
77+
78+
3979
def get_client(*, host: str, port: int, key: str) -> Client:
4080
"""Get a new client instance.
4181
@@ -47,7 +87,10 @@ def get_client(*, host: str, port: int, key: str) -> Client:
4787
Returns:
4888
Client: A new client instance.
4989
"""
50-
channel = grpc.aio.insecure_channel(f"{host}:{port}")
90+
channel = grpc.aio.secure_channel(
91+
f"{host}:{port}",
92+
credentials=ssl_channel_credentials_from_files(),
93+
)
5194
return Client(grpc_channel=channel, svc_addr=f"{host}:{port}", key=key)
5295

5396

0 commit comments

Comments
 (0)