Skip to content

Commit

Permalink
Implement SSL (#6)
Browse files Browse the repository at this point in the history
Introduce backwards compatible SSL.

- [script.py] Add optional argument for ssl-private_key, ssl-public_key and ssl-ca
- [web.py] Add optional ssl_context
- [conftest.py] Pytest utilities to test ssl
- [script_test.py/web_test.py] Add ssl testing
  • Loading branch information
argysamo authored Oct 23, 2023
1 parent 7ccc5d6 commit dc6fe22
Show file tree
Hide file tree
Showing 7 changed files with 270 additions and 34 deletions.
9 changes: 8 additions & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Usage
-----

The library provides a ``PrometheusExporterScript`` class that serves as an
entry point to create services that export Prometheus metrics via an HTTP
entry point to create services that export Prometheus metrics via an HTTP(s)
endpoint.

Creating a new exporter is just a matter of subclassing
Expand Down Expand Up @@ -79,6 +79,9 @@ Exporter command-line
-L {CRITICAL,ERROR,WARNING,INFO,DEBUG}, --log-level {CRITICAL,ERROR,WARNING,INFO,DEBUG}
minimum level for log messages (default: WARNING)
--process-stats include process stats in metrics (default: False)
--ssl-private-key full path to the ssl private key
--ssl-public-key full path to the ssl public key
--ssl-ca full path to the ssl certificate authority (CA)
Further options can be added by implementing ``configure_argument_parser()``,
Expand All @@ -87,6 +90,10 @@ which receives the ``argparse.ArgumentParser`` instance used by the script.
The ``script`` variable from the example above can be referenced in
``pyproject.toml`` to generate the script, like

In order to serve metrics on the HTTPs endpoint both ``ssl-private-key`` and
``ssl-public-key`` need to be define. The ssl certificate authority
(i.e. ``ssl-ca``) is optional.

.. code:: toml
[project.scripts]
Expand Down
36 changes: 36 additions & 0 deletions prometheus_aioexporter/script.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import argparse
from collections.abc import Iterable
import logging
import ssl
import sys
from typing import IO

Expand Down Expand Up @@ -134,6 +135,21 @@ def get_parser(self) -> argparse.ArgumentParser:
action="store_true",
help="include process stats in metrics",
)
parser.add_argument(
"--ssl-private-key",
type=argparse.FileType("r"),
help="full path to the ssl private key",
)
parser.add_argument(
"--ssl-public-key",
type=argparse.FileType("r"),
help="full path to the ssl public key",
)
parser.add_argument(
"--ssl-ca",
type=argparse.FileType("r"),
help="full path to the ssl certificate authority (CA)",
)
self.configure_argument_parser(parser)
return parser

Expand Down Expand Up @@ -164,6 +180,25 @@ def _configure_registry(self, include_process_stats: bool = False) -> None:
ProcessCollector(registry=None)
)

def _get_ssl_context(
self, args: argparse.Namespace
) -> ssl.SSLContext | None:
if args.ssl_private_key is None or args.ssl_public_key is None:
return None
cafile = None
if args.ssl_ca:
cafile = args.ssl_ca.name
args.ssl_ca.close()
ssl_context = ssl.create_default_context(
purpose=ssl.Purpose.CLIENT_AUTH, cafile=cafile
)
ssl_context.load_cert_chain(
args.ssl_public_key.name, args.ssl_private_key.name
)
args.ssl_public_key.close()
args.ssl_private_key.close()
return ssl_context

def _get_exporter(self, args: argparse.Namespace) -> PrometheusExporter:
"""Return a :class:`PrometheusExporter` configured with args."""
exporter = PrometheusExporter(
Expand All @@ -173,6 +208,7 @@ def _get_exporter(self, args: argparse.Namespace) -> PrometheusExporter:
args.port,
self.registry,
metrics_path=args.metrics_path,
ssl_context=self._get_ssl_context(args),
)
exporter.app.on_startup.append(self.on_application_startup)
exporter.app.on_shutdown.append(self.on_application_shutdown)
Expand Down
14 changes: 12 additions & 2 deletions prometheus_aioexporter/web.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Callable,
Iterable,
)
from ssl import SSLContext
from textwrap import dedent

from aiohttp.web import (
Expand All @@ -28,12 +29,13 @@ class PrometheusExporter:
"""Export Prometheus metrics via a web application."""

name: str
descrption: str
description: str
hosts: list[str]
port: int
register: MetricsRegistry
app: Application
metrics_path: str
ssl_context: SSLContext | None = None

_update_handler: UpdateHandler | None = None

Expand All @@ -45,6 +47,7 @@ def __init__(
port: int,
registry: MetricsRegistry,
metrics_path: str = "/metrics",
ssl_context: SSLContext | None = None,
) -> None:
self.name = name
self.description = description
Expand All @@ -53,6 +56,7 @@ def __init__(
self.registry = registry
self.metrics_path = metrics_path
self.app = self._make_application()
self.ssl_context = ssl_context

def set_metric_update_handler(self, handler: UpdateHandler) -> None:
"""Set a handler to update metrics.
Expand All @@ -74,6 +78,7 @@ def run(self) -> None:
port=self.port,
print=lambda *args, **kargs: None,
access_log_format='%a "%r" %s %b "%{Referrer}i" "%{User-Agent}i"',
ssl_context=self.ssl_context,
)

def _make_application(self) -> Application:
Expand All @@ -90,7 +95,12 @@ async def _log_startup_message(self, app: Application) -> None:
for host in self.hosts:
if ":" in host:
host = f"[{host}]"
self.app.logger.info(f"Listening on http://{host}:{self.port}")
protocol = "http"
if self.ssl_context:
protocol = "https"
self.app.logger.info(
f"Listening on {protocol}://{host}:{self.port}"
)

async def _handle_home(self, request: Request) -> Response:
"""Home page request handler."""
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ testing = [
"pytest-aiohttp",
"pytest-asyncio",
"pytest-mock",
"trustme",
]
[project.urls]
changelog = "https://github.com/albertodonato/prometheus-aioexporter/blob/main/CHANGES.rst"
Expand Down
48 changes: 48 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import ssl

import pytest
import trustme


@pytest.fixture
def ca():
yield trustme.CA()


@pytest.fixture
def tls_ca_path(ca):
with ca.cert_pem.tempfile() as ca_cert_pem:
yield ca_cert_pem


@pytest.fixture
def tls_certificate(ca):
yield ca.issue_cert("localhost", "127.0.0.1", "::1")


@pytest.fixture
def tls_public_key_path(tls_certificate):
"""Provide a certificate chain PEM file path via fixture."""
with tls_certificate.private_key_and_cert_chain_pem.tempfile() as cert_pem:
yield cert_pem


@pytest.fixture
def tls_private_key_path(tls_certificate):
"""Provide a certificate private key PEM file path via fixture."""
with tls_certificate.private_key_pem.tempfile() as cert_key_pem:
yield cert_key_pem


@pytest.fixture
def ssl_context(tls_certificate):
ssl_ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
tls_certificate.configure_cert(ssl_ctx)
yield ssl_ctx


@pytest.fixture
def ssl_context_server(tls_public_key_path, ca):
ssl_ctx = ssl.create_default_context(purpose=ssl.Purpose.SERVER_AUTH)
ca.configure_trust(ssl_ctx)
yield ssl_ctx
Loading

0 comments on commit dc6fe22

Please sign in to comment.