Tüm kaynaklar

Docker ve UniFi kurulum uyarlamalarının tam kaynakları. Kodlar burada çalıştırılmaz.

Kod editörüne dön

common.py

2454 bayt · TXT indir

"""Shared conservative validation; Python 3.10+. No network at import."""
import json
import os
from pathlib import Path
import re
import ssl
import tempfile
from urllib.parse import urlsplit
import urllib.request

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise ValueError('Redirect refused; configure the exact target URL')

def https_url(value):
    p = urlsplit(value)
    if p.scheme != 'https' or not p.hostname or p.username or p.password or p.query or p.fragment:
        raise ValueError('Expected HTTPS URL without credentials/query/fragment')
    _ = p.port
    return p

def hostname(value):
    if len(value) > 253 or not re.fullmatch(r'[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?', value):
        raise ValueError('Invalid hostname')
    if any(not x or len(x) > 63 or x.startswith('-') or x.endswith('-') for x in value.split('.')):
        raise ValueError('Invalid DNS label')
    return value

def timeout_value(value):
    value = float(value)
    if not 0.1 <= value <= 30:
        raise ValueError('Timeout must be between 0.1 and 30 seconds')
    return value

def tls_context(cafile=None):
    return ssl.create_default_context(cafile=cafile or None)

def opener(cafile=None, cookies=None):
    handlers = [NoRedirect(), urllib.request.ProxyHandler({}),
                urllib.request.HTTPSHandler(context=tls_context(cafile))]
    if cookies is not None:
        handlers.append(urllib.request.HTTPCookieProcessor(cookies))
    return urllib.request.build_opener(*handlers)

def atomic_json(directory, filename, data):
    directory = Path(directory).expanduser()
    directory.mkdir(parents=True, exist_ok=True, mode=0o700)
    if directory.is_symlink():
        raise ValueError('State directory must not be a symlink')
    directory.chmod(0o700)
    name = None
    try:
        with tempfile.NamedTemporaryFile(mode='w', encoding='utf-8', dir=directory, delete=False) as f:
            name = f.name
            os.fchmod(f.fileno(), 0o600)
            json.dump(data, f, ensure_ascii=False, indent=2)
            f.write('\n')
            f.flush()
            os.fsync(f.fileno())
        os.replace(name, directory / filename)
        fd = os.open(directory, os.O_RDONLY)
        try:
            os.fsync(fd)
        finally:
            os.close(fd)
    finally:
        if name and os.path.exists(name):
            os.unlink(name)

docker_inventory.py

3268 bayt · TXT indir

#!/usr/bin/env python3
"""Read-only local Docker inventory. Default output contains aggregate counts only."""
import argparse
import collections
import datetime as dt
import json
import re
import shutil
import subprocess
import sys


def summarize(objects):
    rows = []
    seen = set()
    for item in objects:
        identity = item['Id']
        if identity in seen:
            raise ValueError('Duplicate container ID')
        seen.add(identity)
        state = item['State']
        config = item.get('Config') or {}
        host = item.get('HostConfig') or {}
        health = (state.get('Health') or {}).get('Status', 'not_configured')
        rows.append({'name': item.get('Name', '').lstrip('/'),
                     'image': config.get('Image', ''),
                     'state': state['Status'], 'running': bool(state['Running']),
                     'health': health, 'restart_count': item.get('RestartCount', 0),
                     'restart_policy': (host.get('RestartPolicy') or {}).get('Name', ''),
                     'log_driver': (host.get('LogConfig') or {}).get('Type', '')})
    return {'checked_at': dt.datetime.now(dt.timezone.utc).isoformat(),
            'total': len(rows), 'running': sum(x['running'] for x in rows),
            'state_counts': dict(collections.Counter(x['state'] for x in rows)),
            'health_counts': dict(collections.Counter(x['health'] for x in rows)),
            'restart_count_sum': sum(x['restart_count'] for x in rows),
            'containers': rows}


def collect(executable=None, runner=subprocess.run):
    docker = executable or shutil.which('docker')
    if not docker:
        raise ValueError('Docker CLI unavailable')
    # Ignore a remote DOCKER_HOST/context: this tool is explicitly for the local host.
    base = [docker, '--host', 'unix:///var/run/docker.sock']
    def invoke(arguments):
        return runner(base + arguments, check=True, capture_output=True,
                      text=True, timeout=20).stdout
    ids = invoke(['ps', '-aq', '--no-trunc']).split()
    if len(ids) != len(set(ids)) or any(not re.fullmatch('[0-9a-f]{64}', x) for x in ids):
        raise ValueError('Invalid container ID inventory')
    if not ids:
        return summarize([])
    data = json.loads(invoke(['inspect'] + ids))
    if not isinstance(data, list) or len(data) != len(ids) or {x['Id'] for x in data} != set(ids):
        raise ValueError('Docker inventory changed or inspect was incomplete; retry read-only')
    return summarize(data)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--docker-bin', help='Explicit Docker CLI path when sudo/cron has a restricted PATH')
    parser.add_argument('--details', action='store_true', help='Include selected non-secret fields; keep this output private')
    args = parser.parse_args()
    result = collect(args.docker_bin)
    if not args.details:
        result.pop('containers')
    print(json.dumps(result, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    try:
        main()
    except Exception as exc:
        # Do not echo daemon response bodies or host configuration on failure.
        print('Inventory failed: ' + type(exc).__name__, file=sys.stderr)
        sys.exit(1)

docker-compose.yml

415 bayt · TXT indir

services:
  speedtest:
    image: openspeedtest/latest@sha256:1127de0693c36bcf8c297c73d09891df8ec243680d027a6b6fab13fa0954ff46
    ports:
      - "${BIND_IP:?Set BIND_IP to your NAS LAN IPv4 address}:${HTTP_PORT:-3002}:3000"
    restart: unless-stopped
    logging:
      driver: json-file
      options:
        max-size: "5m"
        max-file: "2"
    labels:
      com.centurylinklabs.watchtower.enable: "false"

docker.env.example

178 bayt · TXT indir

# Copy to .env; set your own NAS LAN address locally before config/start.
# Never use 0.0.0.0 as an unreviewed substitute. Check firewall/NAT separately.
BIND_IP=
HTTP_PORT=3002

evidence.json

2275 bayt · TXT indir

{
  "docker": {
    "checked_at": "2026-11-14T17:13:44.292751+00:00",
    "total": 27,
    "running": 27,
    "health_counts": {
      "not_configured": 19,
      "healthy": 8
    },
    "retired_grafana_prometheus_absent": true,
    "application_health_limit": "running is not application health; 19 containers have no Docker healthcheck"
  },
  "rf_snapshot": {
    "at_utc": "2026-11-14T17:01:04.807780+00:00",
    "mode": "monitor_only",
    "remote_configuration_writes": 0,
    "pagination_verified": true,
    "radios_config": [
      {
        "name": "wifi0",
        "radio": "ng",
        "channel": "11",
        "ht": "20",
        "tx_power_mode": "medium",
        "min_rssi_enabled": false
      },
      {
        "name": "wifi1",
        "radio": "na",
        "channel": 124,
        "ht": "160",
        "tx_power_mode": "auto",
        "min_rssi_enabled": false
      }
    ],
    "radios_runtime": [
      {
        "radio": "ng",
        "channel": 11,
        "state": "RUN",
        "cu_total": 10,
        "tx_retries_pct": 17.8,
        "num_sta": 7,
        "satisfaction": 97
      },
      {
        "radio": "na",
        "channel": 124,
        "state": "RUN",
        "cu_total": 1,
        "tx_retries_pct": 0.0,
        "num_sta": 4,
        "satisfaction": 99
      }
    ],
    "channel_coverage_validated": false,
    "channel_recommendation": null,
    "event_counts": {
      "CLIENT_CONNECTED_WIRELESS_2": 7,
      "CLIENT_DISCONNECTED_WIRELESS_2": 7
    }
  },
  "verification_scope": {
    "production_read_only_inventory": true,
    "existing_openspeedtest_homepage_http": 200,
    "new_compose_deployment": false,
    "rf_adaptation_live_authenticated_run_in_this_publication": false,
    "firewall_changes_in_this_publication": false,
    "speed_test_started": false,
    "full_application_or_database_restore": false,
    "native_docker_compose_config_valid": true,
    "unit_tests_passed": 18,
    "explicit_controller_url_required": true
  },
  "public_inventory_actual_run": {
    "checked_at": "2026-11-14T17:27:08.238361+00:00",
    "total": 27,
    "running": 27,
    "state_counts": {
      "running": 27
    },
    "health_counts": {
      "not_configured": 19,
      "healthy": 8
    },
    "restart_count_sum": 0
  }
}

README.md

6232 bayt · TXT indir

# Docker ve UniFi kurulum kaynakları · 1.0.0

Bu paket iki rehberin okunabilir, taşınabilir kaynaklarını içerir. Üretimdeki özel otomasyonun birebir kopyası değildir. Gerçek kimlik bilgisi, istemci listesi veya özel ağ adresi içermez. Kontrolün tarihli sınırları evidence.json dosyasındadır.

## Doğrulananlar

- NAS üzerinde salt okunur Docker envanteri alındı. Bu paketin docker_inventory.py uyarlaması da gerçek NAS üzerinde çalıştırıldı.
- docker-compose.yml, NAS'taki Docker Compose ile `config --quiet` aşamasından geçti. Bu dosyayla yeni servis oluşturulmadı; mevcut servis yeniden başlatılmadı.
- Mevcut OpenSpeedTest ana sayfası HTTP 200 ve beklenen sayfa kimliğiyle doğrulandı. Hız testi başlatılmadı.
- 18 birim testi yerel Python ve NAS Python ortamında geçti. Bu testlerde kullanılan yapay veriler yalnız test girdileridir, canlı ağ ölçümü değildir.
- UniFi gözlemi mevcut zamanlanmış monitörün tarihli, kişisel alanları çıkarılmış raporundan alınır. Bu dağıtımın TLS-doğrulamalı UniFi istemcisiyle yeni bir canlı oturum bu yayın işi kapsamında sınanmadı.

## Docker / Container Manager

Dosyalar: docker-compose.yml, docker.env.example ve docker_inventory.py.

1. Container Manager'ın modelinde desteklendiğini kontrol et. Mevcut kurulum varsa ikinci aynı servisi başlatma.
2. Yalnız bu proje için seçtiğin özel klasörde `docker.env.example` dosyasını `.env` adıyla kopyala; kendi NAS LAN adresini yerel editörde BIND_IP alanına gir. Host portunun boş olduğunu kontrol et.
3. `docker compose -p baa-speedtest -f docker-compose.yml config --quiet` yalnız yapılandırma kontrolüdür.
4. Yeni kurulum yapmaya karar verirsen `docker compose -p baa-speedtest -f docker-compose.yml up -d speedtest` servis oluşturur. Çalışma öncesi bu yan etkiyi ve ağ erişimini değerlendir.
5. Container durumunu ve uygulama sayfasını ayrı doğrula. WAN yönlendirmesi açma. Uygulama veritabanı ve kalıcı depolama örneği bu stateless projede yoktur.

Bu imaj referansı 14 Kasım 2026'da mevcut çalışan OpenSpeedTest örneğinden okunan resmî digest'tir; en yeni veya güvenlik açığı olmayan sürüm iddiası değildir.

Envanter aracı varsayılan olarak yalnız toplamları basar:

```sh
python3 docker_inventory.py
```

NAS sudo/cron ortamında PATH kısıtlıysa Docker CLI yolunu açıkça ver:

```sh
python3 docker_inventory.py --docker-bin /usr/local/bin/docker
```

Yetki gerekiyorsa kendi onaylı yönetim yolunu kullan. Bu araç sudo çağırmaz, yetki değiştirmez, container başlatmaz veya imaj çekmez. `--details` seçilmiş alanları ekler; bu çıktıyı özel tut. Ortam değişkenleri ve ham inspect nesneleri hiçbir modda dışarı yazılmaz. Eksik/yarışan envanterde araç hata verir; sessizce eksik toplam sunmaz.

## UniFi salt okunur izleme

Dosyalar: unifi_rf_monitor.py, common.py, unifi.env.example, run-unifi.sh.

Mevcut UniFi OS konsolundaki Network uygulaması içindir; Docker'a ikinci controller kurmaz. Yerel API yolları ürün sürümüne bağlıdır. Ayrı yetkili entegrasyon hesabı ve mümkün olan en düşük görüntüleme yetkisini kullan. 2FA'yı kapatma.

1. Dosyaları yalnız sana ait, yazma yetkisi sınırlı bir dizine çıkar. Python 3 sürümünü kontrol et; yeni kurulum için güncel desteklenen Python sürümünü kullan.
2. `cp unifi.env.example unifi.env` ile özel dosyanı oluştur. `chmod 700 . run-unifi.sh` ve `chmod 600 unifi.env` ile dizin/dosya izinlerini sınırla.
3. unifi.env dosyasını yerel editörde düzenle: zorunlu kontrolcü HTTPS adresi (boş bırakılırsa bağlantı kurulmaz), site, AP adı, yetkili kullanıcı ve parola. Örnek controller.example.com ve AP-lab senin cihazın değildir. Parola komut satırına, crontab'a veya sohbete yazılmaz.
4. Kendi CA'n varsa UNIFI_CA_FILE ile yayımlanabilir CA sertifikasını göster; özel anahtar değil. İstemci TLS doğrulamasını kapatmaz, başka sunucuya yönlendirmeyi izlemez ve ortam proxy'lerini kullanmaz.
5. `./run-unifi.sh` komutunu önce elle çalıştır. Başarıda stdout boş; hata çıkış kodu sıfırdan farklıdır. Normal rapor varsayılan olarak `~/.local/state/homelab-rf/latest.json` dosyasına, dizin 0700 ve dosya 0600 ile yazılır. İstemci isimleri ve MAC/IP alanları rapora eklenmez.
6. Manuel çalışma doğrulanınca DSM Görev Zamanlayıcı veya kendi cron'unla wrapper'ın mutlak yolunu zamanla. Çalışma kullanıcısı, Python PATH'i, çalışma klasörü, saat dilimi ve hata teslimini ayrıca doğrula. Zamanlayıcıda Python yolu kısıtlıysa özel unifi.env içinde PYTHON_BIN değerini doğrulanmış mutlak yorumlayıcı yoluna ayarla. Bu paket hiçbir zamanlanmış görev oluşturmaz.

GET yalnız üç veri yolu için, POST yalnız oturum açma ve salt okunur günlük sorgusu için izinlidir. PUT/PATCH/DELETE ve RF tarama/yapılandırma/adoption POST'ları taşımadan önce reddedilir. Bu istemci kısıtı, hesabın controller üzerindeki yetkilerini kendiliğinden azaltmaz.

Komşu önbelleği bütün kanallarda karşılaştırılabilir ölçüm değildir. Boş kanalı temiz sayma; kod bu veriden kanal önerisi üretmez. Bir API veya zamanlayıcı başarısı, IoT uygulama akışlarının veya kesintisiz video oynatmanın kanıtı değildir.

## Testler

```sh
python3 test_guides.py
sh -n run-unifi.sh
```

Testler Docker/UniFi ağ değişikliği yapmaz. Gerçek parola veya controller erişimi gerekmez. Test fixture'larını gerçek ölçüm sonucu diye sunma.

## Güncelleme ve geri dönüş sınırı

İmaj digest'i sabitlemek veriyi geri getirmez. Bu paket uygulama/veritabanı geri yükleme aracı, otomatik güncelleyici, firewall yazıcısı veya uzaktan erişim çözümü değildir. Bütün volume'leri temizleyen komutlar içermez. Yedek ve geri dönüşü uygulamanın kendi veri biçimine göre ayrıca sınamak gerekir.

Kaynaklar: https://kb.synology.com/en-us/DSM/help/ContainerManager/docker_project · https://github.com/openspeedtest/Docker-Image · https://docs.docker.com/reference/compose-file/services/ · https://help.ui.com/hc/en-us/articles/360012947634-Maximizing-Wireless-Speeds

run-unifi.sh

254 bayt · TXT indir

#!/bin/sh
set -eu
umask 077
cd -- "$(CDPATH= cd -- "$(dirname -- "$0")" && pwd -P)"
if [ ! -f ./unifi.env ]; then
  printf '%s\n' 'Missing private unifi.env' >&2
  exit 1
fi
set -a
. ./unifi.env
set +a
exec "${PYTHON_BIN:-python3}" ./unifi_rf_monitor.py

SHA256SUMS

896 bayt · TXT indir

71c81e2b72bed6d1ceb49847ecd6c036157187e82895447a81b47fec8b8f209c  LICENSE.txt
9afa9cb47357c2796834bcb7b58d405fd6cd36bd1f1ccddb10e2f5733cec76c6  README.md
91c0bb6e226cc993188b708a4b50e6896b87ee32edd1584b354eba1135a844ce  common.py
dd8939afdd5d2681b3cdbaba7fc2c7628938b6f44f91340001797d480f67e62c  docker-compose.yml
2ec50e3d392f1c5ac2178a71b1c5941281ce6583ccbdf1ecc9e1d15be588a16c  docker.env.example
42e84ffe3d9b2d6717268d6c93396b25bd64f9a78f7f2cb6c77392a801386d3c  docker_inventory.py
04fa5dbb9ec22d04f4b453f1f64d3bbc8b0e40cd3584fa2658d3cbb032d38293  evidence.json
5a0779852e35cd8a10936e947ce78c587777f75b14f744135487b4d5a47b63a0  run-unifi.sh
172a8e2220cdb50ec0156e99cb31e58a9ca0af93d010f9e4625df622450d7249  test_guides.py
5e07d24d7423109f471a6fd62662d9cf438a377870373df04b7ae49b02139d91  unifi.env.example
c3c137747412f1297c3e3d61750f7bef8f6c3c50880eaa5f79f9299812c6b3e7  unifi_rf_monitor.py

test_guides.py

6406 bayt · TXT indir

import datetime as dt
import io
import json
from pathlib import Path
import subprocess
import tempfile
import types
import unittest
from unittest.mock import patch

import docker_inventory as inventory
import common
import unifi_rf_monitor as rf


def fixture(identity='a' * 64, health=None, running=True):
    state = {'Status': 'running' if running else 'exited', 'Running': running}
    if health is not None:
        state['Health'] = {'Status': health}
    return {'Id': identity, 'Name': '/fixture-service', 'State': state,
            'RestartCount': 0, 'Config': {'Image': 'example/fixture:unit-test',
            'Env': ['UNIT_TEST_SECRET=fixture-not-a-credential']},
            'HostConfig': {'RestartPolicy': {'Name': 'unless-stopped'},
            'LogConfig': {'Type': 'json-file'}}}


class InventoryTests(unittest.TestCase):
    def test_absent_health_is_not_healthy(self):
        data = inventory.summarize([fixture()])
        self.assertEqual(data['health_counts'], {'not_configured': 1})

    def test_stopped_container_is_included(self):
        data = inventory.summarize([fixture(running=False)])
        self.assertEqual((data['total'], data['running']), (1, 0))

    def test_distinct_health_states(self):
        data = inventory.summarize([fixture(health='healthy'), fixture('b'*64, 'unhealthy')])
        self.assertEqual(data['health_counts'], {'healthy': 1, 'unhealthy': 1})

    def test_no_environment_values_exported(self):
        self.assertNotIn('fixture-not-a-credential', json.dumps(inventory.summarize([fixture()])))

    def test_duplicate_records_refused(self):
        with self.assertRaises(ValueError):
            inventory.summarize([fixture(), fixture()])

    def test_empty_host_never_calls_inspect(self):
        calls = []
        def run(args, **kwargs):
            calls.append(args)
            return types.SimpleNamespace(stdout='')
        self.assertEqual(inventory.collect('docker', run)['total'], 0)
        self.assertEqual(len(calls), 1)
        self.assertEqual(calls[0][1:3], ['--host', 'unix:///var/run/docker.sock'])

    def test_inspect_disagreement_fails(self):
        def run(args, **kwargs):
            return types.SimpleNamespace(stdout='a'*64 if 'ps' in args else '[]')
        with self.assertRaises(ValueError):
            inventory.collect('docker', run)

    def test_only_ps_and_inspect_are_used(self):
        calls = []
        def run(args, **kwargs):
            calls.append(args[3])
            return types.SimpleNamespace(stdout='a'*64 if 'ps' in args else json.dumps([fixture()]))
        self.assertEqual(inventory.collect('docker', run)['total'], 1)
        self.assertEqual(calls, ['ps', 'inspect'])


class ReadOnlyMonitorTests(unittest.TestCase):
    def setUp(self):
        self.api = rf.ReadOnlyUniFi('https://controller.example.com')

    def test_remote_mutations_are_blocked_before_transport(self):
        paths = ['/proxy/network/api/s/default/rest/device/fixture',
                 '/proxy/network/api/s/default/cmd/devmgr',
                 '/proxy/network/v2/api/site/default/firewall-policies/batch-reorder']
        with patch.object(self.api.opener, 'open', side_effect=AssertionError('Network not permitted in tests')):
            for method in ['PUT', 'PATCH', 'DELETE', 'POST']:
                for path in paths:
                    with self.subTest(method=method, path=path), self.assertRaises(ValueError):
                        self.api.request(method, path, {})

    def test_missing_explicit_controller_fails_before_network(self):
        with patch.dict('os.environ', {'UNIFI_USERNAME':'fixture','UNIFI_PASSWORD':'fixture','UNIFI_AP_NAME':'Fixture-AP'}, clear=True):
            with self.assertRaises(ValueError):
                rf.main()

    def test_unknown_get_is_blocked(self):
        with self.assertRaises(ValueError):
            self.api.request('GET', '/api/unreviewed-path')

    def test_get_payload_is_blocked(self):
        with self.assertRaises(ValueError):
            self.api.request('GET', self.api.base_api + '/stat/device', {})

    def test_tls_verification_is_required(self):
        import ssl
        ctx = common.tls_context()
        self.assertTrue(ctx.check_hostname)
        self.assertEqual(ctx.verify_mode, ssl.CERT_REQUIRED)

    def test_bad_controller_urls_refused(self):
        for url in ['http://controller.example.com', 'https://user:pass@controller.example.com',
                    'https://controller.example.com/?token=fixture', 'https://controller.example.com/#fragment']:
            with self.subTest(url=url), self.assertRaises(ValueError):
                rf.ReadOnlyUniFi(url)

    def test_missing_pagination_records_refused(self):
        api = types.SimpleNamespace(logs_api='/logs', request=lambda *args: {
            'total_element_count': 1, 'total_page_count': 1, 'data': []})
        with self.assertRaises(ValueError):
            rf.logs(api, 0, 100)

    def test_empty_complete_window(self):
        api = types.SimpleNamespace(logs_api='/logs', request=lambda *args: {
            'total_element_count': 0, 'total_page_count': 0, 'data': []})
        self.assertEqual(rf.logs(api, 0, 100), [])

    def test_no_channel_recommendation_from_passive_cache(self):
        class API:
            logs_api = '/logs'
            def get_rows(self, suffix):
                return [{'type': 'uap', 'name': 'Fixture-AP', 'state': 1}] if suffix == '/stat/device' else []
            def request(self, *args):
                return {'total_element_count': 0, 'total_page_count': 0, 'data': []}
        result = rf.collect(API(), dt.datetime.now(dt.timezone.utc), 'Fixture-AP')
        self.assertEqual(result['remote_configuration_writes'], 0)
        self.assertFalse(result['channel_coverage_validated'])
        self.assertIsNone(result['channel_recommendation'])

    def test_atomic_private_state_permissions(self):
        import stat
        with tempfile.TemporaryDirectory() as directory:
            common.atomic_json(directory, 'latest.json', {'unit_test': True})
            self.assertEqual(stat.S_IMODE(Path(directory).stat().st_mode), 0o700)
            self.assertEqual(stat.S_IMODE((Path(directory)/'latest.json').stat().st_mode), 0o600)
            self.assertEqual(json.loads((Path(directory)/'latest.json').read_text()), {'unit_test': True})


if __name__ == '__main__':
    unittest.main(verbosity=2)

unifi_rf_monitor.py

7707 bayt · TXT indir

#!/usr/bin/env python3
"""Read-only educational adaptation. Internal UniFi APIs may change."""
import collections
import datetime as dt
import fcntl
import http.cookiejar
import json
import os
from pathlib import Path
import re
import sys
import urllib.request
from common import atomic_json, https_url, opener, timeout_value

class ReadOnlyUniFi:
    def __init__(self, base, site='default', cafile=None, timeout=10):
        p = https_url(base)
        if p.path not in ('', '/') or not re.fullmatch(r'[A-Za-z0-9_-]+', site):
            raise ValueError('Invalid controller base URL or site')
        self.base = base.rstrip('/')
        self.base_api = '/proxy/network/api/s/' + site
        self.logs_api = '/proxy/network/v2/api/site/' + site + '/system-log/all'
        self.read_paths = {self.base_api + s for s in ('/stat/device', '/stat/sta', '/stat/rogueap')}
        self.csrf = None
        self.timeout = timeout_value(timeout)
        self.opener = opener(cafile, http.cookiejar.CookieJar())

    def request(self, method, path, payload=None):
        # Exact path allowlist, not a prefix; redirects and ambient proxies disabled.
        if not ((method == 'GET' and path in self.read_paths and payload is None)
                or (method == 'POST' and path in {'/api/auth/login', self.logs_api})):
            raise ValueError('Read-only policy refused this operation')
        headers = {'Content-Type': 'application/json'}
        if self.csrf:
            headers['X-CSRF-Token'] = self.csrf
        req = urllib.request.Request(self.base + path, method=method, headers=headers,
            data=json.dumps(payload).encode() if payload is not None else None)
        with self.opener.open(req, timeout=self.timeout) as res:
            self.csrf = res.headers.get('x-csrf-token') or self.csrf
            raw = res.read(4_000_001)
            if len(raw) > 4_000_000:
                raise ValueError('Response size limit')
            return json.loads(raw)

    def get_rows(self, suffix):
        data = self.request('GET', self.base_api + suffix)['data']
        if not isinstance(data, list):
            raise ValueError('Unexpected rows schema')
        return data

def logs(api, start_ms, end_ms, max_pages=100, page_size=100):
    if not (1 <= max_pages <= 100 and 1 <= page_size <= 100 and start_ms <= end_ms):
        raise ValueError('Invalid pagination bounds')
    expected = pages = None
    events = []
    seen = set()
    for page in range(max_pages):
        data = api.request('POST', api.logs_api, {
            'timestampFrom': start_ms, 'timestampTo': end_ms,
            'pageNumber': page, 'pageSize': page_size, 'type': 'GENERAL'})
        total, count, rows = data['total_element_count'], data['total_page_count'], data['data']
        if type(total) is not int or type(count) is not int or total < 0 or count < 0:
            raise ValueError('Invalid pagination metadata')
        if not isinstance(rows, list) or len(rows) > page_size:
            raise ValueError('Invalid page rows')
        required = (total + page_size - 1) // page_size
        if count != required and not (total == 0 and count == 1):
            raise ValueError('Inconsistent page count')
        if count > max_pages:
            raise ValueError('Pagination safety limit reached')
        if expected is None:
            expected, pages = total, count
        if (total, count) != (expected, pages):
            raise ValueError('Fixed-window log total/pages changed')
        wanted = min(page_size, max(0, total - page * page_size))
        if len(rows) != wanted:
            raise ValueError('Incomplete page')
        for row in rows:
            identity = row['id']
            timestamp = row['timestamp']
            if not isinstance(identity, (str, int)) or isinstance(identity, bool) or identity in seen:
                raise ValueError('Duplicate/invalid log ID')
            if type(timestamp) not in (int, float) or not start_ms <= timestamp <= end_ms:
                raise ValueError('Log timestamp outside requested window')
            seen.add(identity)
            events.append(row)
        if page + 1 >= count:
            break
    else:
        raise ValueError('Pagination safety limit reached')
    if len(events) != expected:
        raise ValueError('Incomplete logs')
    return events

def fields(row, names):
    return {k: row[k] for k in names if k in row}

def collect(api, now, ap_name):
    if not ap_name or now.tzinfo is None:
        raise ValueError('AP name and timezone-aware datetime required')
    aps = [d for d in api.get_rows('/stat/device') if d.get('type') == 'uap' and d.get('name') == ap_name]
    if len(aps) != 1 or aps[0].get('state') != 1:
        raise ValueError('Configured AP missing, duplicated or offline')
    clients = [x for x in api.get_rows('/stat/sta') if not x.get('is_wired')]
    neighbors = api.get_rows('/stat/rogueap')
    fresh = [x for x in neighbors if type(x.get('last_seen')) in (int, float)
             and 0 <= now.timestamp() - x['last_seen'] <= 3600 and x.get('radio') == 'ng']
    events = logs(api, int((now - dt.timedelta(hours=24)).timestamp()*1000), int(now.timestamp()*1000))
    tracked = collections.Counter(x.get('key', 'UNKNOWN') for x in events
        if x.get('key') in {'CLIENT_CONNECTED_WIRELESS_2', 'CLIENT_DISCONNECTED_WIRELESS_2', 'AP_CHANGED_CHANNELS'})
    return {'at_utc': now.isoformat(), 'mode': 'monitor_only', 'remote_configuration_writes': 0,
        'log_total': len(events), 'pagination_verified': True,
        'ap': fields(aps[0], ['name', 'state', 'uptime', 'version']),
        'radios_config': [fields(x, ['radio', 'channel', 'ht', 'tx_power_mode']) for x in aps[0].get('radio_table', [])],
        'radios_runtime': [fields(x, ['radio', 'channel', 'cu_total', 'tx_retries_pct', 'num_sta']) for x in aps[0].get('radio_table_stats', [])],
        'clients': [fields(x, ['radio', 'signal', 'satisfaction', 'wifi_tx_retries_percentage']) for x in clients],
        'fresh_1h_bss_counts_by_channel': dict(collections.Counter(str(x.get('channel')) for x in fresh)),
        'event_counts': dict(tracked), 'channel_coverage_validated': False,
        'channel_recommendation': None,
        'coverage_note': 'Passive cached observations are not a comparable all-channel RF survey.'}

def main():
    os.umask(0o077)
    env = os.environ
    if not env.get('UNIFI_URL') or not env.get('UNIFI_USERNAME') or not env.get('UNIFI_PASSWORD') or not env.get('UNIFI_AP_NAME'):
        raise ValueError('Set UNIFI_URL, UNIFI_USERNAME, UNIFI_PASSWORD and UNIFI_AP_NAME')
    directory = Path(env.get('RF_STATE_DIR', '~/.local/state/homelab-rf')).expanduser()
    directory.mkdir(parents=True, exist_ok=True, mode=0o700)
    if directory.is_symlink():
        raise ValueError('Symlink state directory refused')
    directory.chmod(0o700)
    with (directory / '.lock').open('a') as lock:
        os.chmod(directory / '.lock', 0o600)
        try:
            fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
        except BlockingIOError:
            return
        api = ReadOnlyUniFi(env['UNIFI_URL'], env.get('UNIFI_SITE', 'default'),
                            env.get('UNIFI_CA_FILE'), env.get('CHECK_TIMEOUT', '10'))
        api.request('POST', '/api/auth/login', {'username': env['UNIFI_USERNAME'],
                    'password': env['UNIFI_PASSWORD'], 'rememberMe': False})
        atomic_json(directory, 'latest.json', collect(api, dt.datetime.now(dt.timezone.utc), env['UNIFI_AP_NAME']))

if __name__ == '__main__':
    try:
        main()
    except Exception as exc:
        print('RF monitor failed: ' + type(exc).__name__, file=sys.stderr)
        sys.exit(1)

unifi.env.example

497 bayt · TXT indir

# Copy to unifi.env, chmod 600, edit locally; never commit real credentials.
UNIFI_URL='https://controller.example.com'
UNIFI_SITE='default'
UNIFI_AP_NAME='AP-lab'
UNIFI_USERNAME=''
UNIFI_PASSWORD=''
# Optional: trusted issuing CA certificate, never a private key; TLS stays verified.
# UNIFI_CA_FILE='/path/to/issuing-ca.pem'
# RF_STATE_DIR='/path/to/private/report-state'

# Optional: verified absolute interpreter path for restricted cron environments.
# PYTHON_BIN='/absolute/path/to/python3'