Skip to main content

The Nacl Middleware

Documentation Status Python Tests

The Nacl Middleware is an aiohttp compatible middleware that provides NaCl encryption for authentication in both HTTP requests and websockets. It allows you to securely handle encrypted messages and sender’s public keys from query parameters. Upon successful decoding, it forwards the request to the appropriate handler, whether it’s a websocket or an HTTP request.

Usage

The middleware uses assymetric keys encryption and it is installed on the server. The middleware assumes that the client will be sending the following GET parameters:

parameter

Description

publicKey

The client’s public key

encryptedMessage

The encrypted message by the client for the server

Example Server Code

from aiohttp.web import Application, Response, run_app
from nacl_middleware import nacl_middleware, Nacl, MailBox

pynacl = Nacl()
public_key_hex = pynacl.decoded_public_key()
print(public_key_hex)

app = Application(middlewares=[
    nacl_middleware(pynacl.private_key)
])

async def thanks_handler(request):
    decrypted_message = request['decrypted_message']
    mail_box: MailBox = request['mail_box']
    if decrypted_message == 'Thank you!':
        text = 'You are welcome!'
    text = "Pardon me?"
    return Response(text = mail_box.box(text))

app.router.add_get('/handle_thanks', thanks_handler)

run_app(app)

Example Client Code

from aiohttp import ClientSession
from asyncio import run
from nacl_middleware import MailBox, Nacl

pynacl = Nacl()
server_hex_public_key = "cbe3b3cf345b24bd050db13bb5f1165f47f36f7151bbba9b27bdef0922674f4d"

async def main():
    mail_box = MailBox(pynacl.private_key, server_hex_public_key)

    def get_params(message):
        return {
            "publicKey": pynacl.decoded_public_key(),
            "encryptedMessage": mail_box.box(message)
        }

    async with ClientSession() as session:
        async with session.get('http://localhost:8080/handle_thanks', params=get_params('Thank you!')) as response:
            encryted_reply = await response.text()
            reply = mail_box.unbox(encryted_reply)
            print("Reply:", reply)

run(main())

Development

Project Configuration

To start, clone the project with:

git clone https://github.com/CosmicDNA/nacl_middleware

Then enter the cloned folder and create a new virtualenv:

cd nacl-middleware
python3 -m  venv .venv

Activate the just created virtualenv with:

. .venv/bin/activate

Install the dependencies with the command:

pip install -e .[test]

Testing

Run the test suite with the command:

pytest -s

Testing with SSL

Certificates Creation

Generate a Client Key and Certificate Signing Request (CSR)

To generate a client key and CSR, run openssl command in the terminal:

# Generate a private key (client.key)
openssl genpkey -algorithm RSA -out client.key

# Create a certificate signing request (client.csr)
openssl req -new -key client.key -out client.csr
Generate Self-Signed SSL Certificates

For the server, generate the self signed certificates with:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout selfsigned.key -out selfsigned.crt

You will be prompted to answer some questions during the certificate generation process. Make sure to set the Common Name (CN) to your server’s domain name (e.g., localhost).

Sign the CSR using your CA’s private key

Lastly, sign the CSR using the server’s CA’s private key

openssl x509 -req -in client.csr -CA selfsigned.crt -CAkey selfsigned.key -CAcreateserial -out client.crt -days 365

Configuration

Once a pytest run has generated a config.json file, you can edit it and add:

{
    "ssl": {
        "cert_path": "selfsigned.crt",
        "key_path": "selfsigned.key"
    }
}

You should now be able to perform the test with SSL enabled.

pytest -s

Metadata

Release files for nacl-middleware 0.0.9

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nacl-middleware 0.0.9
File Size Uploaded
nacl_middleware-0.0.9.tar.gz 7.5 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for nacl-middleware 0.0.9
File Interpreter ABI Platform
nacl_middleware-0.0.9-py3-none-any.whl Python 3 none any Details

Total release size: 14.4 kB

Release files / nacl_middleware-0.0.9.tar.gz

Download URL nacl_middleware-0.0.9.tar.gz
Size 7.5 kB
Tags Source
SHA-256 checksum
How to use checksums
9c9f4d68e2731ee9758133dd6b357525e656474c2abecc8c85fdb3a0037badfa
BLAKE2b-256 checksum
How to use checksums
77d30d61353ec10a32e89c8a67ee3d55ccbe9f4a4fa9eeef2f19892fa5b206a0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.11.2

Release files / nacl_middleware-0.0.9-py3-none-any.whl

Download URL nacl_middleware-0.0.9-py3-none-any.whl
Size 6.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
569f516d5d654e27028fe2d0570a765c4f9537043ba9be3eabe34e6e35f257d6
BLAKE2b-256 checksum
How to use checksums
154d19b128c215c8a279186a55e80d6e2cb6e0d431d7b5831de8cd6515ba6d1b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/5.0.0 CPython/3.11.2

Release history Release notifications | RSS feed

This release

0.0.9 This release

2 release files

0.0.8

2 release files

0.0.7

2 release files

0.0.6

2 release files

0.0.2

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page