hi
This commit is contained in:
commit
2a63bc4e50
14 files changed
+1104
No files matched your search
@@ -0,0 +1,6 @@
|
|||||||
|
.venv/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
data/
|
||||||
|
.env
|
||||||
|
test-results/
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
# amnesia licensing
|
||||||
|
|
||||||
|
The native client now integrates this API; see `../client/LICENSING.md` for
|
||||||
|
sign-in, watermark and endpoint configuration. Restart the service after this
|
||||||
|
update. Client activation and verification return `server_time` alongside
|
||||||
|
`expires_at` so the DLL can use a monotonic session deadline. Verification accepts
|
||||||
|
an optional boolean `renew: true`, extending a still-valid token by at most the
|
||||||
|
configured client lifetime, capped at license expiry. It never renews expired or
|
||||||
|
revoked tokens. `POST /api/client/logout` accepts the bearer token plus `hwid` and
|
||||||
|
deletes that session. These changes require no database migration.
|
||||||
|
|
||||||
|
Python 3.10+ licensing API with SQLite persistence and an Apache-compatible WSGI
|
||||||
|
production server. The sibling `website` project is its account/admin interface.
|
||||||
|
The Minecraft client and injector are separate and unchanged.
|
||||||
|
|
||||||
|
## What it does
|
||||||
|
|
||||||
|
- Username/password accounts, immutable sequential numeric UIDs and admin roles.
|
||||||
|
- Random, single-use license keys with day-based or lifetime access. Time starts
|
||||||
|
on redemption. Keys are stored as keyed hashes; full keys appear only on issue.
|
||||||
|
- First successful native activation ties the **account** to one device.
|
||||||
|
- HWID mismatches are rejected. Only a keyed HMAC of the supplied SHA-256 device
|
||||||
|
fingerprint is stored, not raw serial numbers or the incoming fingerprint.
|
||||||
|
- 15-minute opaque client tokens. Every verify checks account status, current
|
||||||
|
license validity, expiry and the account/device tie. Recheck every 60 seconds;
|
||||||
|
activate again after expiry. Activation rotates the account's client token.
|
||||||
|
- Admin revocation, account suspension, HWID resets, user reset requests and an
|
||||||
|
audit trail. Revocation/reset/suspension invalidates client sessions immediately.
|
||||||
|
- PBKDF2-SHA256 password hashes with 600,000 iterations and random salts. HttpOnly
|
||||||
|
SameSite browser sessions, CSRF checks, exact-origin checks, bounded JSON bodies,
|
||||||
|
parameterized queries and persistent login rate limits.
|
||||||
|
|
||||||
|
HWID checks are a licensing restriction, not hardware attestation or anti-tamper.
|
||||||
|
A modified consumer can bypass local checks; enforcement belongs on this API.
|
||||||
|
The consumer fingerprint must be stable. The example uses a namespaced SHA-256
|
||||||
|
of Windows MachineGuid or Linux machine-id; it does not print the raw identifier.
|
||||||
|
Changing/reinstalling the OS can require an administrator reset.
|
||||||
|
|
||||||
|
## Local start
|
||||||
|
|
||||||
|
From the parent `amnesia` directory:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python website/run-local.py
|
||||||
|
```
|
||||||
|
|
||||||
|
Open http://127.0.0.1:5173 and create the first local administrator. Create a key
|
||||||
|
under license manager, then register a member and redeem it in my licenses.
|
||||||
|
No sample users or passwords are created automatically.
|
||||||
|
|
||||||
|
## API contract
|
||||||
|
|
||||||
|
All POST bodies are JSON. Browser mutations require the configured Origin and,
|
||||||
|
after sign-in, `X-CSRF-Token` returned by `/api/session`. Client endpoints use
|
||||||
|
credentials/Bearer tokens instead of browser cookies or CSRF.
|
||||||
|
|
||||||
|
Local `--dev` startup accepts `localhost`, `127.0.0.1` and `::1` aliases only
|
||||||
|
for the same configured HTTP port. Production keeps exact-origin matching.
|
||||||
|
Restart the licensing server after changing configuration or API code.
|
||||||
|
|
||||||
|
| Method | Route | Purpose |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| GET | `/api/health` | Readiness |
|
||||||
|
| GET | `/api/session` | Current account + CSRF |
|
||||||
|
| POST | `/api/auth/register` | `{username,password}` |
|
||||||
|
| POST | `/api/auth/login` | `{username,password}` |
|
||||||
|
| POST | `/api/auth/logout` | End current browser session |
|
||||||
|
| GET | `/api/account` | Account, licenses, reset request |
|
||||||
|
| POST | `/api/licenses/redeem` | `{key}` |
|
||||||
|
| POST | `/api/account/password` | `{current_password,new_password}`; ends all sessions |
|
||||||
|
| POST | `/api/account/hwid-reset` | `{reason}`; admin approval required |
|
||||||
|
| GET | `/api/admin/overview` | Counts, latest 500 accounts/licenses, reset requests, latest 100 audit events |
|
||||||
|
| POST | `/api/admin/licenses` | `{label,duration_days}`; `null` is lifetime; returns full key once |
|
||||||
|
| POST | `/api/admin/licenses/{id}/revoke` | Revoke issued or redeemed license |
|
||||||
|
| POST | `/api/admin/accounts/{uid}/reset-hwid` | Unbind device, approve request, end client sessions |
|
||||||
|
| POST | `/api/admin/accounts/{uid}/status` | `{enabled:true/false}` |
|
||||||
|
| POST | `/api/client/activate` | `{username,password,hwid,device_name?}`; binds hardware and issues token |
|
||||||
|
| POST | `/api/client/verify` | `{hwid}` + `Authorization: Bearer <token>` |
|
||||||
|
|
||||||
|
`hwid` is exactly 64 hex characters. Activation returns `token`, `expires_at`,
|
||||||
|
`recheck_after`, `account:{uid,username}` and license details. Verification returns
|
||||||
|
`valid:true` and the same identity/expiry metadata without returning a new token.
|
||||||
|
Errors are `{error,code}` with an appropriate HTTP status. Consumers must deny
|
||||||
|
access on failed verification and must not cache a success beyond token expiry.
|
||||||
|
|
||||||
|
Test the standalone consumer **only after redeeming a license**:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
python licensing/client_example.py --url http://127.0.0.1:8787/api --username your_name
|
||||||
|
```
|
||||||
|
|
||||||
|
The password is prompted, never put in command arguments. Tokens are kept in
|
||||||
|
memory. There is no offline license mode or client DLL integration yet.
|
||||||
|
|
||||||
|
## Apache / Linux VPS
|
||||||
|
|
||||||
|
Use the existing TLS certificate for your real domain. The templates use
|
||||||
|
`amnesia.example.com`; replace it everywhere before enabling the site. A single
|
||||||
|
Waitress process listens only on `127.0.0.1:8787`; Apache serves the static website
|
||||||
|
and proxies `/api/`. No inbound API port needs to be opened.
|
||||||
|
|
||||||
|
Example for Debian/Ubuntu (run as your VPS administrator):
|
||||||
|
|
||||||
|
```sh
|
||||||
|
sudo apt install python3 python3-venv apache2
|
||||||
|
sudo useradd --system --home /var/lib/amnesia-licensing --shell /usr/sbin/nologin amnesia
|
||||||
|
sudo install -d -o amnesia -g amnesia -m 700 /var/lib/amnesia-licensing
|
||||||
|
# Copy licensing/ and website/ under /srv/amnesia first.
|
||||||
|
python3 -m venv /srv/amnesia/licensing/.venv
|
||||||
|
/srv/amnesia/licensing/.venv/bin/pip install -r /srv/amnesia/licensing/requirements.txt
|
||||||
|
sudo cp /srv/amnesia/licensing/deploy/amnesia.env.example /etc/amnesia-licensing.env
|
||||||
|
# Edit AMNESIA_ORIGIN to your exact HTTPS origin (no trailing path).
|
||||||
|
sudo chmod 600 /etc/amnesia-licensing.env
|
||||||
|
sudo -u amnesia env AMNESIA_DATA=/var/lib/amnesia-licensing /srv/amnesia/licensing/.venv/bin/python /srv/amnesia/licensing/manage.py create-admin --username your_admin_name
|
||||||
|
sudo cp /srv/amnesia/licensing/deploy/amnesia-licensing.service /etc/systemd/system/
|
||||||
|
sudo systemctl daemon-reload
|
||||||
|
sudo systemctl enable --now amnesia-licensing
|
||||||
|
sudo a2enmod proxy proxy_http headers ssl
|
||||||
|
# Adapt deploy/apache-amnesia.conf to your domain and existing certificate.
|
||||||
|
sudo cp /srv/amnesia/licensing/deploy/apache-amnesia.conf /etc/apache2/sites-available/amnesia.conf
|
||||||
|
sudo a2ensite amnesia
|
||||||
|
sudo apache2ctl configtest
|
||||||
|
sudo systemctl reload apache2
|
||||||
|
```
|
||||||
|
|
||||||
|
Keep code and the virtual environment readable by `amnesia`; make only the state
|
||||||
|
directory writable by that service user. The environment file is read by systemd.
|
||||||
|
Production startup deliberately disables `/api/setup`. Do not use `--dev` or the
|
||||||
|
website preview server on a public interface. TLS makes browser cookies Secure.
|
||||||
|
Admin provisioning/promotions are server-side; public registration always creates
|
||||||
|
ordinary members. To add another admin, run `manage.py create-admin` again.
|
||||||
|
|
||||||
|
Configuration:
|
||||||
|
|
||||||
|
| Variable | Default | Purpose |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `AMNESIA_ORIGIN` | `http://127.0.0.1:5173` | Exact browser origin; set HTTPS on the VPS |
|
||||||
|
| `AMNESIA_DATA` | `licensing/data` | SQLite database + HMAC secret |
|
||||||
|
|
||||||
|
Back up **the database and `hwid.secret` together**. Use SQLite's backup API for a
|
||||||
|
live database, or stop the service before copying the state directory; do not
|
||||||
|
copy only the database file while WAL writes are active. Losing/changing the
|
||||||
|
HMAC secret invalidates key hashes and hardware ties. Do not commit this directory
|
||||||
|
or put it inside Apache's DocumentRoot. Requests never log passwords, tokens,
|
||||||
|
raw keys or HWIDs. Standard Apache access logs still contain IPs and paths.
|
||||||
|
|
||||||
|
## Verification
|
||||||
|
|
||||||
|
```sh
|
||||||
|
cd licensing
|
||||||
|
python -m unittest discover -s tests -v
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests use temporary databases and cover accounts/roles, CSRF/origin checks, key
|
||||||
|
redemption races, HWID mismatch, expiry/revocation, reset approval, password
|
||||||
|
changes, disabled accounts, token expiry, rate limits and secret storage.
|
||||||
|
|
||||||
|
Deployment follows the official [Apache reverse-proxy guide](https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html)
|
||||||
|
and [Waitress proxy/header guidance](https://docs.pylonsproject.org/projects/waitress/en/stable/reverse-proxy.html).
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""Amnesia account and device licensing service."""
|
||||||
@@ -0,0 +1,471 @@
|
|||||||
|
"""Small same-origin JSON API. Run behind Apache/HTTPS in production."""
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import ipaddress
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import sqlite3
|
||||||
|
import time
|
||||||
|
from dataclasses import dataclass
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from http.cookies import SimpleCookie
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
LOG = logging.getLogger("amnesia.licensing")
|
||||||
|
COOKIE = "amnesia_session"
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
USERNAME = re.compile(r"[a-zA-Z0-9_]{3,24}\Z")
|
||||||
|
HWID = re.compile(r"[a-fA-F0-9]{64}\Z")
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Settings:
|
||||||
|
data_dir: Path
|
||||||
|
origin: str = "http://127.0.0.1:5173"
|
||||||
|
secure_cookies: bool = False
|
||||||
|
allow_local_setup: bool = False
|
||||||
|
session_seconds: int = 43200
|
||||||
|
client_seconds: int = 900
|
||||||
|
rate_limit: bool = True
|
||||||
|
allow_loopback_origins: bool = False
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def environment(cls):
|
||||||
|
origin = os.environ.get("AMNESIA_ORIGIN", "http://127.0.0.1:5173").rstrip("/")
|
||||||
|
if urlsplit(origin).scheme not in ("http", "https") or not urlsplit(origin).netloc:
|
||||||
|
raise ValueError("AMNESIA_ORIGIN must be a full http(s) origin")
|
||||||
|
return cls(Path(os.environ.get("AMNESIA_DATA", str(ROOT / "data"))), origin,
|
||||||
|
origin.startswith("https://"), False)
|
||||||
|
|
||||||
|
|
||||||
|
SCHEMA = """
|
||||||
|
CREATE TABLE IF NOT EXISTS accounts (
|
||||||
|
uid INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT NOT NULL,
|
||||||
|
username_key TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL DEFAULT 'user' CHECK(role IN ('user','admin')),
|
||||||
|
enabled INTEGER NOT NULL DEFAULT 1, created_at INTEGER NOT NULL,
|
||||||
|
hwid_hash TEXT, device_name TEXT, bound_at INTEGER, last_seen INTEGER
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS licenses (
|
||||||
|
id TEXT PRIMARY KEY, key_hash TEXT NOT NULL UNIQUE, key_hint TEXT NOT NULL,
|
||||||
|
label TEXT NOT NULL, duration_days INTEGER, status TEXT NOT NULL DEFAULT 'issued',
|
||||||
|
account_uid INTEGER REFERENCES accounts(uid), created_at INTEGER NOT NULL,
|
||||||
|
activated_at INTEGER, expires_at INTEGER
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
token_hash TEXT PRIMARY KEY, account_uid INTEGER NOT NULL REFERENCES accounts(uid),
|
||||||
|
csrf TEXT NOT NULL, expires_at INTEGER NOT NULL, created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS client_tokens (
|
||||||
|
token_hash TEXT PRIMARY KEY, account_uid INTEGER NOT NULL REFERENCES accounts(uid),
|
||||||
|
license_id TEXT NOT NULL REFERENCES licenses(id), hwid_hash TEXT NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS reset_requests (
|
||||||
|
account_uid INTEGER PRIMARY KEY REFERENCES accounts(uid), reason TEXT NOT NULL,
|
||||||
|
requested_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS audit (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT, actor_uid INTEGER REFERENCES accounts(uid),
|
||||||
|
action TEXT NOT NULL, subject TEXT NOT NULL, created_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS limits (
|
||||||
|
identity TEXT PRIMARY KEY, count INTEGER NOT NULL, expires_at INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS licenses_owner ON licenses(account_uid);
|
||||||
|
CREATE INDEX IF NOT EXISTS sessions_owner ON sessions(account_uid);
|
||||||
|
CREATE INDEX IF NOT EXISTS audit_time ON audit(id DESC);
|
||||||
|
PRAGMA user_version=1;
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
class ApiError(Exception):
|
||||||
|
def __init__(self, status, message, code="request_failed"):
|
||||||
|
self.status, self.message, self.code = status, message, code
|
||||||
|
|
||||||
|
|
||||||
|
def password_hash(password):
|
||||||
|
salt = secrets.token_hex(16)
|
||||||
|
digest = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), 600000)
|
||||||
|
return f"pbkdf2_sha256$600000${salt}${digest.hex()}"
|
||||||
|
|
||||||
|
|
||||||
|
def password_matches(password, encoded):
|
||||||
|
try:
|
||||||
|
_, iterations, salt, expected = encoded.split("$")
|
||||||
|
actual = hashlib.pbkdf2_hmac("sha256", password.encode(), bytes.fromhex(salt), int(iterations)).hex()
|
||||||
|
return hmac.compare_digest(actual, expected)
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def text(body, name, minimum=1, maximum=128):
|
||||||
|
value = body.get(name)
|
||||||
|
if not isinstance(value, str) or not minimum <= len(value) <= maximum:
|
||||||
|
raise ApiError(400, f"{name.replace('_', ' ')} must be {minimum}–{maximum} characters", "invalid_input")
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def credentials(body):
|
||||||
|
username = text(body, "username", 3, 24)
|
||||||
|
if not USERNAME.fullmatch(username):
|
||||||
|
raise ApiError(400, "account names use letters, numbers and underscores", "invalid_input")
|
||||||
|
return username, text(body, "password", 12, 128)
|
||||||
|
|
||||||
|
|
||||||
|
class Application:
|
||||||
|
def __init__(self, settings):
|
||||||
|
self.settings = settings
|
||||||
|
settings.data_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
|
||||||
|
secret_path = settings.data_dir / "hwid.secret"
|
||||||
|
try:
|
||||||
|
with secret_path.open("xb") as output:
|
||||||
|
os.chmod(secret_path, 0o600)
|
||||||
|
output.write(secrets.token_bytes(32))
|
||||||
|
except FileExistsError:
|
||||||
|
pass
|
||||||
|
self.secret = secret_path.read_bytes()
|
||||||
|
if len(self.secret) != 32:
|
||||||
|
raise ValueError("hwid.secret must contain 32 bytes; restore it from backup")
|
||||||
|
self.database = settings.data_dir / "licensing.sqlite3"
|
||||||
|
with self.connect() as db:
|
||||||
|
db.execute("PRAGMA journal_mode=WAL")
|
||||||
|
db.executescript(SCHEMA)
|
||||||
|
os.chmod(self.database, 0o600)
|
||||||
|
self.dummy_hash = password_hash(secrets.token_urlsafe(32))
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def connect(self):
|
||||||
|
db = sqlite3.connect(self.database, timeout=10)
|
||||||
|
db.row_factory = sqlite3.Row
|
||||||
|
db.execute("PRAGMA foreign_keys=ON")
|
||||||
|
try:
|
||||||
|
with db:
|
||||||
|
yield db
|
||||||
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
|
def digest(self, namespace, value):
|
||||||
|
return hmac.new(self.secret, (namespace + ":" + value).encode(), hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
def origin_allowed(self, origin):
|
||||||
|
if origin == self.settings.origin:
|
||||||
|
return True
|
||||||
|
if not self.settings.allow_loopback_origins:
|
||||||
|
return False
|
||||||
|
try:
|
||||||
|
expected, incoming = urlsplit(self.settings.origin), urlsplit(origin)
|
||||||
|
loopback = {"localhost", "127.0.0.1", "::1"}
|
||||||
|
return (expected.scheme == incoming.scheme == "http"
|
||||||
|
and expected.hostname in loopback and incoming.hostname in loopback
|
||||||
|
and (expected.port or 80) == (incoming.port or 80)
|
||||||
|
and not incoming.username and not incoming.password
|
||||||
|
and not incoming.path and not incoming.query and not incoming.fragment)
|
||||||
|
except ValueError:
|
||||||
|
return False
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def token_hash(token):
|
||||||
|
return hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
|
||||||
|
def audit(self, db, actor, action, subject):
|
||||||
|
db.execute("INSERT INTO audit(actor_uid,action,subject,created_at) VALUES(?,?,?,?)",
|
||||||
|
(actor, action, str(subject), int(time.time())))
|
||||||
|
|
||||||
|
def create_account(self, db, username, password, role="user"):
|
||||||
|
try:
|
||||||
|
cursor = db.execute("INSERT INTO accounts(username,username_key,password_hash,role,created_at) VALUES(?,?,?,?,?)",
|
||||||
|
(username, username.lower(), password_hash(password), role, int(time.time())))
|
||||||
|
except sqlite3.IntegrityError:
|
||||||
|
raise ApiError(409, "that account name is unavailable", "name_taken")
|
||||||
|
self.audit(db, cursor.lastrowid, "account.created", cursor.lastrowid)
|
||||||
|
return db.execute("SELECT * FROM accounts WHERE uid=?", (cursor.lastrowid,)).fetchone()
|
||||||
|
|
||||||
|
def account_view(self, account):
|
||||||
|
return {key: account[key] for key in ("uid", "username", "role", "created_at", "enabled", "device_name", "bound_at", "last_seen")} | {"hwid_bound": bool(account["hwid_hash"])}
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def license_view(license):
|
||||||
|
value = {key: license[key] for key in ("id", "key_hint", "label", "duration_days", "status", "account_uid", "created_at", "activated_at", "expires_at")}
|
||||||
|
if value["status"] == "active" and value["expires_at"] is not None and value["expires_at"] <= time.time():
|
||||||
|
value["status"] = "expired"
|
||||||
|
return value
|
||||||
|
|
||||||
|
def active_license(self, db, uid):
|
||||||
|
return db.execute("SELECT * FROM licenses WHERE account_uid=? AND status='active' AND (expires_at IS NULL OR expires_at>?) ORDER BY expires_at IS NULL DESC, expires_at DESC LIMIT 1", (uid, int(time.time()))).fetchone()
|
||||||
|
|
||||||
|
def session(self, db, environ):
|
||||||
|
cookies = SimpleCookie()
|
||||||
|
try:
|
||||||
|
cookies.load(environ.get("HTTP_COOKIE", ""))
|
||||||
|
except Exception:
|
||||||
|
return None, None
|
||||||
|
token = cookies.get(COOKIE)
|
||||||
|
if not token or len(token.value) > 128:
|
||||||
|
return None, None
|
||||||
|
session = db.execute("SELECT * FROM sessions WHERE token_hash=? AND expires_at>?", (self.token_hash(token.value), int(time.time()))).fetchone()
|
||||||
|
account = db.execute("SELECT * FROM accounts WHERE uid=? AND enabled=1", (session["account_uid"],)).fetchone() if session else None
|
||||||
|
return session, account
|
||||||
|
|
||||||
|
def cookie(self, token, lifetime):
|
||||||
|
result = f"{COOKIE}={token}; Path=/api; HttpOnly; SameSite=Strict; Max-Age={lifetime}"
|
||||||
|
return result + ("; Secure" if self.settings.secure_cookies else "")
|
||||||
|
|
||||||
|
def login(self, db, account):
|
||||||
|
now = int(time.time())
|
||||||
|
token, csrf = secrets.token_urlsafe(32), secrets.token_urlsafe(32)
|
||||||
|
db.execute("DELETE FROM sessions WHERE expires_at<=?", (now,))
|
||||||
|
db.execute("DELETE FROM client_tokens WHERE expires_at<=?", (now,))
|
||||||
|
db.execute("INSERT INTO sessions VALUES(?,?,?,?,?)", (self.token_hash(token), account["uid"], csrf, now + self.settings.session_seconds, now))
|
||||||
|
db.execute("DELETE FROM sessions WHERE account_uid=? AND token_hash NOT IN (SELECT token_hash FROM sessions WHERE account_uid=? ORDER BY created_at DESC,rowid DESC LIMIT 5)", (account["uid"], account["uid"]))
|
||||||
|
return {"account": self.account_view(account), "csrf": csrf}, [("Set-Cookie", self.cookie(token, self.settings.session_seconds))]
|
||||||
|
|
||||||
|
def limit(self, db, identity, maximum, seconds):
|
||||||
|
if not self.settings.rate_limit:
|
||||||
|
return
|
||||||
|
now = int(time.time())
|
||||||
|
key = self.digest("rate", identity)
|
||||||
|
db.execute("DELETE FROM limits WHERE expires_at<=?", (now,))
|
||||||
|
db.execute("INSERT INTO limits VALUES(?,1,?) ON CONFLICT(identity) DO UPDATE SET count=count+1", (key, now + seconds))
|
||||||
|
count = db.execute("SELECT count FROM limits WHERE identity=?", (key,)).fetchone()[0]
|
||||||
|
if count > maximum:
|
||||||
|
raise ApiError(429, "too many attempts; try again shortly", "rate_limited")
|
||||||
|
|
||||||
|
def __call__(self, environ, start_response):
|
||||||
|
extra = []
|
||||||
|
try:
|
||||||
|
method, path = environ.get("REQUEST_METHOD", "GET"), environ.get("PATH_INFO", "/")
|
||||||
|
if len(path) > 512:
|
||||||
|
raise ApiError(414, "request path is too long")
|
||||||
|
if method not in ("GET", "POST"):
|
||||||
|
raise ApiError(405, "method not allowed")
|
||||||
|
body = {}
|
||||||
|
if method == "POST":
|
||||||
|
if environ.get("CONTENT_TYPE", "").split(";")[0] != "application/json":
|
||||||
|
raise ApiError(415, "send application/json")
|
||||||
|
try:
|
||||||
|
length = int(environ.get("CONTENT_LENGTH", "0"))
|
||||||
|
except ValueError:
|
||||||
|
raise ApiError(400, "invalid request length")
|
||||||
|
if length <= 0 or length > 16384:
|
||||||
|
raise ApiError(413, "request body must be 1–16384 bytes")
|
||||||
|
try:
|
||||||
|
body = json.loads(environ["wsgi.input"].read(length))
|
||||||
|
except (ValueError, UnicodeDecodeError):
|
||||||
|
raise ApiError(400, "invalid JSON")
|
||||||
|
if not isinstance(body, dict):
|
||||||
|
raise ApiError(400, "send a JSON object")
|
||||||
|
if not path.startswith("/api/client/") and not self.origin_allowed(environ.get("HTTP_ORIGIN", "")):
|
||||||
|
raise ApiError(403, "request origin rejected", "origin_rejected")
|
||||||
|
with self.connect() as db:
|
||||||
|
# Commit rate counters even when an authentication request fails.
|
||||||
|
self.limit(db, "all:" + environ.get("REMOTE_ADDR", "unknown"), 360, 60)
|
||||||
|
if method == "POST" and path in ("/api/auth/login", "/api/auth/register", "/api/setup", "/api/client/activate"):
|
||||||
|
self.limit(db, "auth:" + environ.get("REMOTE_ADDR", "unknown"), 12, 60)
|
||||||
|
if isinstance(body.get("username"), str):
|
||||||
|
self.limit(db, "name:" + body["username"].lower()[:128], 30, 300)
|
||||||
|
db.commit()
|
||||||
|
db.execute("BEGIN IMMEDIATE" if method == "POST" else "BEGIN")
|
||||||
|
result, extra = self.route(db, environ, method, path, body)
|
||||||
|
status = 200
|
||||||
|
except ApiError as error:
|
||||||
|
status, result = error.status, {"error": error.message, "code": error.code}
|
||||||
|
except (sqlite3.Error, OSError):
|
||||||
|
LOG.exception("licensing request failed")
|
||||||
|
status, result = 503, {"error": "service temporarily unavailable", "code": "service_unavailable"}
|
||||||
|
except Exception:
|
||||||
|
LOG.exception("unexpected licensing error")
|
||||||
|
status, result = 500, {"error": "request could not be completed", "code": "internal_error"}
|
||||||
|
payload = json.dumps(result, separators=(",", ":")).encode()
|
||||||
|
names = {200:"OK",400:"Bad Request",401:"Unauthorized",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",409:"Conflict",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",429:"Too Many Requests",500:"Internal Server Error",503:"Service Unavailable"}
|
||||||
|
headers = [("Content-Type", "application/json; charset=utf-8"), ("Content-Length", str(len(payload))), ("Cache-Control", "no-store"), ("X-Content-Type-Options", "nosniff"), ("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'")] + extra
|
||||||
|
if status == 429:
|
||||||
|
headers.append(("Retry-After", "60"))
|
||||||
|
start_response(f"{status} {names.get(status,'Error')}", headers)
|
||||||
|
return [payload]
|
||||||
|
|
||||||
|
def route(self, db, environ, method, path, body):
|
||||||
|
if method == "GET" and path == "/api/health":
|
||||||
|
return {"status": "online", "service": "amnesia licensing"}, []
|
||||||
|
session, account = self.session(db, environ)
|
||||||
|
if method == "GET" and path == "/api/session":
|
||||||
|
exists = db.execute("SELECT 1 FROM accounts WHERE role='admin' LIMIT 1").fetchone()
|
||||||
|
return {"account": self.account_view(account) if account else None, "csrf": session["csrf"] if account else None, "setup_required": self.settings.allow_local_setup and not exists}, []
|
||||||
|
if method == "POST" and path == "/api/setup":
|
||||||
|
try:
|
||||||
|
local = ipaddress.ip_address(environ.get("REMOTE_ADDR", "")).is_loopback
|
||||||
|
except ValueError:
|
||||||
|
local = False
|
||||||
|
if not self.settings.allow_local_setup or not local or db.execute("SELECT 1 FROM accounts LIMIT 1").fetchone():
|
||||||
|
raise ApiError(403, "initial setup is unavailable")
|
||||||
|
username, password = credentials(body)
|
||||||
|
return self.login(db, self.create_account(db, username, password, "admin"))
|
||||||
|
if method == "POST" and path in ("/api/auth/register", "/api/auth/login"):
|
||||||
|
username, password = credentials(body)
|
||||||
|
if path.endswith("register"):
|
||||||
|
if not db.execute("SELECT 1 FROM accounts WHERE role='admin' LIMIT 1").fetchone():
|
||||||
|
raise ApiError(403, "registration is not available yet")
|
||||||
|
return self.login(db, self.create_account(db, username, password))
|
||||||
|
candidate = db.execute("SELECT * FROM accounts WHERE username_key=?", (username.lower(),)).fetchone()
|
||||||
|
valid = password_matches(password, candidate["password_hash"] if candidate else self.dummy_hash)
|
||||||
|
if not valid or not candidate or not candidate["enabled"]:
|
||||||
|
raise ApiError(401, "account name or password is incorrect", "invalid_credentials")
|
||||||
|
return self.login(db, candidate)
|
||||||
|
if method == "POST" and path.startswith("/api/client/"):
|
||||||
|
return self.client(db, environ, path, body), []
|
||||||
|
if not account:
|
||||||
|
raise ApiError(401, "sign in to continue", "sign_in_required")
|
||||||
|
if method == "POST" and not hmac.compare_digest(environ.get("HTTP_X_CSRF_TOKEN", ""), session["csrf"]):
|
||||||
|
raise ApiError(403, "session check failed; refresh and try again", "csrf_failed")
|
||||||
|
uid = account["uid"]
|
||||||
|
if method == "POST" and path == "/api/auth/logout":
|
||||||
|
db.execute("DELETE FROM sessions WHERE token_hash=?", (session["token_hash"],))
|
||||||
|
return {"ok": True}, [("Set-Cookie", self.cookie("", 0))]
|
||||||
|
if method == "GET" and path == "/api/account":
|
||||||
|
licenses = [self.license_view(row) for row in db.execute("SELECT * FROM licenses WHERE account_uid=? ORDER BY created_at DESC", (uid,))]
|
||||||
|
reset = db.execute("SELECT reason,requested_at FROM reset_requests WHERE account_uid=?", (uid,)).fetchone()
|
||||||
|
return {"account": self.account_view(account), "licenses": licenses, "reset_request": dict(reset) if reset else None}, []
|
||||||
|
if method == "POST" and path == "/api/licenses/redeem":
|
||||||
|
key = text(body,"key",10,128).strip().upper()
|
||||||
|
license = db.execute("SELECT * FROM licenses WHERE key_hash=?", (self.digest("license", key),)).fetchone()
|
||||||
|
if not license or license["status"] != "issued":
|
||||||
|
raise ApiError(400, "that license key is invalid or already used", "invalid_license")
|
||||||
|
now = int(time.time())
|
||||||
|
expires = now + license["duration_days"] * 86400 if license["duration_days"] else None
|
||||||
|
db.execute("UPDATE licenses SET account_uid=?,status='active',activated_at=?,expires_at=? WHERE id=?", (uid,now,expires,license["id"]))
|
||||||
|
self.audit(db,uid,"license.redeemed",license["id"])
|
||||||
|
return {"ok": True}, []
|
||||||
|
if method == "POST" and path == "/api/account/password":
|
||||||
|
if not password_matches(text(body,"current_password",1,128), account["password_hash"]):
|
||||||
|
raise ApiError(400, "current password is incorrect")
|
||||||
|
password = text(body,"new_password",12,128)
|
||||||
|
db.execute("UPDATE accounts SET password_hash=? WHERE uid=?", (password_hash(password),uid))
|
||||||
|
db.execute("DELETE FROM sessions WHERE account_uid=?", (uid,))
|
||||||
|
db.execute("DELETE FROM client_tokens WHERE account_uid=?", (uid,))
|
||||||
|
self.audit(db,uid,"password.changed",uid)
|
||||||
|
return {"ok":True}, [("Set-Cookie",self.cookie("",0))]
|
||||||
|
if method == "POST" and path == "/api/account/hwid-reset":
|
||||||
|
if not account["hwid_hash"]:
|
||||||
|
raise ApiError(409,"no device is linked to this account")
|
||||||
|
reason = text(body,"reason",5,240).strip()
|
||||||
|
if len(reason)<5:
|
||||||
|
raise ApiError(400,"include a reason of at least 5 characters")
|
||||||
|
db.execute("INSERT INTO reset_requests VALUES(?,?,?) ON CONFLICT(account_uid) DO UPDATE SET reason=excluded.reason, requested_at=excluded.requested_at", (uid,reason,int(time.time())))
|
||||||
|
self.audit(db,uid,"hwid.reset_requested",uid)
|
||||||
|
return {"ok":True}, []
|
||||||
|
if path.startswith("/api/admin/"):
|
||||||
|
if account["role"] != "admin":
|
||||||
|
raise ApiError(403,"administrator access required")
|
||||||
|
return self.admin(db,account,method,path,body), []
|
||||||
|
raise ApiError(404,"endpoint not found")
|
||||||
|
|
||||||
|
def client(self, db, environ, path, body):
|
||||||
|
fingerprint = text(body,"hwid",64,64)
|
||||||
|
if not HWID.fullmatch(fingerprint):
|
||||||
|
raise ApiError(400,"hwid must be a SHA-256 fingerprint","invalid_hwid")
|
||||||
|
hardware = self.digest("hwid",fingerprint.lower())
|
||||||
|
now = int(time.time())
|
||||||
|
if path == "/api/client/activate":
|
||||||
|
username,password = credentials(body)
|
||||||
|
account = db.execute("SELECT * FROM accounts WHERE username_key=?", (username.lower(),)).fetchone()
|
||||||
|
valid = password_matches(password,account["password_hash"] if account else self.dummy_hash)
|
||||||
|
if not valid or not account or not account["enabled"]:
|
||||||
|
raise ApiError(401,"account name or password is incorrect","invalid_credentials")
|
||||||
|
license = self.active_license(db,account["uid"])
|
||||||
|
if not license:
|
||||||
|
raise ApiError(403,"an active license is required","license_required")
|
||||||
|
if account["hwid_hash"] and not hmac.compare_digest(hardware,account["hwid_hash"]):
|
||||||
|
raise ApiError(403,"this account is linked to another device","hwid_mismatch")
|
||||||
|
device_name = text(body,"device_name",1,48) if "device_name" in body else "linked device"
|
||||||
|
db.execute("UPDATE accounts SET hwid_hash=?,device_name=?,bound_at=COALESCE(bound_at,?),last_seen=? WHERE uid=?", (hardware,device_name,now,now,account["uid"]))
|
||||||
|
token = secrets.token_urlsafe(32)
|
||||||
|
expires = min(now+self.settings.client_seconds, license["expires_at"] or now+self.settings.client_seconds)
|
||||||
|
db.execute("DELETE FROM client_tokens WHERE account_uid=? OR expires_at<=?", (account["uid"],now))
|
||||||
|
db.execute("INSERT INTO client_tokens VALUES(?,?,?,?,?)", (self.token_hash(token),account["uid"],license["id"],hardware,expires))
|
||||||
|
self.audit(db,account["uid"],"device.activated",license["id"])
|
||||||
|
return {"token":token,"expires_at":expires,"server_time":now,"recheck_after":60,"account":{"uid":account["uid"],"username":account["username"]},"license":self.license_view(license)}
|
||||||
|
if path in ("/api/client/verify", "/api/client/logout"):
|
||||||
|
auth = environ.get("HTTP_AUTHORIZATION", "")
|
||||||
|
token = auth[7:] if auth.startswith("Bearer ") else ""
|
||||||
|
if not 20 <= len(token) <= 128:
|
||||||
|
raise ApiError(401,"valid client token required","invalid_token")
|
||||||
|
record = db.execute("SELECT * FROM client_tokens WHERE token_hash=? AND expires_at>?", (self.token_hash(token),now)).fetchone()
|
||||||
|
if not record:
|
||||||
|
raise ApiError(401,"client session expired; sign in again","invalid_token")
|
||||||
|
account = db.execute("SELECT * FROM accounts WHERE uid=? AND enabled=1", (record["account_uid"],)).fetchone()
|
||||||
|
license = db.execute("SELECT * FROM licenses WHERE id=? AND status='active' AND (expires_at IS NULL OR expires_at>?)", (record["license_id"],now)).fetchone()
|
||||||
|
if not account or not license:
|
||||||
|
raise ApiError(403,"access is no longer active","access_revoked")
|
||||||
|
if not account["hwid_hash"] or not hmac.compare_digest(hardware,record["hwid_hash"]) or not hmac.compare_digest(hardware,account["hwid_hash"]):
|
||||||
|
raise ApiError(403,"device does not match this session","hwid_mismatch")
|
||||||
|
if path.endswith("logout"):
|
||||||
|
db.execute("DELETE FROM client_tokens WHERE token_hash=?", (record["token_hash"],))
|
||||||
|
return {"ok":True}
|
||||||
|
if "renew" in body and type(body["renew"]) is not bool:
|
||||||
|
raise ApiError(400,"renew must be true or false")
|
||||||
|
expires = record["expires_at"]
|
||||||
|
if body.get("renew"):
|
||||||
|
expires = min(now+self.settings.client_seconds, license["expires_at"] or now+self.settings.client_seconds)
|
||||||
|
db.execute("UPDATE client_tokens SET expires_at=? WHERE token_hash=?", (expires,record["token_hash"]))
|
||||||
|
db.execute("UPDATE accounts SET last_seen=? WHERE uid=?", (now,account["uid"]))
|
||||||
|
return {"valid":True,"expires_at":expires,"server_time":now,"recheck_after":60,"account":{"uid":account["uid"],"username":account["username"]},"license":self.license_view(license)}
|
||||||
|
raise ApiError(404,"endpoint not found")
|
||||||
|
|
||||||
|
def admin(self, db, account, method, path, body):
|
||||||
|
uid = account["uid"]
|
||||||
|
if method == "GET" and path == "/api/admin/overview":
|
||||||
|
counts = {"accounts":db.execute("SELECT count(*) FROM accounts").fetchone()[0],"active_licenses":db.execute("SELECT count(*) FROM licenses WHERE status='active' AND (expires_at IS NULL OR expires_at>?)",(int(time.time()),)).fetchone()[0],"issued_keys":db.execute("SELECT count(*) FROM licenses WHERE status='issued'").fetchone()[0],"reset_requests":db.execute("SELECT count(*) FROM reset_requests").fetchone()[0]}
|
||||||
|
accounts = [self.account_view(row) for row in db.execute("SELECT * FROM accounts ORDER BY uid LIMIT 500")]
|
||||||
|
licenses = [self.license_view(row) for row in db.execute("SELECT * FROM licenses ORDER BY created_at DESC,rowid DESC LIMIT 500")]
|
||||||
|
resets = [dict(row) for row in db.execute("SELECT * FROM reset_requests ORDER BY requested_at")]
|
||||||
|
audit = [dict(row) for row in db.execute("SELECT audit.*,accounts.username FROM audit LEFT JOIN accounts ON accounts.uid=audit.actor_uid ORDER BY id DESC LIMIT 100")]
|
||||||
|
return {"counts":counts,"accounts":accounts,"licenses":licenses,"reset_requests":resets,"audit":audit}
|
||||||
|
if method == "POST" and path == "/api/admin/licenses":
|
||||||
|
label = text(body,"label",1,60).strip()
|
||||||
|
if not label:
|
||||||
|
raise ApiError(400,"a license label is required")
|
||||||
|
days = body.get("duration_days")
|
||||||
|
if days is not None and (type(days) is not int or not 1 <= days <= 3650):
|
||||||
|
raise ApiError(400,"duration must be 1–3650 days, or null for lifetime")
|
||||||
|
key = "AMN-" + "-".join(secrets.token_hex(4).upper() for _ in range(4))
|
||||||
|
identifier = secrets.token_hex(12)
|
||||||
|
db.execute("INSERT INTO licenses(id,key_hash,key_hint,label,duration_days,created_at) VALUES(?,?,?,?,?,?)", (identifier,self.digest("license",key),"AMN-…-"+key[-8:],label,days,int(time.time())))
|
||||||
|
self.audit(db,uid,"license.issued",identifier)
|
||||||
|
return {"key":key,"license":self.license_view(db.execute("SELECT * FROM licenses WHERE id=?",(identifier,)).fetchone())}
|
||||||
|
match = re.fullmatch(r"/api/admin/licenses/([a-f0-9]{24})/revoke",path)
|
||||||
|
if method == "POST" and match:
|
||||||
|
if not db.execute("SELECT 1 FROM licenses WHERE id=?",(match[1],)).fetchone():
|
||||||
|
raise ApiError(404,"license not found")
|
||||||
|
db.execute("UPDATE licenses SET status='revoked' WHERE id=?",(match[1],))
|
||||||
|
db.execute("DELETE FROM client_tokens WHERE license_id=?",(match[1],))
|
||||||
|
self.audit(db,uid,"license.revoked",match[1])
|
||||||
|
return {"ok":True}
|
||||||
|
match = re.fullmatch(r"/api/admin/accounts/(\d+)/(reset-hwid|status)",path)
|
||||||
|
if method == "POST" and match:
|
||||||
|
target = int(match[1])
|
||||||
|
if not db.execute("SELECT 1 FROM accounts WHERE uid=?",(target,)).fetchone():
|
||||||
|
raise ApiError(404,"account not found")
|
||||||
|
if match[2] == "reset-hwid":
|
||||||
|
db.execute("UPDATE accounts SET hwid_hash=NULL,device_name=NULL,bound_at=NULL WHERE uid=?",(target,))
|
||||||
|
db.execute("DELETE FROM reset_requests WHERE account_uid=?",(target,))
|
||||||
|
self.audit(db,uid,"hwid.reset",target)
|
||||||
|
else:
|
||||||
|
if type(body.get("enabled")) is not bool:
|
||||||
|
raise ApiError(400,"enabled must be true or false")
|
||||||
|
if target == uid:
|
||||||
|
raise ApiError(409,"you cannot disable your own administrator account")
|
||||||
|
db.execute("UPDATE accounts SET enabled=? WHERE uid=?",(body["enabled"],target))
|
||||||
|
if not body["enabled"]:
|
||||||
|
db.execute("DELETE FROM sessions WHERE account_uid=?",(target,))
|
||||||
|
self.audit(db,uid,"account.enabled" if body["enabled"] else "account.disabled",target)
|
||||||
|
db.execute("DELETE FROM client_tokens WHERE account_uid=?",(target,))
|
||||||
|
return {"ok":True}
|
||||||
|
raise ApiError(404,"endpoint not found")
|
||||||
|
|
||||||
|
|
||||||
|
def create_app():
|
||||||
|
return Application(Settings.environment())
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"""Example licensing consumer; does not modify or inject the Minecraft client."""
|
||||||
|
import argparse
|
||||||
|
import getpass
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
import platform
|
||||||
|
from pathlib import Path
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
from urllib.request import Request, urlopen
|
||||||
|
from urllib.parse import urlsplit
|
||||||
|
|
||||||
|
|
||||||
|
def machine_fingerprint():
|
||||||
|
if platform.system()=="Windows":
|
||||||
|
import winreg
|
||||||
|
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE,r"SOFTWARE\Microsoft\Cryptography",0,winreg.KEY_READ|winreg.KEY_WOW64_64KEY) as key:
|
||||||
|
identifier=winreg.QueryValueEx(key,"MachineGuid")[0]
|
||||||
|
else:
|
||||||
|
identifier=Path("/etc/machine-id").read_text().strip()
|
||||||
|
return hashlib.sha256(("amnesia/device/v1:"+identifier.strip().lower()).encode()).hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
def request(base,path,body,token=None):
|
||||||
|
headers={"Content-Type":"application/json"}
|
||||||
|
if token:headers["Authorization"]="Bearer "+token
|
||||||
|
req=Request(base.rstrip("/")+path,data=json.dumps(body).encode(),headers=headers,method="POST")
|
||||||
|
try:
|
||||||
|
with urlopen(req,timeout=20) as response:return json.load(response)
|
||||||
|
except HTTPError as error:
|
||||||
|
result=json.load(error)
|
||||||
|
raise RuntimeError(result.get("error","licensing request failed")) from None
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=="__main__":
|
||||||
|
parser=argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--url",required=True,help="https://your-domain/api")
|
||||||
|
parser.add_argument("--username",required=True)
|
||||||
|
args=parser.parse_args()
|
||||||
|
url=urlsplit(args.url)
|
||||||
|
if url.scheme!="https" and not (url.scheme=="http" and url.hostname in ("127.0.0.1","localhost")):
|
||||||
|
parser.error("HTTPS is required except for loopback testing")
|
||||||
|
hardware=machine_fingerprint()
|
||||||
|
result=request(args.url,"/client/activate",{"username":args.username,"password":getpass.getpass("Password: "),"hwid":hardware,"device_name":platform.node()[:48] or "my device"})
|
||||||
|
verified=request(args.url,"/client/verify",{"hwid":hardware},result["token"])
|
||||||
|
print(f"License verified for {verified['account']['username']} / UID {verified['account']['uid']}.")
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Amnesia licensing API
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=amnesia
|
||||||
|
Group=amnesia
|
||||||
|
WorkingDirectory=/srv/amnesia/licensing
|
||||||
|
EnvironmentFile=/etc/amnesia-licensing.env
|
||||||
|
ExecStart=/srv/amnesia/licensing/.venv/bin/python /srv/amnesia/licensing/run.py
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=3
|
||||||
|
StateDirectory=amnesia-licensing
|
||||||
|
UMask=0077
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
ReadWritePaths=/var/lib/amnesia-licensing
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
AMNESIA_ORIGIN=https://amnesia.example.com
|
||||||
|
AMNESIA_DATA=/var/lib/amnesia-licensing
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Replace amnesia.example.com with your domain and use its existing TLS certificate.
|
||||||
|
# Required modules: proxy proxy_http headers ssl
|
||||||
|
<VirtualHost *:80>
|
||||||
|
ServerName amnesia.example.com
|
||||||
|
Redirect permanent / https://amnesia.example.com/
|
||||||
|
</VirtualHost>
|
||||||
|
|
||||||
|
<VirtualHost *:443>
|
||||||
|
ServerName amnesia.example.com
|
||||||
|
SSLEngine on
|
||||||
|
SSLCertificateFile /etc/letsencrypt/live/amnesia.example.com/fullchain.pem
|
||||||
|
SSLCertificateKeyFile /etc/letsencrypt/live/amnesia.example.com/privkey.pem
|
||||||
|
|
||||||
|
DocumentRoot /srv/amnesia/website/public
|
||||||
|
<Directory /srv/amnesia/website/public>
|
||||||
|
Options -Indexes
|
||||||
|
AllowOverride None
|
||||||
|
Require all granted
|
||||||
|
</Directory>
|
||||||
|
|
||||||
|
ProxyRequests Off
|
||||||
|
ProxyPreserveHost On
|
||||||
|
RequestHeader unset X-Forwarded-For early
|
||||||
|
RequestHeader unset Forwarded early
|
||||||
|
RequestHeader set X-Forwarded-Proto "https"
|
||||||
|
ProxyPass /api/ http://127.0.0.1:8787/api/ timeout=30
|
||||||
|
ProxyPassReverse /api/ http://127.0.0.1:8787/api/
|
||||||
|
|
||||||
|
Header always set X-Content-Type-Options "nosniff"
|
||||||
|
Header always set Referrer-Policy "same-origin"
|
||||||
|
Header always set Strict-Transport-Security "max-age=31536000"
|
||||||
|
Header always set Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'self'; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'"
|
||||||
|
|
||||||
|
ErrorLog ${APACHE_LOG_DIR}/amnesia-error.log
|
||||||
|
CustomLog ${APACHE_LOG_DIR}/amnesia-access.log combined
|
||||||
|
</VirtualHost>
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""Provision an administrator without exposing a password in shell history."""
|
||||||
|
import argparse
|
||||||
|
import getpass
|
||||||
|
from amnesia_licensing.app import Application, Settings, USERNAME
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("command", choices=["create-admin"])
|
||||||
|
parser.add_argument("--username", required=True)
|
||||||
|
args = parser.parse_args()
|
||||||
|
if not USERNAME.fullmatch(args.username):
|
||||||
|
parser.error("username must contain 3–24 letters, digits or underscores")
|
||||||
|
password = getpass.getpass("Password (12–128 characters): ")
|
||||||
|
if not 12 <= len(password) <= 128 or password != getpass.getpass("Confirm password: "):
|
||||||
|
parser.error("password length invalid or confirmation did not match")
|
||||||
|
app = Application(Settings.environment())
|
||||||
|
with app.connect() as db:
|
||||||
|
db.execute("BEGIN IMMEDIATE")
|
||||||
|
account = app.create_account(db, args.username, password, "admin")
|
||||||
|
print(f"Administrator {account['username']} created with UID {account['uid']}.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
waitress==3.0.2
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
"""Local development or production entry point."""
|
||||||
|
import argparse
|
||||||
|
import logging
|
||||||
|
from socketserver import ThreadingMixIn
|
||||||
|
from wsgiref.simple_server import WSGIServer, make_server
|
||||||
|
from amnesia_licensing.app import Application, Settings
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
parser.add_argument("--dev", action="store_true", help="loopback-only development server; enables first-account setup")
|
||||||
|
parser.add_argument("--port", type=int, default=8787)
|
||||||
|
args = parser.parse_args()
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
settings = Settings.environment()
|
||||||
|
settings.allow_local_setup = args.dev
|
||||||
|
settings.allow_loopback_origins = args.dev
|
||||||
|
app = Application(settings)
|
||||||
|
if args.dev:
|
||||||
|
class Server(ThreadingMixIn, WSGIServer):
|
||||||
|
daemon_threads = True
|
||||||
|
print(f"Licensing API: http://127.0.0.1:{args.port}", flush=True)
|
||||||
|
with make_server("127.0.0.1", args.port, app, server_class=Server) as server:
|
||||||
|
server.serve_forever()
|
||||||
|
else:
|
||||||
|
try:
|
||||||
|
from waitress import serve
|
||||||
|
except ImportError:
|
||||||
|
parser.error("install requirements.txt before starting the production server")
|
||||||
|
serve(app, listen=f"127.0.0.1:{args.port}", threads=4, trusted_proxy="127.0.0.1",
|
||||||
|
trusted_proxy_count=1, trusted_proxy_headers={"x-forwarded-for", "x-forwarded-proto"},
|
||||||
|
clear_untrusted_proxy_headers=True, max_request_body_size=16384)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
"""Manual browser-QA companion. Uses only disposable preview_* accounts."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from urllib.request import Request,urlopen
|
||||||
|
from urllib.error import HTTPError
|
||||||
|
|
||||||
|
|
||||||
|
def post(path,body,token=None):
|
||||||
|
headers={"Content-Type":"application/json"}
|
||||||
|
if token:headers["Authorization"]="Bearer "+token
|
||||||
|
request=Request("http://127.0.0.1:8789/api"+path,json.dumps(body).encode(),headers,method="POST")
|
||||||
|
try:
|
||||||
|
with urlopen(request,timeout=10) as response:return response.status,json.load(response)
|
||||||
|
except HTTPError as error:return error.code,json.load(error)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=="__main__":
|
||||||
|
hardware=hashlib.sha256(b"disposable browser qa device").hexdigest()
|
||||||
|
status,result=post("/client/activate",{"username":"preview_member","password":"local-qa-member-2026","hwid":hardware,"device_name":"preview desktop"})
|
||||||
|
assert status==200,result
|
||||||
|
token=result["token"]
|
||||||
|
status,verified=post("/client/verify",{"hwid":hardware},token)
|
||||||
|
assert status==200 and verified["valid"],verified
|
||||||
|
status,rejected=post("/client/verify",{"hwid":"b"*64},token)
|
||||||
|
assert status==403 and rejected["code"]=="hwid_mismatch",rejected
|
||||||
|
print(f"PASS: production HTTP server activation, UID {verified['account']['uid']}, device tie, token verification and wrong-device rejection")
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
"""Disposable HTTP integration test for the native Windows client. No user DB/HWID."""
|
||||||
|
import json
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import threading
|
||||||
|
from pathlib import Path
|
||||||
|
from wsgiref.simple_server import make_server, WSGIRequestHandler
|
||||||
|
|
||||||
|
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||||
|
from amnesia_licensing.app import Application, Settings
|
||||||
|
from test_api import Browser, PASSWORD
|
||||||
|
|
||||||
|
class QuietHandler(WSGIRequestHandler):
|
||||||
|
def log_message(self,*args):pass
|
||||||
|
|
||||||
|
def check(outage=False):
|
||||||
|
executable=Path(__file__).resolve().parents[2]/"client/build/tests/licensing_test.exe"
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
app=Application(Settings(Path(directory),allow_local_setup=True,rate_limit=False,client_seconds=3))
|
||||||
|
admin,user=Browser(app),Browser(app)
|
||||||
|
assert admin.request("/api/setup",{"username":"owner","password":PASSWORD})[0]==200
|
||||||
|
assert user.request("/api/auth/register",{"username":"member","password":PASSWORD})[0]==200
|
||||||
|
issued=admin.request("/api/admin/licenses",{"label":"native test","duration_days":30})[1]
|
||||||
|
assert user.request("/api/licenses/redeem",{"key":issued["key"]})[0]==200
|
||||||
|
failing=threading.Event()
|
||||||
|
def gateway(environ,start):
|
||||||
|
if failing.is_set() and environ.get("PATH_INFO")=="/api/client/verify":
|
||||||
|
start("503 Service Unavailable",[("Content-Type","application/json")])
|
||||||
|
return [b'{"error":"test outage"}']
|
||||||
|
return app(environ,start)
|
||||||
|
with make_server("127.0.0.1",0,gateway,handler_class=QuietHandler) as server:
|
||||||
|
thread=threading.Thread(target=server.serve_forever);thread.start()
|
||||||
|
try:
|
||||||
|
child=subprocess.Popen([str(executable),f"http://127.0.0.1:{server.server_port}/api"],stdout=subprocess.PIPE,stderr=subprocess.STDOUT,text=True)
|
||||||
|
for line in child.stdout:
|
||||||
|
print(line,end="",flush=True)
|
||||||
|
if "worker activated" in line:
|
||||||
|
if outage:failing.set()
|
||||||
|
else:assert admin.request(f"/api/admin/licenses/{issued['license']['id']}/revoke",{})[0]==200
|
||||||
|
assert child.wait(timeout=15)==0
|
||||||
|
finally:
|
||||||
|
if child.poll() is None:child.kill();child.wait()
|
||||||
|
server.shutdown();thread.join()
|
||||||
|
|
||||||
|
if __name__=="__main__":
|
||||||
|
check();print("native revocation passed")
|
||||||
|
check(outage=True);print("native outage expiry passed")
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
import hashlib
|
||||||
|
import io
|
||||||
|
import json
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from unittest.mock import patch
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
from pathlib import Path
|
||||||
|
from amnesia_licensing.app import Application, Settings
|
||||||
|
|
||||||
|
PASSWORD="a-test-password-1234"
|
||||||
|
HWID=hashlib.sha256(b"test device one").hexdigest()
|
||||||
|
SECOND=hashlib.sha256(b"test device two").hexdigest()
|
||||||
|
|
||||||
|
|
||||||
|
class Browser:
|
||||||
|
def __init__(self, app):
|
||||||
|
self.app,self.cookie,self.csrf=app,"",""
|
||||||
|
|
||||||
|
def request(self, path, body=None, origin=None, csrf=None, token=None, remote="127.0.0.1"):
|
||||||
|
payload=json.dumps(body).encode() if body is not None else b""
|
||||||
|
environ={"REQUEST_METHOD":"POST" if body is not None else "GET","PATH_INFO":path,
|
||||||
|
"CONTENT_TYPE":"application/json","CONTENT_LENGTH":str(len(payload)),"wsgi.input":io.BytesIO(payload),
|
||||||
|
"HTTP_ORIGIN":origin if origin is not None else self.app.settings.origin,"REMOTE_ADDR":remote,
|
||||||
|
"HTTP_COOKIE":self.cookie,"HTTP_X_CSRF_TOKEN":self.csrf if csrf is None else csrf}
|
||||||
|
if token:environ["HTTP_AUTHORIZATION"]="Bearer "+token
|
||||||
|
response={}
|
||||||
|
def start(status,headers):response.update(status=int(status.split()[0]),headers=dict(headers))
|
||||||
|
result=json.loads(b"".join(self.app(environ,start)))
|
||||||
|
cookie=response["headers"].get("Set-Cookie")
|
||||||
|
if cookie:self.cookie=cookie.split(";")[0]
|
||||||
|
if "csrf" in result:self.csrf=result["csrf"] or ""
|
||||||
|
return response["status"],result,response["headers"]
|
||||||
|
|
||||||
|
|
||||||
|
class LicensingTests(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.temp=tempfile.TemporaryDirectory()
|
||||||
|
self.app=Application(Settings(Path(self.temp.name),allow_local_setup=True,rate_limit=False))
|
||||||
|
self.admin=Browser(self.app)
|
||||||
|
status,owner,_=self.admin.request("/api/setup",{"username":"owner","password":PASSWORD})
|
||||||
|
self.assertEqual(status,200);self.assertEqual(owner["account"]["uid"],1)
|
||||||
|
self.user=Browser(self.app)
|
||||||
|
status,result,_=self.user.request("/api/auth/register",{"username":"member","password":PASSWORD})
|
||||||
|
self.assertEqual(status,200);self.uid=result["account"]["uid"]
|
||||||
|
|
||||||
|
def tearDown(self):self.temp.cleanup()
|
||||||
|
|
||||||
|
def issue(self,days=30):
|
||||||
|
status,value,_=self.admin.request("/api/admin/licenses",{"label":"amnesia access","duration_days":days})
|
||||||
|
self.assertEqual(status,200)
|
||||||
|
return value
|
||||||
|
|
||||||
|
def activate(self,hardware=HWID):
|
||||||
|
return self.user.request("/api/client/activate",{"username":"member","password":PASSWORD,"hwid":hardware,"device_name":"test pc"})
|
||||||
|
|
||||||
|
def redeem(self,issued=None):
|
||||||
|
issued=issued or self.issue()
|
||||||
|
status,_,_=self.user.request("/api/licenses/redeem",{"key":issued["key"]})
|
||||||
|
self.assertEqual(status,200)
|
||||||
|
return issued
|
||||||
|
|
||||||
|
def test_accounts_uid_auth_and_roles(self):
|
||||||
|
self.assertEqual(self.uid,2)
|
||||||
|
self.assertEqual(self.user.request("/api/admin/overview")[0],403)
|
||||||
|
self.assertEqual(Browser(self.app).request("/api/account")[0],401)
|
||||||
|
self.assertEqual(Browser(self.app).request("/api/auth/register",{"username":"MEMBER","password":PASSWORD})[0],409)
|
||||||
|
status,value,headers=Browser(self.app).request("/api/auth/login",{"username":"MEMBER","password":PASSWORD})
|
||||||
|
self.assertEqual(status,200);self.assertEqual(value["account"]["uid"],2)
|
||||||
|
self.assertIn("HttpOnly",headers["Set-Cookie"]);self.assertIn("SameSite=Strict",headers["Set-Cookie"])
|
||||||
|
self.assertEqual(Browser(self.app).request("/api/auth/login",{"username":"member","password":"wrong-password"})[0],401)
|
||||||
|
|
||||||
|
def test_first_setup_is_local_one_time_only(self):
|
||||||
|
self.assertEqual(Browser(self.app).request("/api/setup",{"username":"second","password":PASSWORD})[0],403)
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
app=Application(Settings(Path(directory),allow_local_setup=True,rate_limit=False))
|
||||||
|
self.assertEqual(Browser(app).request("/api/setup",{"username":"attacker","password":PASSWORD},remote="203.0.113.1")[0],403)
|
||||||
|
|
||||||
|
def test_redemption_single_use_and_first_device_binding(self):
|
||||||
|
key=self.redeem()
|
||||||
|
self.assertEqual(self.user.request("/api/licenses/redeem",{"key":key["key"]})[0],400)
|
||||||
|
status,activated,_=self.activate()
|
||||||
|
self.assertEqual(status,200);self.assertEqual(activated["account"]["uid"],self.uid)
|
||||||
|
status,verified,_=self.user.request("/api/client/verify",{"hwid":HWID},token=activated["token"])
|
||||||
|
self.assertEqual(status,200);self.assertTrue(verified["valid"])
|
||||||
|
self.assertEqual(self.activate(SECOND)[1]["code"],"hwid_mismatch")
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":SECOND},token=activated["token"])[0],403)
|
||||||
|
|
||||||
|
def test_unlicensed_cannot_activate_or_bind(self):
|
||||||
|
self.assertEqual(self.activate()[1]["code"],"license_required")
|
||||||
|
self.assertFalse(self.user.request("/api/account")[1]["account"]["hwid_bound"])
|
||||||
|
|
||||||
|
def test_client_renewal_is_bounded_and_logout_invalidates(self):
|
||||||
|
issued=self.redeem();activated=self.activate()[1];token=activated["token"]
|
||||||
|
self.assertGreater(activated["expires_at"],activated["server_time"])
|
||||||
|
moment=activated["expires_at"]-10
|
||||||
|
with patch("amnesia_licensing.app.time.time",return_value=moment):
|
||||||
|
status,renewed,_=self.user.request("/api/client/verify",{"hwid":HWID,"renew":True},token=token)
|
||||||
|
self.assertEqual(status,200)
|
||||||
|
self.assertEqual(renewed["expires_at"],moment+self.app.settings.client_seconds)
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":SECOND,"renew":True},token=token)[0],403)
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":HWID,"renew":1},token=token)[0],400)
|
||||||
|
with self.app.connect() as db:
|
||||||
|
db.execute("UPDATE licenses SET expires_at=? WHERE id=?",(moment+30,issued["license"]["id"]))
|
||||||
|
bounded=self.user.request("/api/client/verify",{"hwid":HWID,"renew":True},token=token)[1]
|
||||||
|
self.assertEqual(bounded["expires_at"],moment+30)
|
||||||
|
self.assertEqual(self.user.request("/api/client/logout",{"hwid":SECOND},token=token)[0],403)
|
||||||
|
self.assertEqual(self.user.request("/api/client/logout",{"hwid":HWID},token=token)[0],200)
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":HWID,"renew":True},token=token)[0],401)
|
||||||
|
|
||||||
|
def test_expired_token_cannot_be_renewed(self):
|
||||||
|
self.redeem();activated=self.activate()[1]
|
||||||
|
with patch("amnesia_licensing.app.time.time",return_value=activated["expires_at"]):
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":HWID,"renew":True},token=activated["token"])[0],401)
|
||||||
|
|
||||||
|
def test_revocation_and_expiration_block_tokens(self):
|
||||||
|
issued=self.redeem();token=self.activate()[1]["token"]
|
||||||
|
self.assertEqual(self.admin.request(f"/api/admin/licenses/{issued['license']['id']}/revoke",{})[0],200)
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":HWID},token=token)[0],401)
|
||||||
|
issued=self.redeem();token=self.activate()[1]["token"]
|
||||||
|
with self.app.connect() as db:db.execute("UPDATE licenses SET expires_at=1 WHERE id=?",(issued["license"]["id"],))
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":HWID},token=token)[0],403)
|
||||||
|
self.assertEqual(self.activate()[0],403)
|
||||||
|
self.assertIn("expired",[l["status"] for l in self.user.request("/api/account")[1]["licenses"]])
|
||||||
|
|
||||||
|
def test_hwid_reset_request_approval_invalidates_old_tokens(self):
|
||||||
|
self.redeem();token=self.activate()[1]["token"]
|
||||||
|
self.assertEqual(self.user.request("/api/account/hwid-reset",{"reason":"new computer"})[0],200)
|
||||||
|
self.assertEqual(len(self.admin.request("/api/admin/overview")[1]["reset_requests"]),1)
|
||||||
|
self.assertEqual(self.user.request(f"/api/admin/accounts/{self.uid}/reset-hwid",{})[0],403)
|
||||||
|
self.assertEqual(self.admin.request(f"/api/admin/accounts/{self.uid}/reset-hwid",{})[0],200)
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":HWID},token=token)[0],401)
|
||||||
|
self.assertEqual(self.activate(SECOND)[0],200)
|
||||||
|
self.assertIsNone(self.user.request("/api/account")[1]["reset_request"])
|
||||||
|
|
||||||
|
def test_password_change_and_account_disable_end_sessions(self):
|
||||||
|
self.redeem();token=self.activate()[1]["token"]
|
||||||
|
self.assertEqual(self.admin.request(f"/api/admin/accounts/{self.uid}/status",{"enabled":False})[0],200)
|
||||||
|
self.assertEqual(self.user.request("/api/account")[0],401)
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":HWID},token=token)[0],401)
|
||||||
|
self.assertEqual(self.admin.request("/api/admin/accounts/1/status",{"enabled":False})[0],409)
|
||||||
|
self.admin.request(f"/api/admin/accounts/{self.uid}/status",{"enabled":True})
|
||||||
|
self.user.request("/api/auth/login",{"username":"member","password":PASSWORD})
|
||||||
|
self.assertEqual(self.user.request("/api/account/password",{"current_password":PASSWORD,"new_password":"a-new-password-4567"})[0],200)
|
||||||
|
self.assertEqual(self.user.request("/api/account")[0],401)
|
||||||
|
self.assertEqual(self.user.request("/api/auth/login",{"username":"member","password":PASSWORD})[0],401)
|
||||||
|
self.assertEqual(self.user.request("/api/auth/login",{"username":"member","password":"a-new-password-4567"})[0],200)
|
||||||
|
|
||||||
|
def test_csrf_origin_and_sql_injection_boundaries(self):
|
||||||
|
self.assertEqual(self.admin.request("/api/admin/licenses",{"label":"x","duration_days":30},csrf="wrong")[0],403)
|
||||||
|
self.assertEqual(self.admin.request("/api/admin/licenses",{"label":"x","duration_days":30},origin="https://evil.example")[0],403)
|
||||||
|
self.assertEqual(self.user.request("/api/licenses/redeem",{"key":"' OR 1=1 --"})[0],400)
|
||||||
|
self.assertEqual(self.admin.request("/api/admin/licenses",{"label":"x","duration_days":True})[0],400)
|
||||||
|
self.assertEqual(self.admin.request("/api/admin/licenses",{"label":" ","duration_days":30})[0],400)
|
||||||
|
self.assertEqual(self.activate("not a hardware hash")[0],400)
|
||||||
|
|
||||||
|
def test_no_plaintext_secrets_in_database_or_public_views(self):
|
||||||
|
issued=self.redeem(self.issue(None));token=self.activate()[1]["token"]
|
||||||
|
with self.app.connect() as db:dump="\n".join(db.iterdump())
|
||||||
|
for secret in (PASSWORD,HWID,issued["key"],token):self.assertNotIn(secret,dump)
|
||||||
|
public=json.dumps(self.user.request("/api/account")[1])
|
||||||
|
for internal in ("password_hash","key_hash","hwid_hash","token_hash"):self.assertNotIn(internal,public)
|
||||||
|
self.assertIsNone(self.user.request("/api/account")[1]["licenses"][0]["expires_at"])
|
||||||
|
|
||||||
|
def test_concurrent_redemption_only_succeeds_once(self):
|
||||||
|
issued=self.issue()
|
||||||
|
def redeem(_):return self.user.request("/api/licenses/redeem",{"key":issued["key"]})[0]
|
||||||
|
with ThreadPoolExecutor(max_workers=2) as pool:statuses=list(pool.map(redeem,range(2)))
|
||||||
|
self.assertEqual(sorted(statuses),[200,400])
|
||||||
|
|
||||||
|
def test_rate_limits_persist_on_failed_logins(self):
|
||||||
|
self.app.settings.rate_limit=True
|
||||||
|
visitor=Browser(self.app)
|
||||||
|
statuses=[visitor.request("/api/auth/login",{"username":"unknown","password":PASSWORD})[0] for _ in range(13)]
|
||||||
|
self.assertEqual(statuses[-1],429)
|
||||||
|
|
||||||
|
def test_client_token_expiry(self):
|
||||||
|
self.redeem();token=self.activate()[1]["token"]
|
||||||
|
with self.app.connect() as db:db.execute("UPDATE client_tokens SET expires_at=1")
|
||||||
|
self.assertEqual(self.user.request("/api/client/verify",{"hwid":HWID},token=token)[0],401)
|
||||||
|
|
||||||
|
def test_public_registration_cannot_choose_role_or_uid(self):
|
||||||
|
status,result,_=Browser(self.app).request("/api/auth/register",{"username":"ordinary","password":PASSWORD,"role":"admin","uid":999})
|
||||||
|
self.assertEqual(status,200)
|
||||||
|
self.assertEqual(result["account"]["role"],"user")
|
||||||
|
self.assertEqual(result["account"]["uid"],3)
|
||||||
|
|
||||||
|
def test_production_setup_disabled_and_https_cookie_secure(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
app=Application(Settings(Path(directory),origin="https://amnesia.example.com",secure_cookies=True,rate_limit=False))
|
||||||
|
visitor=Browser(app)
|
||||||
|
self.assertEqual(visitor.request("/api/setup",{"username":"owner","password":PASSWORD})[0],403)
|
||||||
|
with app.connect() as db:app.create_account(db,"owner",PASSWORD,"admin")
|
||||||
|
status,_,headers=visitor.request("/api/auth/login",{"username":"owner","password":PASSWORD})
|
||||||
|
self.assertEqual(status,200)
|
||||||
|
self.assertIn("; Secure",headers["Set-Cookie"])
|
||||||
|
self.assertFalse(visitor.request("/api/session")[1]["setup_required"])
|
||||||
|
|
||||||
|
def test_two_devices_cannot_win_first_binding_concurrently(self):
|
||||||
|
self.redeem()
|
||||||
|
with ThreadPoolExecutor(max_workers=2) as pool:
|
||||||
|
results=list(pool.map(lambda hardware:self.activate(hardware)[0],(HWID,SECOND)))
|
||||||
|
self.assertEqual(sorted(results),[200,403])
|
||||||
|
|
||||||
|
def test_dev_accepts_only_same_port_loopback_origins(self):
|
||||||
|
self.app.settings.allow_loopback_origins=True
|
||||||
|
status,_,_=Browser(self.app).request("/api/auth/login",{"username":"owner","password":PASSWORD},origin="http://localhost:5173")
|
||||||
|
self.assertEqual(status,200)
|
||||||
|
for origin in ("http://localhost:5174","https://localhost:5173","http://evil.example:5173",
|
||||||
|
"http://127.0.0.1.evil.example:5173","null","", "http://localhost:5173/path",
|
||||||
|
"http://user@localhost:5173","http://localhost:bad"):
|
||||||
|
self.assertFalse(self.app.origin_allowed(origin),origin)
|
||||||
|
self.app.settings.allow_loopback_origins=False
|
||||||
|
self.assertFalse(self.app.origin_allowed("http://localhost:5173"))
|
||||||
|
self.assertTrue(self.app.origin_allowed("http://127.0.0.1:5173"))
|
||||||
|
|
||||||
|
def test_first_admin_setup_from_localhost(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
app=Application(Settings(Path(directory),allow_local_setup=True,allow_loopback_origins=True,rate_limit=False))
|
||||||
|
status,result,_=Browser(app).request("/api/setup",{"username":"owner","password":PASSWORD},origin="http://localhost:5173")
|
||||||
|
self.assertEqual(status,200)
|
||||||
|
self.assertEqual(result["account"]["uid"],1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=="__main__":unittest.main()
|
||||||
Reference in new issue
Block a user