diff --git a/README.md b/README.md index ac5a677..413ecbd 100644 --- a/README.md +++ b/README.md @@ -1,48 +1,128 @@ # Arch-traefik-hub πŸš€ -A centralized local services manager using **Traefik v3** as a reverse proxy with automated **SSL (Let's Encrypt)** via Dynu DNS-01 challenges. +A centralized local services platform using **Traefik v3** as a reverse proxy with automated **SSL (Let's Encrypt)** and resilient **Dynu DDNS IP synchronization**. + +--- ## πŸ—οΈ Architecture -- **Gateway**: Traefik (running in `core/`) -- **Network**: `proxy-net` (shared Docker bridge) -- **Domain**: `*.arch-services.mywire.org` -- **Automation**: `up.sh` script for zero-config deployment + +The system is composed of two independent but complementary layers: + +### 1. Gateway Layer (Traefik) +- Reverse proxy for all services +- Handles HTTPS termination +- Performs ACME DNS-01 challenges via Dynu API +- Runs inside `core/` + +### 2. Infrastructure Layer (Dynu IP Sync) +- Systemd-managed IP monitor (`dynu.service`) +- Periodically detects public IPv4 changes +- Updates Dynu DNS records only when necessary +- Uses: + - DNS (fast path via `dig`) + - HTTP providers (fallback) + - Atomic state (`/var/lib/dynu/last_ip`) + - Structured journald logs + +### 3. Network +- Shared Docker bridge: `proxy-net` +- Domain: `*.arch-services.mywire.org` + +--- ## 🚦 Project Status -| Task | Status | +| Component | Status | | :--- | :--- | | NAT Port Forwarding (80/443) | βœ… Completed | -| Folder Scaffolding | βœ… Completed | -| Shared Network Setup | βœ… Completed | -| Custom Python Dashboard | πŸ—οΈ In Progress | -| Dynu API Integration | ⏳ Pending (Key found) | -| Let's Encrypt Validation | ⏳ Pending | +| Traefik Gateway | βœ… Operational | +| Dynu DDNS IP Sync | βœ… Completed | +| ACME DNS-01 (Let's Encrypt) | ⏳ Pending validation | +| Python Dashboard | πŸ—οΈ In Progress | + +--- ## πŸš€ Getting Started -### 1. Configuration -Create a `.env` file in the root directory (use `.env-example` as a template): +### 1. Environment Configuration + +Create `.env` in the project root: + ```bash DYNU_API_KEY=your_key_here ACME_EMAIL=your_email@example.com DOMAIN=arch-services.mywire.org ``` -### 2. Launching the Hub -The `up.sh` script handles network creation, directory permissions for SSL, and container startup. +--- + +### 2. Launch the Gateway + ```bash chmod +x up.sh ./up.sh ``` -### 3. Verification -- **Traefik Logs**: `docker logs -f traefik` (Watch for successful SSL challenge) -- **Local Dashboard**: `http://192.168.1.36:3000` (Once dashboard service is up) -- **Service Logs**: `https://logs.arch-services.mywire.org` (Via Dozzle) +This will: +- Create the shared Docker network +- Set correct permissions for ACME storage +- Start Traefik and core services + +--- + +### 3. Configure Dynu IP Sync (Host-level) + +The IP updater runs **outside Docker** via systemd. + +Run the setup script: + +```bash +sudo ./setup-dynu.sh \ + --host yourdomain.mywire.org \ + --user your_dynu_username \ + --password your_dynu_password +``` + +This installs: +- `/usr/local/bin/ip-monitor.sh` +- `dynu.service` +- `dynu.timer` + +Verify: + +```bash +systemctl status dynu.timer +journalctl -u dynu.service -f +cat /var/lib/dynu/last_ip +``` + +--- + +## πŸ” Verification + +- **Traefik Logs** + ```bash + docker logs -f traefik + ``` + +- **Dynu Sync Logs** + ```bash + journalctl -u dynu.service -f + ``` + +- **Check Current IP State** + ```bash + cat /var/lib/dynu/last_ip + ``` + +--- ## πŸ› οΈ Adding New Services -To add a service, create a folder in `services/` and ensure the `docker-compose.yml` uses the `proxy-net` and includes the Traefik labels: + +Each service must: + +- Join `proxy-net` +- Define Traefik routing labels ```yaml labels: @@ -54,8 +134,28 @@ labels: --- -## πŸ“¦ Current Service Map -- **Excalidraw**: `excalidraw.${DOMAIN}` -- **Gitea**: `gitea.${DOMAIN}` -- **Ollama**: `ollama.${DOMAIN}` (Load balanced x3) -- **Dozzle**: `logs.${DOMAIN}` +## πŸ“¦ Current Services + +- Excalidraw β†’ `excalidraw.${DOMAIN}` +- Gitea β†’ `gitea.${DOMAIN}` +- Ollama (x3) β†’ `ollama.${DOMAIN}` +- Dozzle β†’ `logs.${DOMAIN}` + +--- + +## πŸ“Œ Design Principles + +- **Idempotent execution** (safe under repetition) +- **Fail-fast behavior** (no partial state) +- **Atomic state updates** +- **Separation of concerns**: + - Traefik β†’ TLS + routing + - Dynu updater β†’ IP correctness +- **Observability-first logging** (journald structured events) + +--- + +## πŸ“š Related Docs + +- `docs/dynu-ip-update.md` β†’ usage and operational notes +- `docs/dynu-ip-update-protocol.md` β†’ design and architecture decisions \ No newline at end of file diff --git a/docs/dynu-ip-update-protocol.md b/docs/dynu-ip-update-protocol.md index 76994e7..3898b2f 100644 --- a/docs/dynu-ip-update-protocol.md +++ b/docs/dynu-ip-update-protocol.md @@ -1,66 +1,213 @@ -# Dynu IP Address Update Protocol +# Dynu IP Monitor & Updater (Design / Architecture) ## Problem Definition -* **Success Criteria**: The system must detect changes in public IPv4 addresses and update Dynu records with high resilience, using strict validation and atomic state management to avoid `abuse` flags. -* **Non-Goals**: This implementation does not manage complex DNS records (MX/TXT) or IPv6 addressing. -## ADR: Resilience & Security Hardening -**Decision**: Implement a hardened, multi-provider discovery engine via systemd. +Maintain accurate DNS A records in Dynu despite: -* **Rationale**: - * **Redundancy**: Iterating through multiple HTTP providers prevents failure if a single service (like `ifconfig.me`) goes offline. - * **Security**: Systemd sandboxing (`ProtectSystem=strict`, `NoNewPrivileges`) ensures the script operates in a "least privilege" environment. - * **Observability**: Capturing `stderr` from discovery commands into the journal allows for deep-dive debugging of network timeouts. -* **Consequences**: Slightly higher complexity in shell logic, but provides a "set and forget" infrastructure layer. +* dynamic public IPs +* unreliable external IP providers +* transient network failures + +### Success Criteria + +* Correct IP is eventually reflected in Dynu +* No invalid or private IPs are ever persisted +* No redundant updates (avoid Dynu abuse flags) +* Safe under concurrent or repeated execution + +### Non-Goals + +* IPv6 support +* complex DNS record management +* real-time updates (polling only) --- -## Implementation Details +## Core Design Decisions -### 1. Directory & State Management -Runtime data is handled by systemd's `StateDirectory` directive, which manages `/var/lib/dynu` automatically. -* **State File**: `/var/lib/dynu/last_ip` (Atomic updates via `mktemp` + `mv`). -* **Locking**: Concurrency is managed via `flock` on `/var/lib/dynu/lock`. +### 1. Probe Model (Not a Daemon) -### 2. Core Logic: `ip-monitor.sh` -The script follows a "Fail-Fast" philosophy: -1. **Invariants**: Validates that it is running within a systemd environment. -2. **Discovery Loop**: - * Primary: DNS query via `dig` (ultra-fast). - * Fallback: Multi-URL HTTP loop (`api.ipify.org`, `ifconfig.me`, `wtfismyip.com`). -3. **Validation**: Strict regex and numeric bound checks for IPv4 format. -4. **Update**: Hits the Dynu REST API only upon confirmed IP delta. +The system runs periodically instead of continuously. -### 3. Hardened Systemd Orchestration +**Why:** -#### Service: `dynu.service` -```ini -[Service] -Type=oneshot -User=root -StateDirectory=dynu -EnvironmentFile=/etc/conf.d/dynu-environment -ExecStart=/usr/local/bin/ip-monitor.sh -# Hardening -NoNewPrivileges=true -PrivateTmp=true -ProtectSystem=strict -ProtectHome=true -ReadWritePaths=/var/lib/dynu -``` - -#### Timer: `dynu.timer` -```ini -[Timer] -OnBootSec=30s -OnUnitActiveSec=15min -Persistent=true -``` +* simpler lifecycle (systemd handles scheduling) +* naturally idempotent +* avoids long-lived state bugs --- -## Verification and Monitoring -* **Live Logs**: `journalctl -u dynu.service -f` -* **Check State**: `cat /var/lib/dynu/last_ip` -* **Simulate Update**: `echo "1.1.1.1" > /var/lib/dynu/last_ip && systemctl start dynu.service` -``` \ No newline at end of file +### 2. Dual-Source Discovery + +* Primary: DNS (`dig`) +* Fallback: HTTP providers + +**Why:** + +* DNS is faster and lightweight +* HTTP provides redundancy when DNS fails + +--- + +### 3. Explicit Degradation Model + +Failures are classified: + +* `degraded` β†’ fallback used, system still functional +* `error` β†’ no valid IP, abort + +**Why:** + +* improves observability +* avoids silent failure modes + +--- + +### 4. Strict Validation Pipeline + +Every candidate IP must pass: + +1. format validation (regex + bounds) +2. public IP validation (no RFC1918 / CGNAT) + +Validation is applied: + +* per-provider +* after discovery (final gate) + +**Why:** + +* prevents poisoning state with invalid data +* enforces invariant: *state must always be valid* + +--- + +### 5. State as a Consistency Contract + +`last_ip` represents: + +> β€œThe last IP successfully synchronized with Dynu” + +It is updated **only after**: + +* HTTP 200 +* valid Dynu semantic response (`good` / `nochg`) + +**Why:** + +* avoids divergence between local state and remote DNS + +--- + +### 6. Atomic Writes + +State updates use: + +``` +write β†’ temp file β†’ mv +``` + +**Why:** + +* guarantees consistency even on crash/interruption +* `mv` is atomic on same filesystem + +--- + +### 7. Concurrency Strategy + +Non-blocking lock via `flock`. + +If locked: + +``` +skip execution +``` + +**Why:** + +* prevents overlapping runs +* avoids queue buildup from timers +* ensures last execution β€œwins” + +--- + +### 8. Deferred Credential Processing + +Password hashing happens only when update is needed. + +**Why:** + +* avoids unnecessary computation +* keeps fast-path (no-change) minimal + +--- + +### 9. Transport vs Semantic Validation + +Two layers: + +1. Transport β†’ HTTP status must be `200` +2. Semantic β†’ response must start with `good` or `nochg` + +**Why:** + +* separates network failures from API logic failures +* improves debugging clarity + +--- + +### 10. Structured Logging + +All logs follow: + +``` +event=... reason=... cause=... +``` + +**Why:** + +* machine-filterable via journald +* consistent debugging surface + +--- + +## Trade-offs + +### Bash vs Higher-Level Language + +**Chosen:** Bash + +**Pros:** + +* zero runtime dependency +* native systemd integration +* simple deployment + +**Cons:** + +* limited abstractions +* harder error composition +* more manual validation + +Given the scope (I/O-bound, small state machine), Bash remains appropriate. + +--- + +## Failure Modes Considered + +* DNS unavailable β†’ fallback to HTTP +* HTTP provider failure β†’ rotate providers +* invalid IP returned β†’ rejected +* API failure β†’ no state mutation +* concurrent execution β†’ skipped +* partial execution β†’ no persistent side effects + +--- + +## Key Invariants + +* No invalid IP is ever persisted +* State reflects only successful external sync +* Script is safe to run repeatedly +* System is eventually consistent, not instantly consistent diff --git a/docs/roadmap.md b/docs/roadmap.md index 234cf20..860b13e 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -1,53 +1,113 @@ # πŸ—ΊοΈ Project Roadmap: Arch-traefik-hub -This document outlines the development phases for the **Arch-traefik-hub** ecosystem, focusing on security, observability, and service scalability. +This roadmap reflects the current system maturity and next priorities. -## Phase 1: Core Gateway & Security πŸ”’ -*The objective is to establish a hardened "Front Door" with automated certificate management.* +--- -- [ ] **Credential Provisioning:** Configure the `.env` layer using Dynu API credentials. -- [ ] **Infrastructure Initialization:** Execute the `up.sh` deployment orchestration script. -- [ ] **ACME Validation:** Monitor Traefik logs to verify successful **DNS-01 challenges** and SSL certificate issuance. -- [ ] **Traffic Verification:** Confirm secure $HTTPS$ routing to the gateway via the `*.arch-services.mywire.org` TLD. +## Phase 1: Core Gateway & DNS Stability πŸ”’ (Mostly Complete) -## Phase 2: Observability & Management Dashboard πŸ“Š -*Transitioning from CLI-based management to a centralized visual interface.* +Objective: stable external access with correct DNS resolution. -- [ ] **Full-Stack Dashboard:** Develop a FastAPI-backed JS frontend to consume real-time container metadata. -- [ ] **Dockerization:** Containerize the Python dashboard and deploy it as a core service within the `proxy-net`. -- [ ] **Log Stream Integration:** Implement deep-linking between the custom dashboard and **Dozzle** for instant per-service log access. +- [x] NAT Port Forwarding (80/443) +- [x] Dynu DDNS IP synchronization (systemd-based) +- [x] Traefik deployment with reverse proxy +- [ ] ACME DNS-01 validation (Let's Encrypt) +- [ ] End-to-end HTTPS verification across all services + +Notes: +- IP drift is now handled independently via Dynu updater +- Remaining risk is ACME challenge correctness + +--- + +## Phase 2: Observability & Control Plane πŸ“Š + +Objective: reduce reliance on CLI and improve visibility. + +- [ ] FastAPI backend for service metadata +- [ ] Minimal JS frontend dashboard +- [ ] Integration with Docker socket (read-only) +- [ ] Deep-linking to Dozzle logs per service +- [ ] Health/status indicators for: + - containers + - domains + - SSL certificates + +--- ## Phase 3: Service Ecosystem Expansion πŸš€ -*Deploying high-utility services while maintaining network isolation and resource efficiency.* -- [ ] **Visual Collaboration:** Deploy and configure **Excalidraw** and **Mermaid** for local diagramming. -- [ ] **Local AI Hub:** Optimize the **Ollama** deployment with load-balanced replicas for high-availability inference. -- [ ] **Performance Profiling:** Establish baseline CPU/RAM metrics to ensure host stability across all active services. +Objective: increase utility without compromising isolation. + +- [ ] Excalidraw + diagram tooling +- [ ] Expand Ollama cluster (load + memory tuning) +- [ ] Add developer-focused tools (CI, registry, etc.) +- [ ] Define service templates for quick onboarding + +Constraints: +- Must use `proxy-net` +- Must be Traefik-exposed +- Must remain resource-aware + +--- ## Phase 4: Network Optimization & Resilience 🌐 -*Optimizing the home network for low-latency and local-first access.* -- [ ] **Local DNS Resolution:** (Optional) Integrate a DNS sinkhole (e.g., Pi-hole) to resolve hostnames locally, reducing reliance on external DNS lookups. -- [ ] **Cross-Device Validation:** Audit **NAT Hairpinning** performance to ensure seamless access from mobile and IoT devices on the local Wi-Fi. +Objective: reduce external dependencies and improve latency. + +- [ ] Local DNS resolver (Pi-hole or equivalent) +- [ ] Internal hostname resolution (LAN-first) +- [ ] NAT hairpinning validation across devices +- [ ] Optional fallback DNS providers for redundancy --- -## πŸ’‘ Implementation Best Practices +## Phase 5: Hardening & Reliability βš™οΈ -### Network Resolution in Python -When querying the Docker socket via the Python SDK, ensure the logic is resilient to Docker Compose project naming (which often prepends directory names to network strings): +Objective: move from β€œworking” to β€œrobust”. -```python -# Use partial matching to find the proxy-net membership -if any("proxy-net" in net for net in networks.keys()): - # logic for proxy-registered containers -``` - -### Security Standards -- **ACME Storage:** The `acme.json` file must maintain `600` permissions to be accepted by the Traefik provider. -- **Socket Access:** The Docker socket is mounted as `ro` (Read-Only) wherever possible to adhere to the principle of least privilege. +- [ ] Add alerting (failed Dynu updates, SSL issues) +- [ ] Timer tuning based on real IP volatility +- [ ] Rate-limit awareness for Dynu API +- [ ] Backup strategy for: + - Traefik config + - ACME storage +- [ ] Evaluate IPv6 support (explicitly out-of-scope so far) --- -### How to use this roadmap -This roadmap is updated as features are merged into the `main` branch. Contributions to the service templates or dashboard logic are welcome via Pull Requests. +## πŸ’‘ Engineering Notes + +### Separation of Concerns + +- Dynu updater: + - ensures correct **public IP** + - runs via systemd (host-level) + +- Traefik: + - ensures **TLS + routing** + - runs in Docker + +This separation prevents coupling failures (e.g., container restart affecting DNS correctness). + +--- + +### Failure Model + +- **Degraded** + - DNS failure β†’ HTTP fallback + - Provider-specific issues + +- **Error** + - No valid IP found + - Dynu API failure + +Only **successful external sync** mutates local state. + +--- + +### How to Use This Roadmap + +- Updated after stable merges into `main` +- Items should represent **deployable increments**, not ideas +- Avoid speculative features unless tied to concrete problems \ No newline at end of file diff --git a/scripts/dynu/dynu-ip-update.md b/scripts/dynu/dynu-ip-update.md index 6050b74..1545355 100644 --- a/scripts/dynu/dynu-ip-update.md +++ b/scripts/dynu/dynu-ip-update.md @@ -1,15 +1,125 @@ -# Set up instructions and notes +# Dynu IP Monitor & Updater +This component keeps your Dynu DNS record in sync with your current public IPv4 address. -```plaintext +It runs as a **systemd timer-driven probe**, not a daemon. + +## Execution Flow + +``` timer β†’ service β†’ script - β”œβ”€ lock (no concurrency) - β”œβ”€ DNS attempt (logged) - β”œβ”€ HTTP fallback (logged) - β”œβ”€ validate - β”œβ”€ compare with state - β”œβ”€ update Dynu (bounded time) + β”œβ”€ lock (skip if overlapping run) + β”œβ”€ DNS discovery (fast path) + β”œβ”€ HTTP fallback (multi-provider) + β”œβ”€ strict validation + β”œβ”€ compare with last known IP + β”œβ”€ update Dynu (only on change) β”œβ”€ atomic state write - └─ structured logs + └─ structured logs (journald) ``` +--- + +## Installation + +Run the setup script as root: + +```bash +sudo ./setup.sh \ + --host your-domain.mywire.org \ + --user your-dynu-username \ + --password your-dynu-password +``` + +This will: + +* Install the script to `/usr/local/bin/ip-monitor.sh` +* Install systemd units: + + * `/etc/systemd/system/dynu.service` + * `/etc/systemd/system/dynu.timer` +* Store credentials in: + + * `/etc/conf.d/dynu-environment` (mode `600`) +* Enable and start the timer + +--- + +## Runtime Behavior + +* Runs every **5 minutes** (configurable via `dynu.timer`) +* Skips execution if a previous run is still active +* Only updates Dynu **when IP changes** +* Never writes state unless the update succeeds + +--- + +## State Management + +* Directory: `/var/lib/dynu/` (managed by systemd) +* Files: + + * `last_ip` β†’ last successfully synced public IP + * `lock` β†’ used for concurrency control + +State updates are **atomic**: + +* write β†’ temp file +* move β†’ final file + +--- + +## Logs & Monitoring + +View logs: + +```bash +journalctl -u dynu.service -f +``` + +### Log Types + +* `event=discovered` β†’ IP successfully detected +* `event=change` β†’ IP changed +* `event=state_updated` β†’ Dynu successfully updated +* `event=degraded` β†’ fallback or partial failure +* `event=error` β†’ hard failure (no state change) +* `event=skip` β†’ concurrent run avoided + +--- + +## Manual Testing + +Force an update: + +```bash +echo "1.1.1.1" > /var/lib/dynu/last_ip +systemctl start dynu.service +``` + +Check state: + +```bash +cat /var/lib/dynu/last_ip +``` + +--- + +## Configuration + +### Timer + +```ini +OnBootSec=30s +OnUnitActiveSec=5min +Persistent=true +``` + +### Service + +* Runs as `root` +* Uses systemd sandboxing: + + * `ProtectSystem=strict` + * `NoNewPrivileges=true` + * limited write access to `/var/lib/dynu`