Metadata-Version: 2.4
Name: mqtts_demo_helper
Version: 1.1.1
Summary: Offline mutual-TLS MQTT broker demonstration and test helpers
Author: Avnet
Author-email: Laurent Lagosanto <laurent.lagosanto@avnet.eu>
License-Expression: Apache-2.0
Project-URL: License, https://www.apache.org/licenses/LICENSE-2.0
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: amqtt
Requires-Dist: paho-mqtt
Requires-Dist: cryptography>=44.0
Requires-Dist: colorama
Provides-Extra: test
Requires-Dist: pytest; extra == "test"
Requires-Dist: pytest-asyncio; extra == "test"
Requires-Dist: pytest-cov; extra == "test"
Dynamic: license-file

# mqtts_demo_helper

Offline Mutual-TLS MQTT Broker Demo

Copyright 2026 Avnet, Inc. Licensed under the Apache License, Version 2.0.
See [LICENSE](LICENSE) and [NOTICE](NOTICE).

Authors: Avnet; Laurent Lagosanto <laurent.lagosanto@avnet.eu>.

This project is primarily a local MQTT-over-TLS (MQTTS) demonstration/test broker.
It shows X.509 client-certificate authentication, identity-based authorization,
and topic mappings that resemble Generic MQTT, AWS IoT Core, and Azure IoT Hub.
The optional device simulator under `examples/` is only a convenient test
client; the broker is the main application.

See [RELEASE_NOTES.md](RELEASE_NOTES.md) for the version history and upgrade
notes.

The broker runs on one PC without Docker, cloud services, or a database. After
installing the Python dependencies, all communication and tests are local.

> This is a learning/demo broker, not a production replacement for AWS IoT
> Core, Azure IoT Hub, or an internet-facing MQTT service.

## What the broker demonstrates

- TLS with a broker certificate and required client certificates (mTLS)
- Device identity extracted from the client certificate, not the MQTT username
- Per-identity authorization: publish only to that device's D2C topic and
  subscribe only to its C2D topic
- Generic, AWS-style shadow, and Azure-style topic names
- Delayed echo of accepted D2C messages to the matching C2D topic
- Broker-owned CA and server certificates persisted under `broker-pki/`

Run three isolated broker processes, one per TLS profile:

| Profile | Default port | TLS policy |
|---|---:|---|
| RSA | `8883` | TLS 1.2 only; classical groups |
| ECDSA | `18883` | TLS 1.2 only; classical groups |
| ML-DSA-87 | `28883` | TLS 1.3 only; `MLKEM768` only |

Each process binds `0.0.0.0` by default. Broker PKI is generated on first start
and reused on subsequent starts.

## Project layout

```text
demo_mqtt_broker.py          Broker CLI entry point
mqtt_demo/
  broker.py                  AMQTT broker and lifecycle
  auth.py                    Certificate authentication and topic ACL
  echo.py                    Broker events and delayed echoes
  pki.py                     CA and certificate generation/validation
  tls.py                     TLS profile selection and requirements
  cli.py                     Shared certificate and TLS command-line options
  topics.py                  Topic mapping and authorization rules
  models.py                  Shared data models
  logging_utils.py           Categorized logging
  constants.py               Defaults
examples/
  create_device_certificate.py  Create a test certificate and trust its CA
  device_simulator.py        Optional MQTT test client
tests/                       Local PKI, TLS, authorization, echo, load tests
.vscode/
  launch.json                Broker-first run configurations
pyproject.toml                PyPI package metadata and CLI entry points
LICENSE                       Apache License 2.0
NOTICE                        Avnet and author attribution
```

## Requirements and installation

- Python 3.12 or newer
- Free local TCP ports 8883, 18883, and 28883 (or select different ports with
  `--port`)
- OpenSSL 3.5+ and `cryptography` 44.0+ for the ML-KEM-768 / ML-DSA-87 profile;
  RSA and ECDSA use TLS 1.2 with classical groups

Windows PowerShell:

```powershell
python -m venv .venv
.venv\Scripts\activate
pip install --upgrade pip
pip install -r requirements.txt
```

To install the packaged project and its test extras from a local checkout:

```powershell
python -m pip install ".[test]"
```

After publication, install it from PyPI with:

```powershell
python -m pip install mqtts_demo_helper
```

The distribution provides the `demo-mqtt-broker`,
`demo-mqtt-test-client`, and `demo-mqtt-create-device-certificate` commands.

## Publishing to PyPI

The GitHub Actions workflow runs tests on Linux and Windows and builds the
distribution. Publishing a GitHub Release triggers a PyPI upload after the
tests and package checks pass; ordinary pushes and pull requests do not publish.

Before the first release, configure a PyPI Trusted Publisher for
`mqtts_demo_helper` (or a pending publisher if the project does not yet exist):

1. In PyPI's publishing settings, select GitHub as the publisher and enter
   owner `lagosantol`, repository `mqtts_demo_helper`, workflow `workflow.yml`,
   and environment `pypi`.
2. In GitHub, create the `pypi` environment under repository settings and
   configure any desired environment protection rules.
3. Update the version in `pyproject.toml` to a version not already on PyPI,
   push that change, and publish a GitHub Release from that commit.

The workflow uses GitHub's OIDC identity to authenticate with PyPI; no PyPI
API token needs to be stored in the repository. See the
[PyPI Trusted Publishers documentation](https://docs.pypi.org/trusted-publishers/).

Linux/macOS:

```bash
python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt
```

## Start the three brokers, then add a client CA

Each broker process creates the shared `client-ca/` folder if it does not
already exist. The brokers can start with an empty trust folder; client
connections will be accepted only after a trusted client CA is added. Open
three PowerShell terminals and start one profile in each:

```powershell
python demo_mqtt_broker.py --mode generic --client-ca client-ca --tls-profile rsa
python demo_mqtt_broker.py --mode generic --client-ca client-ca --tls-profile ecdsa
python demo_mqtt_broker.py --mode generic --client-ca client-ca --tls-profile pqc
```

The CLI selects the matching bundled OpenSSL policy before TLS is initialized.
The default ports are `8883` (RSA), `18883` (ECDSA), and `28883` (PQC). Set
`--port` to override a profile's port. These policies cannot be combined in one
process: the OpenSSL group policy is process-wide. The broker fails closed if
an incompatible `OPENSSL_CONF` is set or TLS was initialized too early.

Each process creates its own CA and server identity under
`broker-pki/rsa/`, `broker-pki/ecdsa/`, and `broker-pki/pqc/`. Their default
key parameters are RSA 2048, ECDSA `secp256r1`, and ML-DSA-87. Public CA
certificates are written as `broker-pki/<profile>/broker-ca.crt`; clients use
the CA matching their selected profile. Private keys remain local; do not
share them.

Choose the RSA key size and ECDSA curve while creating the identities. Apply
these settings when starting the matching broker process:

```powershell
python demo_mqtt_broker.py --client-ca client-ca --tls-profile rsa --rsa-key-size 3072
python demo_mqtt_broker.py --client-ca client-ca --tls-profile ecdsa --ecdsa-curve secp384r1
```

`--rsa-key-size` accepts `2048`, `3072`, or `4096`; `--ecdsa-curve` accepts
`secp256r1` or `secp384r1`. Each identity's CA and server leaf use the
corresponding algorithm. Existing key material is reused only when it matches
the selected parameters. Use a new `--broker-pki` directory when changing an
algorithm or key size.

Keep the broker running and create one device identity per TLS algorithm. Each
command adds its public client CA to the shared broker trust folder without
replacing the other profiles' CA:

```powershell
python -m examples.create_device_certificate --identity device-rsa --tls-profile rsa --device-pki device-pki/rsa --client-ca client-ca
python -m examples.create_device_certificate --identity device-ecdsa --tls-profile ecdsa --device-pki device-pki/ecdsa --client-ca client-ca
python -m examples.create_device_certificate --identity device-pqc --tls-profile pqc --device-pki device-pki/pqc --client-ca client-ca
```

The RSA key size and ECDSA curve can be selected with `--rsa-key-size` and
`--ecdsa-curve` on both the certificate-creation and simulator commands.

Run the three test clients in separate terminals. Each simulator selects its
profile's default port and sends the matching SNI:

```powershell
python -m examples.device_simulator --identity device-rsa --tls-profile rsa --device-pki device-pki/rsa --broker-pki broker-pki --broker localhost
python -m examples.device_simulator --identity device-ecdsa --tls-profile ecdsa --device-pki device-pki/ecdsa --broker-pki broker-pki --broker localhost
python -m examples.device_simulator --identity device-pqc --tls-profile pqc --device-pki device-pki/pqc --broker-pki broker-pki --broker localhost
```

RSA and ECDSA connections use TLS 1.2 only with classical key-exchange groups;
they do not offer or use ML-KEM. The PQC broker uses TLS 1.3 and the sole
`MLKEM768` group, so a full handshake requires ML-KEM-768 and cannot fall back
to a classical or hybrid group. The PQC broker and device certificates use
ML-DSA-87. OpenSSL 3.5+ on both PQC peers must support `MLKEM768`; otherwise
the handshake fails. Each client must trust the broker CA for its profile and
present a client certificate from a CA in `client-ca/`.

The simulator selects the bundled OpenSSL configuration from `--tls-profile`
before TLS starts. Other Python clients must set `OPENSSL_CONF` before starting
Python: use `mqtt_demo/openssl-classical.cnf` for RSA/ECDSA or
`mqtt_demo/openssl-pqc.cnf` for ML-KEM-768.

Each client subscribes to its C2D topic and publishes sinusoidal telemetry
every five seconds. The broker echoes accepted messages to the matching C2D
topic after the configured delay. Use Ctrl+C in each client terminal to stop
that client.

### Broker modes and topic access

Select one mode when starting the broker. Every client must use that same mode.

| Mode | Device publishes (D2C) | Device subscribes (C2D) |
|---|---|---|
| `generic` | `device/<identity>/d2c` | `device/<identity>/c2d` |
| `aws` | `$aws/things/<identity>/shadow/update` | `$aws/things/<identity>/shadow/update/delta` |
| `azure` | `devices/<identity>/messages/events/` | `devices/<identity>/messages/devicebound/` |

For example, start AWS-style topic behavior with:

```powershell
python demo_mqtt_broker.py --mode aws --client-ca client-ca --tls-profile rsa
python demo_mqtt_broker.py --mode aws --client-ca client-ca --tls-profile ecdsa
python demo_mqtt_broker.py --mode aws --client-ca client-ca --tls-profile pqc
```

An identity may publish only to its own D2C topic and subscribe only to its own
C2D topic. The broker derives the identity from the client X.509 certificate
(URI SAN, DNS SAN, then Common Name). Unauthorized topic access is denied and
logged.

### Broker options

```text
--mode {generic,aws,azure}   Topic convention (default: generic)
--client-ca PATH            PEM CA file/chain, or folder of PEM CA files (required)
--echo-delay SECONDS        Delay before echoing D2C messages (default: 3)
--host HOST                 Bind address (default: 0.0.0.0)
--port PORT                 TLS listener port (default by profile: 8883/18883/28883)
--broker-pki PATH           Broker certificate directory (default: broker-pki)
--tls-profile {rsa,ecdsa,pqc}  Single broker identity and TLS policy (default: rsa)
--rsa-key-size {2048,3072,4096}    RSA CA and leaf key size (default: 2048)
--ecdsa-curve {secp256r1,secp384r1} ECDSA CA and leaf curve (default: secp256r1)
```

The device simulator also accepts `--tls-profile`, `--rsa-key-size`, and
`--ecdsa-curve`, as well as `--port`, `--device-pki`, and `--broker-pki`.

## VS Code

Open **Run and Debug** and start each broker profile in its own terminal:

- `MQTT Broker (RSA, TLS 1.2)` on port `8883`
- `MQTT Broker (ECDSA, TLS 1.2)` on port `18883`
- `MQTT Broker (ML-DSA-87 + MLKEM768)` on port `28883`

Each broker process creates its profile identity and the shared `client-ca/`
directory. The device simulator selects its matching TLS policy from
`--tls-profile`.

Create `.venv` and install `requirements.txt` there before using Run and Debug.
Select that `.venv` interpreter in VS Code.

## Tests

The automated tests use temporary PKI directories and localhost. They cover
certificate generation, RSA/ECDSA TLS 1.2 connections, the strict MLKEM768
TLS 1.3 handshake, valid and rejected mTLS clients, per-device topic
authorization, mode-specific echoes, and ten simultaneous test devices.

```powershell
$env:OPENSSL_CONF = (Resolve-Path .\mqtt_demo\openssl-classical.cnf).Path
pytest -v -m "not pqc"
$env:OPENSSL_CONF = (Resolve-Path .\mqtt_demo\openssl-pqc.cnf).Path
pytest -v -m pqc
```
