From 10b795ce139240e2b1f7b18b25d89fe52a2cc723 Mon Sep 17 00:00:00 2001 From: michael Date: Tue, 17 Jun 2025 19:30:34 +0200 Subject: [PATCH] refactor(architecture): migrate Furt concept from Go to C+Lua for digital sovereignty MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace Go-based architecture with C+Lua hybrid approach - Eliminate Google-controlled dependencies per tech-reference analysis - Add master strategy document for 18-24 month migration roadmap - Define modular architecture with <200 lines per script constraint - Specify Pure Lua → C+Lua → OpenBSD migration path - Document SMTP integration for mail.dragons-at-work.de Files modified: - devdocs/KONZEPT.md (complete rewrite) - devdocs/MASTER_STRATEGY.md (new) Resolves concept phase, enables Week 1 Lua implementation. --- devdocs/furt_konzept.md | 1037 ++++++++++++++++++------------- devdocs/furt_master_strategy.md | 296 +++++++++ 2 files changed, 891 insertions(+), 442 deletions(-) create mode 100644 devdocs/furt_master_strategy.md diff --git a/devdocs/furt_konzept.md b/devdocs/furt_konzept.md index e7c7605..7e41e1e 100644 --- a/devdocs/furt_konzept.md +++ b/devdocs/furt_konzept.md @@ -1,520 +1,673 @@ # Furt: API-Gateway im Einklang mit digitaler Souveränität **Erstellt:** 03. Juni 2025 -**Letzte Aktualisierung:** 03. Juni 2025 -**Version:** 1.0 +**Letzte Aktualisierung:** 17. Juni 2025 +**Version:** 2.0 **Verantwortlich:** DAW-Team **Dateipfad:** devdocs/KONZEPT.md ## Zweck dieses Dokuments -Dieses Dokument definiert die grundlegenden Prinzipien, technischen Entscheidungen und Entwicklungsrichtlinien für das Furt API-Gateway-System. Es dient als zentrale Referenz für alle Entwickler und Mitwirkenden des Projekts. +Dieses Dokument definiert das überarbeitete Konzept für Furt basierend auf der Dragons@Work Tech-Reference und dem Prinzip der maximalen technologischen Souveränität. Das System wird von Go auf C + Lua umgestellt, um Corporate-Capture zu vermeiden. -Es richtet sich an Entwickler, Projektbeteiligte und alle, die am Code-Design und der Implementierung von Furt arbeiten. +## Grund für die Überarbeitung -## Verwandte Dokumente +Die ursprüngliche Go-basierte Architektur widerspricht den Prinzipien digitaler Souveränität: +- **Go ist Google-controlled** (Proxy, Module-Summen, Telemetrie) +- **Corporate-Abhängigkeit** durch Go-Ökosystem +- **Nicht im Einklang** mit der Tech-Reference -Dieses Dokument steht im Zusammenhang mit folgenden anderen Dokumenten: +## 1. Neue Projektvision und Philosophie -- **README.md:** Öffentliche Projektbeschreibung, ../README.md -- **ARCHITECTURE.md:** Detaillierte Architekturübersicht, devdocs/ARCHITECTURE.md -- **DECISIONS.md:** Wichtige Architekturentscheidungen, devdocs/DECISIONS.md +Furt (germanisch für "Durchgang durch Wasser") ist ein **selbst-gehostetes API-Gateway-System** basierend auf **C + Lua**, das vollständig im Einklang mit den Prinzipien digitaler Souveränität steht: -## 1. Projektvision und Philosophie +### Kernprinzipien +- **C als Basis** - Bewährt seit 50+ Jahren, strukturell uncapturable +- **Lua für Logik** - PUC-Rio University, echte akademische Unabhängigkeit +- **Minimale Dependencies** - Nur GCC + musl, keine Corporate-Libraries +- **Maximale Transparenz** - Jede Zeile Code verstehbar und kontrollierbar +- **Ultra-Low-Tech** - Ressourcenschonend, lange Lebensdauer -Furt (germanisch für "Durchgang durch Wasser") ist ein selbst-gehostetes API-Gateway-System, das vollständig im Einklang mit den Prinzipien digitaler Souveränität, technologischer Angemessenheit und ressourcenschonender Entwicklung steht. Das System soll: +### Abgrenzung zu Corporate-Lösungen +- **Keine Cloud-Dependencies** +- **Keine Corporate-Runtimes** (Go, Node.js, etc.) +- **Keine Black-Box-Components** +- **Keine Vendor-Lock-ins** -- **Einfachheit über Komplexität stellen** - leicht verständlich, wartbar und erweiterbar sein -- **Ressourceneffizient arbeiten** - minimale Server-Anforderungen und optimierte Performance -- **Vollständige Kontrolle** ermöglichen - transparenter Code ohne Black-Boxes -- **Langfristig tragfähig** sein - basierend auf bewährten Technologien -- **Service-Modularität** unterstützen - eigenständige Services unter einheitlicher API -- **Mehrsprachigkeit** von Anfang an unterstützen (DE, EN, FR) - -Im Gegensatz zu existierenden Enterprise-Gateway-Lösungen fokussiert sich Furt auf: -- Native Installation als Hauptdeployment-Methode (keine Container-Abhängigkeit) -- Minimale externe Abhängigkeiten -- Transparente Konfiguration und Datenverarbeitung -- Volle Kompatibilität mit Low-Tech-Webseiten und statischen Site-Generatoren (besonders Hugo) -- **Ein Gateway für alle Services** - von Kontaktformularen bis zu komplexeren Anwendungen - -## 2. Technische Architektur +## 2. Technische Architektur (C + Lua) ### 2.1 Technology-Stack -- **Backend:** Go (für Performance, einfache Deployment durch einzelne Binärdatei) -- **Gateway-Pattern:** Reverse Proxy mit Service Registry -- **Konfiguration:** YAML-basiert (human-readable, versionierbar) -- **Proxy-Integration:** Apache als SSL-terminierender Reverse Proxy -- **Services:** Eigenständige Go-Binaries mit eigenen Ports -- **Authentifizierung:** API-Keys mit granularen Berechtigungen -- **Logging:** Strukturierte JSON-Logs mit konfigurierbaren Leveln +**Core:** +- **C (GCC + musl)** - Gateway-Kern, HTTP-Server, System-Interface +- **Lua 5.4** - Business-Logic, Konfiguration, Service-Scripts +- **LMDB** - Datenbank (Howard Chu/Symas, keine VC-Dependencies) +- **OpenBSD httpd** - Als Reverse-Proxy (langfristig, Apache-Migration) + +**Konfiguration:** +- **Lua-Scripts** statt YAML (native, programmierbar, validierbar) +- **LMDB-Storage** für Konfiguration und State +- **Environment-Variables** nur für Secrets + +**Services:** +- **C-Module** mit Lua-Scripten für Business-Logic +- **Minimale HTTP-Implementation** in C +- **Lua-basierte** Request-Handler ### 2.2 Projektstruktur ``` furt/ -├── cmd/ -│ ├── furt-gateway/ # Gateway-Binary -│ │ └── main.go -│ └── services/ # Service-Binaries -│ ├── formular2mail/ # Kontaktformular → E-Mail -│ ├── sagjan/ # Kommentarsystem-Integration -│ └── shop/ # Zukünftig: E-Commerce -├── internal/ -│ ├── gateway/ # Gateway-Kernlogik -│ │ ├── server.go # HTTP-Server -│ │ ├── router.go # Request-Routing -│ │ ├── proxy.go # Service-Proxy -│ │ ├── auth.go # Authentifizierung -│ │ └── middleware.go # Gateway-Middleware -│ ├── services/ # Service-Implementierungen -│ │ ├── formular2mail/ # Formular-Service-Logik -│ │ └── sagjan/ # Kommentar-Service-Logik -│ └── shared/ # Geteilte Komponenten -│ ├── auth/ # Authentifizierungs-Bibliothek -│ ├── config/ # Konfigurationsmanagement -│ └── logging/ # Strukturiertes Logging -├── configs/ # Konfigurationsvorlagen -│ ├── gateway.yaml.example # Gateway-Konfiguration -│ └── services/ # Service-spezifische Configs -│ ├── formular2mail.yaml.example -│ └── sagjan.yaml.example -├── docs/ # Öffentliche Dokumentation -│ ├── installation.md # Installationsanleitung -│ ├── configuration.md # Konfigurationsreferenz -│ ├── services/ # Service-spezifische Dokumentation -│ └── api/ # OpenAPI-Dokumentation -│ ├── gateway.yaml # Gateway-API-Spec -│ └── services/ # Service-API-Specs -├── devdocs/ # Entwicklerdokumentation +├── src/ +│ ├── core/ # C Core-Implementation +│ │ ├── http_server.c # Minimal HTTP-Server +│ │ ├── router.c # Request-Routing +│ │ ├── proxy.c # Service-Proxy +│ │ ├── auth.c # Authentifizierung +│ │ └── main.c # Entry Point +│ ├── lua/ # Lua-Scripts +│ │ ├── gateway/ # Gateway-Logic +│ │ │ ├── config.lua # Konfigurationsmanagement +│ │ │ ├── middleware.lua # Middleware-Chain +│ │ │ └── services.lua # Service-Registry +│ │ └── services/ # Service-Logic +│ │ ├── formular2mail.lua # Mail-Service +│ │ └── sagjan.lua # Comment-Service +│ └── include/ # C Header-Files +│ ├── furt.h # Main Header +│ ├── http.h # HTTP Definitions +│ └── lua_bridge.h # C ↔ Lua Interface +├── config/ # Konfiguration +│ ├── gateway.lua # Gateway-Konfiguration +│ └── services/ # Service-Configs +│ ├── formular2mail.lua +│ └── sagjan.lua +├── build/ # Build-System +│ ├── Makefile # Haupt-Makefile +│ ├── config.mk # Build-Konfiguration +│ └── deps/ # Dependencies (Lua, LMDB) +├── docs/ # Dokumentation +│ ├── installation.md # Installation +│ ├── configuration.md # Konfiguration +│ └── development.md # Entwicklung ├── scripts/ # Build & Deployment -│ ├── build-all.sh # Alle Komponenten bauen -│ ├── deploy-gateway.sh # Gateway deployment -│ ├── deploy-service.sh # Service deployment -│ └── service-generator.sh # Neuen Service scaffolden -├── examples/ # Beispiel-Integrationen -│ ├── hugo/ # Hugo-Shortcodes -│ ├── nginx/ # Nginx-Proxy-Config -│ └── apache/ # Apache-Proxy-Config -└── tests/ # Test-Suites - ├── integration/ # Service-Integration-Tests - └── e2e/ # End-to-End-Tests +│ ├── build.sh # Build-Script +│ ├── install.sh # Installation +│ └── service-generator.sh # Service-Generator +├── tests/ # Tests +│ ├── unit/ # Unit-Tests (C) +│ ├── integration/ # Integration-Tests +│ └── lua/ # Lua-Tests +└── examples/ # Beispiele + ├── hugo/ # Hugo-Integration + └── configs/ # Beispiel-Konfigurationen ``` -### 2.3 Gateway-Architektur +### 2.3 C + Lua Integration-Pattern -Das Furt-Gateway implementiert ein **Service-Registry-Pattern** mit dateibasierter Konfiguration: +**C-Kern mit Lua-Logic:** +```c +// src/core/main.c +#include "furt.h" +#include "lua_bridge.h" -```go -// Beispiel Gateway-Konfiguration -type GatewayConfig struct { - Gateway GatewaySettings `yaml:"gateway"` - Security SecurityConfig `yaml:"security"` - Services map[string]ServiceConfig `yaml:"services"` - Logging LoggingConfig `yaml:"logging"` -} - -type ServiceConfig struct { - Enabled bool `yaml:"enabled"` - PathPrefix string `yaml:"path_prefix"` // /v1/mail, /v1/comments - Upstream string `yaml:"upstream"` // http://127.0.0.1:8081 - HealthCheck string `yaml:"health_check"` // /health - Timeout time.Duration `yaml:"timeout"` - HasAdminUI bool `yaml:"has_admin_ui"` - AdminPath string `yaml:"admin_path"` -} -``` - -**Request-Flow:** -1. Client → Apache (SSL-Terminierung) → Gateway -2. Gateway → Authentifizierung (API-Key + IP-Check) -3. Gateway → Service-Registry (Route Resolution) -4. Gateway → Service-Proxy (Request Forwarding) -5. Service → Response → Gateway → Client - -## 3. Entwicklungsphasen gemäß natürlichem Wachstum - -Die Entwicklung folgt einem natürlichen, organischen Prozess, der in vier Hauptphasen gegliedert ist: - -### 3.1 Wurzelphase (Grundlagen) - -- **Ziel:** Funktionierendes Gateway mit minimalen Features -- **Schlüsselfeatures:** - - HTTP-Gateway mit grundlegendem Routing - - API-Key-Authentifizierung mit IP-Beschränkungen - - Formular2Mail-Service (E-Mail-Weiterleitung) - - Basis-Hugo-Integration (Shortcodes) - - Native Installationspakete für alle Komponenten - -### 3.2 Wachstumsphase (Erweiterung) - -- **Ziel:** Stabile, nutzbare Version mit wichtigen Services -- **Schlüsselfeatures:** - - Sagjan-Integration (Kommentarsystem) - - Erweiterte Middleware (Rate-Limiting, Logging) - - Service-Generator für neue Services - - Admin-Dashboard für Gateway-Management - - Umfassende OpenAPI-Dokumentation - -### 3.3 Blütephase (Vernetzung) - -- **Ziel:** Verbesserung der Integration und Erweiterbarkeit -- **Schlüsselfeatures:** - - Shop-Service (E-Commerce-Integration) - - Webhook-Support für Service-Events - - Erweiterte Monitoring-Funktionen - - Multi-Tenant-Fähigkeiten - - Service-Discovery-Verbesserungen - -### 3.4 Fruchtphase (Reifung) - -- **Ziel:** Langfristige Wartbarkeit und Community-Entwicklung -- **Schlüsselfeatures:** - - Community-Service-Ecosystem - - Performance-Optimierungen - - High-Availability-Features - - Föderation mit anderen Furt-Instanzen - -## 4. Service-Integration-Konzept - -### 4.1 Service-Entwicklung-Pattern - -Jeder Service folgt einem standardisierten Muster: - -```go -// Service-Interface -type Service interface { - // Für Gateway-Integration - HandleRequest(w http.ResponseWriter, r *http.Request) - HealthCheck() error +int main(int argc, char *argv[]) { + furt_context_t *ctx = furt_init(); - // Für Standalone-Mode - HandleWithAuth(w http.ResponseWriter, r *http.Request) // Eigene Auth + // Initialize Lua state + lua_State *L = lua_bridge_init(ctx); - // Service-Lifecycle - Start(ctx context.Context) error - Stop(ctx context.Context) error -} - -// Service-Konfiguration -type ServiceConfig struct { - Port string `yaml:"port"` - Environment string `yaml:"environment"` - Auth ServiceAuth `yaml:"auth"` - Logging LoggingConfig `yaml:"logging"` - Custom map[string]string `yaml:"custom"` // Service-spezifisch + // Load gateway configuration + lua_bridge_load_config(L, "config/gateway.lua"); + + // Start HTTP server + http_server_start(ctx, L); + + return 0; } ``` -### 4.2 Dual-Mode-Operation +**Lua-Service-Logic:** +```lua +-- config/services/formular2mail.lua +local formular2mail = { + name = "formular2mail", + path_prefix = "/v1/mail", + port = 8081, + + -- Request-Handler + handle_request = function(request) + if request.method ~= "POST" then + return { status = 405, body = "Method not allowed" } + end + + local data = json.decode(request.body) + if not validate_mail_data(data) then + return { status = 400, body = "Invalid data" } + end + + local result = send_mail(data) + return { status = 200, body = json.encode(result) } + end, + + -- Health-Check + health_check = function() + return { status = "healthy", timestamp = os.time() } + end +} -Jeder Service kann sowohl **hinter dem Gateway** als auch **standalone** betrieben werden: +return formular2mail +``` -**Gateway-Mode:** -- Service läuft auf localhost:PORT -- Authentifizierung erfolgt im Gateway -- Routing über Gateway-Pfade (/v1/mail, /v1/comments) +## 3. Build-System und Dependencies -**Standalone-Mode:** -- Service läuft mit eigener Authentifizierung -- Direkte API-Endpunkte (/api/v1/mail/send) -- Eigene Dokumentation und Admin-UI +### 3.1 Minimale Dependencies -### 4.3 Service-Generator +**Required:** +- **GCC** (oder clang, aber nicht MSVC) +- **musl libc** (vermeidet glibc-Komplexität) +- **Lua 5.4** (als Source eingebunden, nicht als Package) +- **LMDB** (als Source eingebunden) -Für schnelle Service-Entwicklung existiert ein Generator: +**Optional:** +- **Valgrind** für Memory-Debugging +- **strace** für System-Call-Debugging + +### 3.2 Build-Process + +```makefile +# build/Makefile +CC = gcc +CFLAGS = -std=c99 -Wall -Wextra -O2 -DLUA_USE_POSIX +LDFLAGS = -lm -ldl + +# Dependencies +LUA_DIR = deps/lua-5.4.6 +LMDB_DIR = deps/lmdb + +SOURCES = src/core/*.c $(LUA_DIR)/src/*.c $(LMDB_DIR)/*.c +TARGET = bin/furt-gateway + +all: $(TARGET) + +$(TARGET): $(SOURCES) + $(CC) $(CFLAGS) -I$(LUA_DIR)/src -I$(LMDB_DIR) \ + $(SOURCES) -o $(TARGET) $(LDFLAGS) + +clean: + rm -f $(TARGET) + +install: $(TARGET) + cp $(TARGET) /usr/local/bin/ + cp -r config/ /etc/furt/ + cp -r src/lua/ /usr/local/share/furt/ + +.PHONY: all clean install +``` + +### 3.3 Dependency-Management + +**Statically Linked:** +- Lua-Source direkt eingebunden +- LMDB-Source direkt eingebunden +- Keine Package-Manager-Dependencies + +**Why Static Linking:** +- Vermeidet Library-Version-Konflikte +- Reduziert Runtime-Dependencies +- Maximale Kontrolle über Code-Path + +## 4. Service-Entwicklung-Pattern + +### 4.1 Service als C-Module + Lua-Script + +**Service-Interface in C:** +```c +// src/core/service.h +typedef struct { + char *name; + char *path_prefix; + int port; + lua_State *lua_state; +} furt_service_t; + +// Service-Lifecycle +int service_init(furt_service_t *service, const char *config_path); +int service_handle_request(furt_service_t *service, http_request_t *req, http_response_t *res); +int service_health_check(furt_service_t *service); +void service_cleanup(furt_service_t *service); +``` + +**Service-Logic in Lua:** +```lua +-- src/lua/services/base.lua +local base_service = { + -- Standard Request-Verarbeitung + process_request = function(self, request) + -- Input-Validation + if not self:validate_input(request) then + return self:error_response(400, "Invalid input") + end + + -- Business-Logic + local result = self:handle_business_logic(request) + + -- Response-Formatting + return self:format_response(result) + end, + + -- Standard Error-Handling + error_response = function(self, status, message) + return { + status = status, + headers = { ["Content-Type"] = "application/json" }, + body = json.encode({ error = message }) + } + end +} + +return base_service +``` + +### 4.2 Service-Generator (Shell + Lua) ```bash -./scripts/service-generator.sh newsletter -# Erstellt: -# - cmd/services/newsletter/main.go -# - internal/services/newsletter/service.go -# - configs/services/newsletter.yaml -# - docs/services/newsletter.yaml -# - Deployment-Scripts -``` +#!/bin/bash +# scripts/service-generator.sh -## 5. Implementierungsrichtlinien +SERVICE_NAME=$1 +if [ -z "$SERVICE_NAME" ]; then + echo "Usage: $0 " + exit 1 +fi -### 5.1 Go-spezifische Standards +# Create service Lua file +cat > "src/lua/services/${SERVICE_NAME}.lua" << EOF +local base = require("services.base") +local ${SERVICE_NAME} = {} -- **Formatierung:** `gofmt` für alle Go-Dateien verwenden -- **Linting:** `golangci-lint` mit angepasster Konfiguration -- **Tests:** Für jedes Package Testdateien (coverage-Ziel: mind. 80%) -- **Abhängigkeiten:** Minimale externe Abhängigkeiten, nur Go-Standard-Library + etablierte Packages -- **Fehlerbehandlung:** Explizite Fehlerprüfung, strukturierte Fehlerrückgaben -- **Logging:** Strukturiertes JSON-Logging mit verschiedenen Leveln -- **Kommentare:** Alle Funktionen und Typen auf Englisch dokumentieren +setmetatable(${SERVICE_NAME}, { __index = base }) -### 5.2 API-Design-Standards +function ${SERVICE_NAME}:handle_business_logic(request) + -- TODO: Implement ${SERVICE_NAME} logic + return { message = "Hello from ${SERVICE_NAME}" } +end -- **RESTful-Design:** Standard HTTP-Methoden und Status-Codes -- **Versionierung:** `/v1/` Pfad-Prefix für alle APIs -- **JSON-Format:** Einheitliche Request/Response-Strukturen -- **Fehlerbehandlung:** Konsistente Fehler-Response-Formate -- **OpenAPI:** Jeder Endpunkt wird dokumentiert +function ${SERVICE_NAME}:validate_input(request) + -- TODO: Implement validation + return true +end -### 5.3 Konfigurationsmanagement +return ${SERVICE_NAME} +EOF -- **YAML-Format:** Human-readable, versionierbar -- **Umgebungsvariablen:** Für sensitive Daten (Tokens, Passwörter) -- **Hierarchische Konfiguration:** Default → Environment → Local -- **Validierung:** Konfiguration wird beim Start validiert - -## 6. Qualitätssicherung - -### 6.1 Teststrategie - -- **Unit-Tests:** Für alle Kernfunktionen und Services -- **Integration-Tests:** Für Gateway ↔ Service-Kommunikation -- **API-Tests:** Für alle Endpunkte mit verschiedenen Authentifizierungsszenarien -- **End-to-End-Tests:** Für vollständige User-Journeys (Hugo → Gateway → Service) -- **Performance-Tests:** Load-Testing für Gateway und Services - -### 6.2 Code-Review-Prozess - -- Peer-Reviews für alle Änderungen -- Prüfung auf Einhaltung der Low-Tech-Prinzipien -- Überprüfung der API-Dokumentation -- Fokus auf Sicherheit und Performance -- Beachtung der Service-Integration-Patterns - -### 6.3 Sicherheits-Standards - -- **API-Key-Management:** Sichere Generation und Rotation -- **Input-Validierung:** Alle User-Inputs validieren -- **Rate-Limiting:** Schutz vor Abuse -- **IP-Allowlisting:** Restriktive Service-Zugriffe -- **Secure Headers:** Standard-Security-Headers -- **Audit-Logging:** Sicherheitsrelevante Events loggen - -## 7. Deployment und Installation - -### 7.1 Native Installation (primär) - -**Gateway-Deployment:** -```bash -# Build -./scripts/build-all.sh - -# Deploy Gateway -./scripts/deploy-gateway.sh - -# Deploy Services -./scripts/deploy-service.sh formular2mail -./scripts/deploy-service.sh sagjan -``` - -**Systemd-Integration:** -- Gateway als `furt-gateway.service` -- Services als `formular2mail-service.service`, etc. -- Automatischer Start und Restart -- Structured Logging zu journald - -### 7.2 Apache-Integration - -**Reverse-Proxy-Konfiguration:** -```apache - - ServerName api.dragons-at-work.de +# Create config file +cat > "config/services/${SERVICE_NAME}.lua" << EOF +return { + name = "${SERVICE_NAME}", + path_prefix = "/v1/${SERVICE_NAME}", + port = 808X, -- TODO: Set port + enabled = true, - # SSL-Terminierung durch Apache - SSLEngine on - SSLCertificateFile /path/to/cert.pem - SSLCertificateKeyFile /path/to/key.pem - - # Gateway-Proxy - ProxyPreserveHost On - ProxyPass / http://127.0.0.1:8080/ - ProxyPassReverse / http://127.0.0.1:8080/ - - # Headers für Gateway - ProxyPassReverse / http://127.0.0.1:8080/ - ProxySetHeader X-Forwarded-For %{REMOTE_ADDR}s - ProxySetHeader X-Forwarded-Proto https - -``` - -### 7.3 Monitoring und Logging - -**Log-Struktur:** -``` -/var/log/furt/ -├── gateway.log # Gateway-Logs -├── formular2mail.log # Service-Logs -├── sagjan.log -└── access.log # Request-Logs -``` - -**Health-Checks:** -- Gateway: `/health` (Service-Status-Aggregation) -- Services: `/health` (Individual Service Health) -- Systemd: `watchdog` für automatischen Restart - -## 8. Hugo-Integration - -### 8.1 Shortcode-Integration - -**Kontaktformular:** -```hugo -{{< furt-contact - form-id="contact-main" - api-key="hugo-frontend-key" - success-message="Vielen Dank für deine Nachricht!" ->}} -``` - -**Kommentarsystem:** -```hugo -{{< furt-comments - page-url="{{ .Permalink }}" - api-key="sagjan-public-key" - moderation="true" ->}} -``` - -### 8.2 JavaScript-Client - -**Minimaler, Framework-freier JavaScript-Client:** -```javascript -// pkg/client/furt-client.js -class FurtClient { - constructor(baseURL, apiKey) { - this.baseURL = baseURL; - this.apiKey = apiKey; + -- Service-specific config + config = { + -- TODO: Add service configuration } +} +EOF + +echo "Created service: ${SERVICE_NAME}" +``` + +## 5. Konfigurationsmanagement (Lua-basiert) + +### 5.1 Lua-Konfiguration statt YAML + +**Gateway-Konfiguration:** +```lua +-- config/gateway.lua +return { + server = { + host = "127.0.0.1", + port = 8080, + max_connections = 1000, + request_timeout = 30 + }, - async submitForm(formData, endpoint) { - // Progressive Enhancement - // Funktioniert mit und ohne JavaScript + security = { + api_keys = { + { + key = os.getenv("HUGO_API_KEY"), + name = "hugo-frontend", + permissions = { "mail:send", "comments:read" }, + allowed_ips = { "127.0.0.1", "10.0.0.0/8" } + } + } + }, + + services = { + require("services.formular2mail"), + require("services.sagjan") + }, + + logging = { + level = "info", + file = "/var/log/furt/gateway.log" } } ``` -## 9. Git-Workflow und Versionierung +**Vorteile Lua-Config:** +- **Native Programmierbarkeit** (Loops, Conditions, Functions) +- **Environment-Variable-Access** direkt in Config +- **Validation** durch Lua-Logic möglich +- **Kommentare und Dokumentation** integriert +- **Modularität** durch require() -### 9.1 Branch-Strategie +### 5.2 Config-Validation -- `main`: Stabile Releases -- `develop`: Hauptentwicklungszweig -- `feature/*`: Feature-Branches -- `service/*`: Service-spezifische Entwicklung -- `release/*`: Release-Kandidaten +```lua +-- src/lua/gateway/config_validator.lua +local validator = {} -### 9.2 Commit-Message-Format +function validator.validate_gateway_config(config) + assert(config.server, "server config required") + assert(config.server.port, "server.port required") + assert(type(config.server.port) == "number", "server.port must be number") + + for _, service in ipairs(config.services) do + validator.validate_service_config(service) + end + + return true +end -``` -typ(bereich): short description of the change +function validator.validate_service_config(service) + assert(service.name, "service.name required") + assert(service.path_prefix, "service.path_prefix required") + assert(service.port, "service.port required") + + return true +end -Detailed explanation of the change, if necessary. -Multiple lines possible. - -Resolves: #123 +return validator ``` -- **Typen:** feat, fix, docs, style, refactor, test, chore -- **Bereiche:** gateway, service-*, config, docs, scripts -- **Sprache:** Englisch für alle Commit-Messages +## 6. Authentifizierung und Sicherheit -### 9.3 Versionierung +### 6.1 C-basierte Auth-Implementation -Semantic Versioning (MAJOR.MINOR.PATCH): -- **MAJOR:** Breaking Changes in Gateway-API oder Service-Interfaces -- **MINOR:** Neue Services oder Features (abwärtskompatibel) -- **PATCH:** Bugfixes und Performance-Verbesserungen +```c +// src/core/auth.c +#include "auth.h" +#include -## 10. Service-Spezifikationen +typedef struct { + char key[64]; + char name[32]; + char **permissions; + char **allowed_ips; +} api_key_t; -### 10.1 Formular2Mail-Service +int auth_validate_api_key(const char *key, const char *client_ip) { + // Load API keys from Lua config + // Validate key and IP + // Return permissions mask +} -**Zweck:** Kontaktformulare zu E-Mail weiterleiten -**Port:** 8081 -**API:** `/send` (POST) -**Integration:** SMTP mit bestehendem Postfix -**Hugo-Integration:** Shortcode für Kontaktformulare - -### 10.2 Sagjan-Service (geplant) - -**Zweck:** Kommentarsystem-Integration -**Port:** 8082 -**API:** `/comments/*` (GET, POST, PUT, DELETE) -**Features:** Moderation, Threading, Spam-Schutz -**Hugo-Integration:** Shortcode für Kommentare - -### 10.3 Zukünftige Services - -- **Shop-Service:** E-Commerce-Funktionen -- **Newsletter-Service:** Listmonk-Integration -- **Calendar-Service:** Terminbuchungen -- **Auth-Service:** User-Management - -## 11. Lizenzierung - -### 11.1 Apache License 2.0 - -Das Projekt steht unter der Apache License 2.0, die: -- Kommerzielle Nutzung erlaubt -- Patentrechte explizit gewährt -- Modifikationen ermöglicht -- Verteilung gestattet - -### 11.2 Copyright-Header - -Jede Quellcode-Datei muss folgenden Header enthalten: - -```go -// Copyright 2025 Furt Contributors -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. +int auth_check_permission(int permissions_mask, const char *permission) { + // Check if permission is allowed +} ``` +### 6.2 IP-Allowlisting in C + +```c +// src/core/ip_filter.c +#include + +int ip_is_allowed(const char *client_ip, char **allowed_ips) { + for (int i = 0; allowed_ips[i] != NULL; i++) { + if (ip_matches_cidr(client_ip, allowed_ips[i])) { + return 1; + } + } + return 0; +} + +int ip_matches_cidr(const char *ip, const char *cidr) { + // CIDR matching implementation +} +``` + +## 7. Performance und Ressourcen + +### 7.1 Memory-Management + +**C-Memory-Management:** +- **Stack-Allocation** wo möglich +- **Explicit malloc/free** für dynamische Allocations +- **Memory-Pools** für häufige Allocations +- **Valgrind-Testing** mandatory + +**Lua-Integration:** +- **Lua-GC-Tuning** für Server-Workloads +- **C ↔ Lua** Memory-Boundary klar definiert +- **Lua-State-Isolation** zwischen Services + +### 7.2 Performance-Charakteristika + +**Erwartete Performance:** +- **Memory:** < 10 MB für Gateway + 3 Services +- **CPU:** < 1% bei 100 req/s +- **Startup:** < 100ms Cold-Start +- **Latency:** < 1ms Gateway-Overhead + +**vs. Go-Implementation:** +- **10x weniger Memory** (keine GC, kein Runtime) +- **5x weniger CPU** (native Code, keine Abstractions) +- **100x schneller Startup** (kein Runtime-Init) + +## 8. Testing-Strategy + +### 8.1 C-Code-Testing + +```c +// tests/unit/test_auth.c +#include "auth.h" +#include "test_framework.h" + +void test_api_key_validation() { + // Setup + auth_init_test_keys(); + + // Test valid key + assert_true(auth_validate_api_key("valid-key", "127.0.0.1")); + + // Test invalid key + assert_false(auth_validate_api_key("invalid-key", "127.0.0.1")); + + // Test IP restriction + assert_false(auth_validate_api_key("valid-key", "192.168.1.1")); +} +``` + +### 8.2 Lua-Logic-Testing + +```lua +-- tests/lua/test_services.lua +local service = require("services.formular2mail") + +function test_mail_service_validation() + local request = { + method = "POST", + body = '{"name":"Test","email":"test@example.com","message":"Test"}' + } + + local response = service:process_request(request) + assert(response.status == 200) +end +``` + +### 8.3 Integration-Testing + +```bash +#!/bin/bash +# tests/integration/test_gateway.sh + +# Start test gateway +./bin/furt-gateway & +GATEWAY_PID=$! + +# Test API endpoint +curl -X POST http://localhost:8080/v1/mail/send \ + -H "X-API-Key: test-key" \ + -d '{"name":"Test","email":"test@example.com","message":"Test"}' + +# Cleanup +kill $GATEWAY_PID +``` + +## 9. Deployment und Installation + +### 9.1 Native Installation (Single Binary) + +```bash +# Build from source +git clone https://gitea.dragons-at-work.de/DAW/furt.git +cd furt +make clean all + +# Install +sudo make install + +# Configure +sudo cp examples/configs/* /etc/furt/ + +# Start +sudo systemctl enable furt-gateway +sudo systemctl start furt-gateway +``` + +### 9.2 Systemd-Integration + +```ini +# /etc/systemd/system/furt-gateway.service +[Unit] +Description=Furt API Gateway +After=network.target + +[Service] +Type=simple +User=furt +Group=furt +ExecStart=/usr/local/bin/furt-gateway +Restart=always +RestartSec=5 +StandardOutput=journal +StandardError=journal + +[Install] +WantedBy=multi-user.target +``` + +### 9.3 OpenBSD-Integration (langfristig) + +```bash +# /etc/rc.d/furt_gateway +#!/bin/ksh +daemon="/usr/local/bin/furt-gateway" +daemon_user="_furt" + +. /etc/rc.d/rc.subr + +rc_cmd $1 +``` + +## 10. Migration von Go zu C + Lua + +### 10.1 Migration-Strategy + +**Phase 1: C-Grundgerüst** +- HTTP-Server in C implementieren +- Basis-Routing implementieren +- Lua-Integration testen + +**Phase 2: Service-Migration** +- Formular2Mail-Service als Lua-Script +- Auth-System in C + Lua +- Tests migrieren + +**Phase 3: Feature-Parität** +- Alle Go-Features in C + Lua +- Performance-Optimierung +- Dokumentation-Update + +**Phase 4: Deployment** +- Production-Deployment +- Go-Version deprecaten +- Community-Feedback integrieren + +### 10.2 Kompatibilität + +**API-Compatibility:** +- Gleiche HTTP-APIs wie Go-Version +- Gleiche Konfiguration-Semantik (aber Lua statt YAML) +- Gleiche Integration mit Hugo-Shortcodes + +**Migration-Pfad:** +- Side-by-Side-Deployment möglich +- Graduelle Service-Migration +- Zero-Downtime-Umstellung + +## 11. Langfristige Vision + +### 11.1 Souveräne Technologie-Stack + +**Complete Independence:** +- **Compiler:** GCC (GNU, nicht Corporate) +- **Libc:** musl (minimal, secure) +- **Database:** LMDB (academic, proven) +- **Scripting:** Lua (university-backed) +- **HTTP-Server:** Eigene Implementation (< 1000 Zeilen C) + +### 11.2 Community und Open Source + +**Authentic Open Source:** +- Apache 2.0 License +- Keine Corporate-Contributors +- Community-driven Development +- Educational Documentation + +**Biocodie-Integration:** +- Furt als Referenz-Implementation für "Organische Software" +- Minimale Komplexität, maximale Transparenz +- Natürliche Wachstums-Pattern + ## 12. Nächste Schritte -### 12.1 Unmittelbare Implementierung (Wurzelphase) +### 12.1 Unmittelbare Implementierung -1. **Gateway-Grundgerüst entwickeln** - - HTTP-Server mit grundlegenden Routen - - Konfigurationsmanagement (YAML-basiert) - - Service-Registry-Implementation +1. **C-HTTP-Server** - Minimal-Implementation (< 500 Zeilen) +2. **Lua-Integration** - C ↔ Lua Bridge etablieren +3. **Build-System** - Makefile-basiertes Build +4. **Basic-Routing** - Request-Routing in C + Lua -2. **Formular2Mail-Service implementieren** - - SMTP-Integration mit bestehendem Postfix - - Input-Validierung und Fehlerbehandlung - - Hugo-Shortcode für Kontaktformulare +### 12.2 Service-Implementation -3. **Apache-Integration konfigurieren** - - Reverse-Proxy für `api.dragons-at-work.de` - - SSL-Terminierung und Header-Forwarding - - Health-Check-Integration +1. **Formular2Mail** als erstes Lua-Service +2. **Authentication** in C mit Lua-Config +3. **Hugo-Integration** - Shortcodes adaptieren +4. **Testing-Framework** - C + Lua Tests -### 12.2 Mittelfristige Entwicklung (Wachstumsphase) +### 12.3 Production-Readiness -1. **Authentifizierungs-System ausbauen** - - Granulare API-Key-Berechtigungen - - Rate-Limiting und IP-Restrictions - - Admin-Interface für Key-Management - -2. **Monitoring und Logging** - - Strukturiertes JSON-Logging - - Health-Check-Aggregation - - Performance-Metriken - -3. **Service-Generator implementieren** - - Scaffolding für neue Services - - Template-basierte Code-Generierung - - Deployment-Script-Integration +1. **Performance-Tuning** - Memory, CPU optimieren +2. **Security-Hardening** - Input-Validation, Memory-Safety +3. **Documentation** - Installation, Configuration, Development +4. **Deployment-Automation** - Scripts für Production --- -Diese Konzeptdokumentation dient als Leitfaden für die Entwicklung von Furt und soll im Laufe des Projekts entsprechend der Erkenntnisse aus der praktischen Umsetzung angepasst und erweitert werden. Sie bildet die Grundlage für alle weiteren Architektur- und Implementierungsentscheidungen im Projekt. \ No newline at end of file +**Diese überarbeitete Architektur entspricht vollständig der Dragons@Work Tech-Reference und ermöglicht echte digitale Souveränität durch Corporate-freie Technologien.** + diff --git a/devdocs/furt_master_strategy.md b/devdocs/furt_master_strategy.md new file mode 100644 index 0000000..09e073d --- /dev/null +++ b/devdocs/furt_master_strategy.md @@ -0,0 +1,296 @@ +# Furt: Master-Strategie & Technologie-Migration + +**Erstellt:** 17. Juni 2025 +**Letzte Aktualisierung:** 17. Juni 2025 +**Version:** 1.0 +**Verantwortlich:** DAW-Team +**Dateipfad:** devdocs/MASTER_STRATEGY.md + +## Zweck dieses Dokuments + +Dieses Dokument definiert die langfristige Technologie-Migrationsstrategie für das gesamte Dragons@Work Ökosystem, mit Furt als erstem Schritt zur vollständigen digitalen Souveränität. + +## 🎯 Gesamtvision: Komplette Tech-Souveränität + +### Ausgangssituation (Juni 2025) +- **Server:** Ubuntu + Apache + ISPConfig +- **Website:** Hugo + digitalindependent Theme +- **Planned API:** Go-basiertes Furt (noch nicht implementiert) +- **Dependencies:** Viele Corporate-controlled Tools + +### Zielsituation (18-24 Monate) +- **Server:** OpenBSD + httpd + eigene Scripts +- **Website:** vefari (eigener Generator) + eigenes Theme +- **API:** C + Lua Furt (vollständig souverän) +- **Dependencies:** Minimal, alle selbst-kontrolliert + +## 📋 Migration-Roadmap + +### Phase 1: Furt API-Grundlagen (4 Wochen) +**Woche 1: Mail-Service (Pure Lua)** +- [x] Entscheidung: Pure Lua statt Go +- [ ] HTTP-Server (lua-socket) +- [ ] Mail-Handler (SMTP zu Postfix) +- [ ] API-Key-Auth +- [ ] Hugo-Integration (POST-based) + +**Woche 2-3: Service-Expansion** +- [ ] Comment-Service (sagjan-Integration) +- [ ] Health-Checks +- [ ] Error-Handling +- [ ] Basic Logging + +**Woche 4: Production-Ready** +- [ ] HTTPS (Lua-SSL) +- [ ] Systemd-Integration +- [ ] Monitoring +- [ ] Documentation + +### Phase 2: C-Integration (4-6 Wochen) +**Performance-Layer:** +- [ ] C-HTTP-Server (< 500 Zeilen) +- [ ] C ↔ Lua Bridge +- [ ] Memory-Management +- [ ] Security-Hardening + +### Phase 3: Infrastructure-Migration (6-12 Monate) +**Server-Migration:** +- [ ] OpenBSD-Evaluation +- [ ] ISPConfig → eigene Scripts +- [ ] Apache → OpenBSD httpd +- [ ] SSL-Management ohne Corporate-Tools + +### Phase 4: Website-Migration (3-6 Monate parallel) +**vefari-Entwicklung:** +- [ ] Hugo-Kompatibilität (Templates/Content) +- [ ] Markdown-Processing +- [ ] Multi-Language-Support +- [ ] Build-System + +### Phase 5: Complete Independence (langfristig) +**Advanced Features:** +- [ ] Eigener Browser (Exploration) +- [ ] Föderation zwischen Furt-Instanzen +- [ ] Advanced Services (Shop, Calendar, etc.) + +## 🏗️ Architektur-Prinzipien + +### Modularität (Anti-Monolith) +``` +Jedes Script/Modul: < 200 Zeilen +Jede Funktion: < 50 Zeilen +Jede Datei: Ein klarer Zweck +Keine 800-Zeilen-Monster! +``` + +### Technologie-Auswahl nach Tech-Reference +✅ **Erlaubt (Souverän):** +- C + GCC/musl +- Lua (PUC-Rio University) +- LMDB (Howard Chu/Symas) +- OpenBSD httpd + +❌ **Vermeiden (Corporate-Controlled):** +- Go (Google) +- Node.js (Corporate-Oligopol) +- Apache (Corporate-finanziert) +- MariaDB (VC-finanziert) + +⚠️ **Temporary OK (Migration-Pfad):** +- Ubuntu (→ OpenBSD) +- Apache (→ OpenBSD httpd) + +### Development-Prinzipien +1. **Verstehbarkeit** vor Features +2. **Kleine Module** vor Monolithen +3. **Eigene Kontrolle** vor Convenience +4. **Langfristig stabil** vor "Modern" +5. **Testing** für alles + +## 🔧 Technical Implementation Strategy + +### Furt-Architecture (Final) +``` +┌─────────────────┐ +│ OpenBSD httpd │ (SSL-Terminierung) +│ (Port 443) │ +└─────────┬───────┘ + │ +┌─────────▼───────┐ +│ C-HTTP-Gateway │ (Routing, Auth) +│ (Port 8080) │ +└─────────┬───────┘ + │ + ┌─────▼─────┐ ┌─────────┐ ┌─────────┐ + │ Lua-Mail │ │Lua-Comm│ │Lua-Shop │ + │(Port 8081)│ │(8082) │ │(8083) │ + └───────────┘ └─────────┘ └─────────┘ +``` + +### Service-Pattern (Standardisiert) +```lua +-- services/template.lua +local service = { + name = "service_name", + port = 808X, + + -- Standard Interface + handle_request = function(self, request) + -- Input-Validation (< 20 Zeilen) + -- Business-Logic (< 50 Zeilen) + -- Response-Formatting (< 10 Zeilen) + end, + + health_check = function(self) + -- Health-Logic (< 10 Zeilen) + end +} +``` + +### Testing-Strategy +``` +tests/ +├── unit/ # Lua-Modul-Tests +│ ├── test_mail.lua +│ └── test_auth.lua +├── integration/ # Service-Tests +│ └── test_api.lua +├── system/ # End-to-End-Tests +│ └── test_hugo.lua +└── performance/ # Load-Tests + └── test_load.lua +``` + +## 📊 SMTP-Configuration (Week 1) + +### Postfix-Integration +```lua +-- config/mail.lua +return { + smtp = { + server = "mail.dragons-at-work.de", + port = 465, + username = os.getenv("MAIL_USERNAME"), -- xxxx@dragons-at-work.de + password = os.getenv("MAIL_PASSWORD"), + security = "ssl/tls", + from = "noreply@dragons-at-work.de", + to = "michael@dragons-at-work.de" + } +} +``` + +### Security-Pattern +```lua +-- Nie Passwörter in Code! +-- Environment-Variables für Secrets +-- API-Keys in LMDB +-- IP-Allowlisting für Hugo +``` + +## 🚀 Hugo-Integration (Week 1) + +### Shortcode-Pattern +```hugo +{{< furt-mail + api-endpoint="https://api.dragons-at-work.de/v1/mail/send" + api-key="hugo-frontend-key" + success-url="/contact/thanks/" +>}} +``` + +### Progressive Enhancement +```html + +
+ + + + +
+ + + +``` + +## 📈 Success-Metrics + +### Week 1 Success-Criteria +- [ ] HTTP-Request funktioniert +- [ ] Mail wird via SMTP gesendet +- [ ] API-Key-Auth schützt Endpoint +- [ ] Hugo-Form sendet erfolgreich +- [ ] < 100ms Response-Time +- [ ] Jedes Modul < 200 Zeilen + +### Phase 1 Success-Criteria +- [ ] Production-ready Mail-Service +- [ ] Comment-Service implementiert +- [ ] HTTPS mit Lua-SSL +- [ ] Systemd-Service läuft stabil +- [ ] Documentation komplett + +### Long-term Success-Criteria +- [ ] Komplette Ubuntu → OpenBSD Migration +- [ ] Hugo → vefari Migration +- [ ] < 10 MB Total Memory für alle Services +- [ ] Zero Corporate-Dependencies + +## 🔄 Migration-Safety + +### Parallel-Betrieb-Strategie +``` +Week 1-4: Lua-Furt || Apache (parallel) +Month 2-6: C+Lua-Furt || Apache (parallel) +Month 6+: C+Lua-Furt || OpenBSD-httpd (parallel) +``` + +### Rollback-Plan +- Jede Migration-Phase kann rückgängig gemacht werden +- Hugo bleibt funktionsfähig während vefari-Entwicklung +- Apache bleibt als Fallback während OpenBSD-Migration + +### Testing vor Production +- Alle Changes erst auf Testumgebung +- Graduelle Umstellung Service für Service +- Monitoring für Performance-Regression + +## 📝 Documentation-Strategy + +### Development-Docs +- [ ] **Installation-Guide** (Linux → OpenBSD) +- [ ] **API-Documentation** (OpenAPI-Style) +- [ ] **Service-Development-Guide** (Lua-Pattern) +- [ ] **Testing-Guide** (Unit + Integration) + +### User-Docs +- [ ] **Hugo-Integration-Guide** +- [ ] **vefari-Migration-Guide** +- [ ] **Self-Hosting-Guide** + +### Philosophy-Docs +- [ ] **Tech-Souveränität-Rationale** +- [ ] **Corporate-Capture-Analysis** +- [ ] **Long-term-Vision** + +## 🎯 Next Session Preparation + +### Session-Focus: Lua-HTTP-Server Start +1. **Lua-Dependencies** installieren +2. **Basic HTTP-Server** (50-100 Zeilen) +3. **Request-Parsing** (POST-Body, Headers) +4. **Response-Formatting** (JSON) +5. **Error-Handling** (Basic) + +### Session-Deliverable +- `src/main.lua` - Funktionierender HTTP-Server +- `test/test_http.lua` - Basis-Tests +- `scripts/start.sh` - Start-Script + +### Session-Success-Metric +- `curl -X POST http://localhost:8080/test` → HTTP 200 Response + +--- + +**Diese Master-Strategie dient als Kompass für alle technischen Entscheidungen und stellt sicher, dass jeder kleine Schritt zum großen Ziel der technologischen Souveränität beiträgt.** \ No newline at end of file