Build an authenticated file share with Python
Phil Schwartz’s open-source portfolio favours focused tools that solve one operational problem, as DenyHosts, Kodos and Scratchy demonstrate. A lightweight download server follows that pattern: share a release archive, log sample or project file without installing a full hosting platform. Using Python’s http.server to build a quick file sharing service with authentication keeps the dependency list almost empty.
The pattern suits a short-lived, pull-based handoff rather than a permanent cloud service. The sender places files in one directory, recipients download them, and a reverse proxy can provide HTTPS. Its narrow purpose makes the security decisions easier to audit.
Set the scope before writing code
Decide what “sharing” means for the transfer. Python’s standard handler provides downloads, not uploads, so the sender must copy files into the shared directory before sending the URL. It also supports browsing directories unless that feature is disabled.
Plan for a limited lifetime. A convenient URL for a conference presentation, family video archive or temporary client handover can disappear when the process stops. Long-term storage, collaborative editing and resumable uploads belong in a service such as Nextcloud or FileBrowser.
Prepare the shared directory
Create a dedicated directory that contains only material intended for recipients. Restrict its permissions and copy in the finished files:
umask 077
mkdir -p shared
cp artefact.tar.gz shared/
chmod 700 shared
Avoid symbolic links inside this directory. The standard handler prevents ordinary .. path traversal, but a link may expose content from elsewhere on the host. Store secrets, SSH keys and credential files elsewhere.
Keep the username and password outside the source code. In Bash, a local demonstration can use environment variables:
export SHARE_USER=phil
read -rs SHARE_PASSWORD
export SHARE_PASSWORD
For a recurring service, inject the password from a secret manager or a permission-restricted service configuration instead.
Require authentication in Python
Subclass SimpleHTTPRequestHandler and check the Authorization header before allowing GET or HEAD requests. Constant-time comparison avoids leaking details through ordinary string comparison.
import base64
import hmac
import os
from functools import partial
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
root = Path(os.environ.get("SHARE_ROOT", "shared")).resolve()
user = os.environ.get("SHARE_USER")
password = os.environ.get("SHARE_PASSWORD")
if not user or not password:
raise SystemExit("Set SHARE_USER and SHARE_PASSWORD")
expected = b"Basic " + base64.b64encode(
f"{user}:{password}".encode("utf-8")
)
class AuthenticatedHandler(SimpleHTTPRequestHandler):
def authorised(self):
supplied = self.headers.get("Authorization", "").encode("utf-8")
return hmac.compare_digest(supplied, expected)
def challenge(self):
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="Shared files"')
self.send_header("Content-Length", "0")
self.end_headers()
def do_GET(self):
if self.authorised():
super().do_GET()
else:
self.challenge()
def do_HEAD(self):
if self.authorised():
super().do_HEAD()
else:
self.challenge()
def list_directory(self, path):
self.send_error(403, "Directory listing disabled")
return None
host = os.environ.get("SHARE_HOST", "127.0.0.1")
port = int(os.environ.get("SHARE_PORT", "8080"))
handler = partial(AuthenticatedHandler, directory=str(root))
with ThreadingHTTPServer((host, port), handler) as server:
print(f"Serving {root} at http://{host}:{port}")
server.serve_forever()
Run it with python3 share.py. The default loopback binding keeps the service inaccessible from the network, which is appropriate when a local reverse proxy will connect to it.
Add HTTPS with a reverse proxy
Basic authentication encodes credentials rather than encrypting them. Anyone able to observe an unencrypted HTTP connection could capture and reuse them, so use HTTPS whenever credentials cross a network.
Caddy provides a compact configuration and can obtain a trusted certificate automatically:
share.example.com.au {
reverse_proxy 127.0.0.1:8080
}
Point the domain’s DNS record at the server and allow inbound HTTPS through the host firewall and router. Python remains responsible for authentication, while Caddy handles TLS and forwards the Authorization header. Keep the Python process bound to loopback so it cannot be reached without the proxy.
Plan around Australian network conditions
Australian connections vary considerably between cities and regions. NBN services in Sydney and Melbourne often provide workable upload capacity, while fixed wireless and some regional links can be slower. Check the upstream speed because every recipient downloads through the host connection.
Home addresses may change, and some fixed-wireless or business services use carrier-grade NAT. If direct inbound connections fail, dynamic DNS can help with changing addresses, while an SSH tunnel or hosted reverse proxy can avoid router changes. Never expose a router administration interface merely to make the transfer work.
Public naming also involves local market practices. A .au domain can be purchased through an Australian registrar under auDA’s eligibility rules, and a suitable subdomain can keep the project tidy. For larger or longer-lived transfers, AWS and Azure offer Australian regions around Sydney and Melbourne, providing a local alternative to maintaining a home server.
Respect the security boundary
Python’s documentation does not recommend http.server for production use. A reverse proxy, HTTPS, access controls and careful file handling can make it dependable for a temporary transfer, but it should not be treated as hardened enterprise infrastructure.
Basic authentication also lacks fine-grained permissions and expiry. A long password stored in a process environment is preferable to one embedded in source code, but it should still be rotated after the handoff. Access logs can reveal requested filenames, so avoid revealing sensitive document names in URLs.
If the shared material contains personal information, consider the Australian Privacy Act and Notifiable Data Breaches scheme where applicable. A digital file does not pass through customs like a posted parcel, although copyright, contractual access and privacy obligations still apply when recipients are overseas.
Apply a dependable sharing routine
A short checklist makes temporary file handoffs easier to operate safely:
- Put only approved files in the shared directory.
- Generate a long, unique password for each transfer.
- Require HTTPS before sending the URL.
- Restrict public access to the proxy and authentication layer.
- Remove the files and revoke credentials when sharing ends.
- Retain logs only as long as they remain useful.
This creates a compact and auditable service for occasional team handoffs, without presenting a small Python process as a replacement for a managed cloud platform.
