refactor: move Go source files to src/ directory
Organize project structure by relocating all Go files to a src/ directory, following standard Go project conventions and improving code organization.
This commit is contained in:
362
src/auth.go
Normal file
362
src/auth.go
Normal file
@@ -0,0 +1,362 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var startTime = time.Now()
|
||||
|
||||
func CheckAuth(db *sql.DB, r *http.Request) bool {
|
||||
ip := r.Header.Get("X-Real-IP")
|
||||
if ip == "" {
|
||||
return false
|
||||
}
|
||||
ok, err := IsPermanentWhitelisted(db, ip)
|
||||
if err == nil && ok {
|
||||
return true
|
||||
}
|
||||
ok, err = IsTempWhitelisted(db, ip)
|
||||
if err == nil && ok {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func authHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
ip := r.Header.Get("X-Real-IP")
|
||||
if ip == "" {
|
||||
slog.Warn("auth denied: no X-Real-IP", "remote_addr", r.RemoteAddr)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if !CheckAuth(db, r) {
|
||||
slog.Warn("auth denied", "ip", ip)
|
||||
w.WriteHeader(http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
slog.Info("auth allowed", "ip", ip)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func apiKeyMiddleware(next http.HandlerFunc, token string) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, token) {
|
||||
slog.Warn("unauthorized API access")
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func whitelistTempHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, cfg.APIToken) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPost {
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
type request struct {
|
||||
IP string `json:"ip"`
|
||||
TTLSeconds int `json:"ttl_seconds"`
|
||||
Reason string `json:"reason,omitempty"`
|
||||
}
|
||||
var req request
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if req.IP == "" || req.TTLSeconds <= 0 {
|
||||
http.Error(w, "ip and ttl_seconds required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !IsIP(req.IP) {
|
||||
http.Error(w, "invalid IP address", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
clientIP := getClientIP(r)
|
||||
if err := AddTempEntry(db, req.IP, req.TTLSeconds, req.Reason, clientIP); err != nil {
|
||||
slog.Error("failed to add temp entry", "error", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
slog.Info("temp whitelist added", "ip", req.IP, "ttl", req.TTLSeconds)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func whitelistListHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, cfg.APIToken) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
limit, offset, err := parsePagination(r)
|
||||
if err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
entries, err := ListTempEntriesPaginated(db, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, "database error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(entries)
|
||||
}
|
||||
}
|
||||
|
||||
func permWhitelistListHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, cfg.APIToken) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
limit, offset, err := parsePagination(r)
|
||||
if err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
entries, err := ListPermEntriesPaginated(db, limit, offset)
|
||||
if err != nil {
|
||||
http.Error(w, "database error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(entries)
|
||||
}
|
||||
}
|
||||
|
||||
func whitelistDeleteHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, cfg.APIToken) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
ip := r.PathValue("ip")
|
||||
if ip == "" {
|
||||
http.Error(w, "ip required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
clientIP := getClientIP(r)
|
||||
if err := DeleteTempEntry(db, ip, clientIP); err != nil {
|
||||
slog.Error("failed to delete temp entry", "error", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
slog.Info("temp whitelist deleted", "ip", ip)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func logsHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, cfg.APIToken) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
query := `SELECT timestamp, action, ip, cidr, ttl_seconds, reason, api_client_ip FROM audit_log`
|
||||
var args []any
|
||||
|
||||
filterAction := r.URL.Query().Get("action")
|
||||
filterIP := r.URL.Query().Get("ip")
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
offsetStr := r.URL.Query().Get("offset")
|
||||
|
||||
var conditions []string
|
||||
if filterAction != "" {
|
||||
conditions = append(conditions, `action = ?`)
|
||||
args = append(args, filterAction)
|
||||
}
|
||||
if filterIP != "" {
|
||||
conditions = append(conditions, `ip = ?`)
|
||||
args = append(args, filterIP)
|
||||
}
|
||||
|
||||
if len(conditions) > 0 {
|
||||
query += " WHERE " + strings.Join(conditions, " AND ")
|
||||
}
|
||||
query += ` ORDER BY timestamp DESC`
|
||||
|
||||
limit := 200
|
||||
offset := 0
|
||||
if limitStr != "" {
|
||||
if parsed, err := strconv.Atoi(limitStr); err == nil && parsed > 0 && parsed <= 1000 {
|
||||
limit = parsed
|
||||
}
|
||||
}
|
||||
if offsetStr != "" {
|
||||
if parsed, err := strconv.Atoi(offsetStr); err == nil && parsed >= 0 {
|
||||
offset = parsed
|
||||
}
|
||||
}
|
||||
query += fmt.Sprintf(` LIMIT %d OFFSET %d`, limit, offset)
|
||||
|
||||
rows, err := db.Query(query, args...)
|
||||
if err != nil {
|
||||
slog.Error("failed to query logs", "error", err)
|
||||
http.Error(w, "database error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
logs := make([]map[string]interface{}, 0)
|
||||
for rows.Next() {
|
||||
var ts time.Time
|
||||
var action, apiClientIP string
|
||||
var ip, cidr, reason sql.NullString
|
||||
var ttlSeconds sql.NullInt64
|
||||
if err := rows.Scan(&ts, &action, &ip, &cidr, &ttlSeconds, &reason, &apiClientIP); err != nil {
|
||||
continue
|
||||
}
|
||||
entry := map[string]interface{}{
|
||||
"timestamp": ts,
|
||||
"action": action,
|
||||
"api_client_ip": apiClientIP,
|
||||
"reason": reason.String,
|
||||
}
|
||||
if ip.Valid {
|
||||
entry["ip"] = ip.String
|
||||
}
|
||||
if cidr.Valid {
|
||||
entry["cidr"] = cidr.String
|
||||
}
|
||||
if ttlSeconds.Valid {
|
||||
entry["ttl_seconds"] = ttlSeconds.Int64
|
||||
}
|
||||
logs = append(logs, entry)
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(logs)
|
||||
}
|
||||
}
|
||||
|
||||
func permWhitelistAddHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, cfg.APIToken) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
type request struct {
|
||||
Entry string `json:"entry"`
|
||||
}
|
||||
var req request
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if req.Entry == "" {
|
||||
http.Error(w, "entry required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if !IsIP(req.Entry) && !IsCIDR(req.Entry) {
|
||||
http.Error(w, "invalid entry (must be valid IP or CIDR range)", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
ok, err := AddPermanentEntry(db, req.Entry, getClientIP(r))
|
||||
if err != nil {
|
||||
slog.Error("failed to add perm entry", "error", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
http.Error(w, "entry already exists", http.StatusConflict)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func permWhitelistDeleteHandler(cfg Config, db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
if !verifyAPIKey(r, cfg.APIToken) {
|
||||
http.Error(w, "unauthorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
entry := r.PathValue("entry")
|
||||
if entry == "" {
|
||||
http.Error(w, "entry required", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if err := DeletePermanentEntry(db, entry, getClientIP(r)); err != nil {
|
||||
slog.Error("failed to delete perm entry", "error", err)
|
||||
http.Error(w, "internal error", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
|
||||
func getClientIP(r *http.Request) string {
|
||||
if ip := r.Header.Get("X-Real-IP"); ip != "" {
|
||||
return ip
|
||||
}
|
||||
ip, _, _ := net.SplitHostPort(r.RemoteAddr)
|
||||
return ip
|
||||
}
|
||||
|
||||
func verifyAPIKey(r *http.Request, expectedToken string) bool {
|
||||
return r.Header.Get("Authorization") == "Bearer "+expectedToken
|
||||
}
|
||||
|
||||
func statusHandler(db *sql.DB) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
var permCount int
|
||||
var tempCount int
|
||||
var dbOK bool
|
||||
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM perm_whitelist`).Scan(&permCount); err == nil {
|
||||
dbOK = true
|
||||
}
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM temp_whitelist WHERE expires_at > ?`, time.Now().Format(time.RFC3339)).Scan(&tempCount); err == nil {
|
||||
dbOK = true
|
||||
} else {
|
||||
dbOK = false
|
||||
}
|
||||
|
||||
health := map[string]interface{}{
|
||||
"status": "ok",
|
||||
"uptime": time.Since(startTime).String(),
|
||||
"perm_whitelist_count": permCount,
|
||||
"temp_whitelist_count": tempCount,
|
||||
"db_ok": dbOK,
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(health)
|
||||
}
|
||||
}
|
||||
|
||||
func parsePagination(r *http.Request) (int, int, error) {
|
||||
limitStr := r.URL.Query().Get("limit")
|
||||
offsetStr := r.URL.Query().Get("offset")
|
||||
|
||||
limit := 200
|
||||
offset := 0
|
||||
|
||||
if limitStr != "" {
|
||||
if parsed, err := strconv.Atoi(limitStr); err == nil && parsed > 0 && parsed <= 1000 {
|
||||
limit = parsed
|
||||
}
|
||||
}
|
||||
if offsetStr != "" {
|
||||
if parsed, err := strconv.Atoi(offsetStr); err == nil && parsed >= 0 {
|
||||
offset = parsed
|
||||
}
|
||||
}
|
||||
return limit, offset, nil
|
||||
}
|
||||
163
src/auth_test.go
Normal file
163
src/auth_test.go
Normal file
@@ -0,0 +1,163 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestIsIP(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantOK bool
|
||||
}{
|
||||
{"ipv4", "192.168.1.1", true},
|
||||
{"ipv4 loopback", "127.0.0.1", true},
|
||||
{"ipv6", "2001:0db8:85a3:0000:0000:8a2e:0370:7334", true},
|
||||
{"ipv6 short", "::1", true},
|
||||
{"empty", "", false},
|
||||
{"hostname", "example.com", false},
|
||||
{"garbage", "not-an-ip!!", false},
|
||||
{"partial", "192.168", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := IsIP(tt.input); got != tt.wantOK {
|
||||
t.Errorf("IsIP(%q) = %v, want %v", tt.input, got, tt.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsCIDR(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantOK bool
|
||||
}{
|
||||
{"ipv4 cidr", "192.168.1.0/24", true},
|
||||
{"ipv6 cidr", "2001:db8::/32", true},
|
||||
{"single host", "10.0.0.0/32", true},
|
||||
{"plain ip", "10.0.0.1", false},
|
||||
{"missing prefix", "192.168.1.0", false},
|
||||
{"garbage", "foo/bar", false},
|
||||
{"empty", "", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := IsCIDR(tt.input); got != tt.wantOK {
|
||||
t.Errorf("IsCIDR(%q) = %v, want %v", tt.input, got, tt.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestIPMatchesEntry(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
ip string
|
||||
entry string
|
||||
wantOK bool
|
||||
wantErr bool
|
||||
}{
|
||||
{"exact match", "192.168.1.5", "192.168.1.5", true, false},
|
||||
{"ipv4 cidr match", "10.0.0.5", "10.0.0.0/24", true, false},
|
||||
{"ipv4 cidr no match", "10.0.1.5", "10.0.0.0/24", false, false},
|
||||
{"ipv6 cidr match", "2001:db8::1", "2001:db8::/32", true, false},
|
||||
{"invalid entry", "10.0.0.1", "not-a-cidr", false, false},
|
||||
{"empty entry", "10.0.0.1", "", false, false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ipMatchesEntry(tt.ip, tt.entry)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Errorf("ipMatchesEntry(%q, %q) = %v, want error", tt.ip, tt.entry, got)
|
||||
}
|
||||
} else {
|
||||
if err != nil {
|
||||
t.Errorf("ipMatchesEntry(%q, %q) error: %v", tt.ip, tt.entry, err)
|
||||
}
|
||||
if got != tt.wantOK {
|
||||
t.Errorf("ipMatchesEntry(%q, %q) = %v, want %v", tt.ip, tt.entry, got, tt.wantOK)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyAPIKey(t *testing.T) {
|
||||
token := "super-secret"
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
auth string
|
||||
wantOK bool
|
||||
}{
|
||||
{"correct token", "Bearer super-secret", true},
|
||||
{"missing Bearer", "super-secret", false},
|
||||
{"wrong token", "Bearer wrong", false},
|
||||
{"empty", "", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := http.Request{Header: http.Header{}}
|
||||
r.Header.Set("Authorization", tt.auth)
|
||||
if got := verifyAPIKey(&r, token); got != tt.wantOK {
|
||||
t.Errorf("verifyAPIKey(%q) = %v, want %v", tt.auth, got, tt.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiKeyMiddleware(t *testing.T) {
|
||||
token := "test-token"
|
||||
called := false
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
called = true
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
wrapped := apiKeyMiddleware(next, token)
|
||||
|
||||
t.Run("valid key", func(t *testing.T) {
|
||||
called = false
|
||||
r := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
r.Header.Set("Authorization", "Bearer test-token")
|
||||
w := httptest.NewRecorder()
|
||||
wrapped(w, r)
|
||||
if !called {
|
||||
t.Error("middleware did not call next handler")
|
||||
}
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Errorf("expected 204, got %d", w.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("invalid key", func(t *testing.T) {
|
||||
called = false
|
||||
r := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
r.Header.Set("Authorization", "Bearer wrong")
|
||||
w := httptest.NewRecorder()
|
||||
wrapped(w, r)
|
||||
if called {
|
||||
t.Error("middleware called next handler despite invalid key")
|
||||
}
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", w.Code)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("missing key", func(t *testing.T) {
|
||||
called = false
|
||||
r := httptest.NewRequest(http.MethodGet, "/test", nil)
|
||||
w := httptest.NewRecorder()
|
||||
wrapped(w, r)
|
||||
if called {
|
||||
t.Error("middleware called next handler despite missing key")
|
||||
}
|
||||
if w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("expected 401, got %d", w.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
21
src/cleanup.go
Normal file
21
src/cleanup.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"time"
|
||||
)
|
||||
|
||||
func cleanupLoop(ctx context.Context, db *sql.DB, interval time.Duration) {
|
||||
ticker := time.NewTicker(interval)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
_ = CleanupExpiredTemp(db)
|
||||
_ = RotateAuditLog(db, 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
41
src/config.go
Normal file
41
src/config.go
Normal file
@@ -0,0 +1,41 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Port string
|
||||
APIToken string
|
||||
DataDir string
|
||||
CleanupInterval time.Duration
|
||||
DBPath string
|
||||
}
|
||||
|
||||
func loadConfig() Config {
|
||||
return Config{
|
||||
Port: getEnv("AUTH_PROXY_PORT", "8080"),
|
||||
APIToken: getEnv("AUTH_PROXY_API_TOKEN", ""),
|
||||
DataDir: getEnv("DATA_DIR", "/data"),
|
||||
CleanupInterval: parseDuration("CLEANUP_INTERVAL", 60*time.Second),
|
||||
DBPath: getEnv("AUTH_PROXY_DB_PATH", "/data/auth-proxy.db"),
|
||||
}
|
||||
}
|
||||
|
||||
func getEnv(key, defaultValue string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
func parseDuration(key string, defaultVal time.Duration) time.Duration {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
d, err := time.ParseDuration(v)
|
||||
if err == nil {
|
||||
return d
|
||||
}
|
||||
}
|
||||
return defaultVal
|
||||
}
|
||||
412
src/db.go
Normal file
412
src/db.go
Normal file
@@ -0,0 +1,412 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net"
|
||||
"time"
|
||||
|
||||
sqlite "modernc.org/sqlite"
|
||||
)
|
||||
|
||||
func InitDB(dbPath string) (*sql.DB, error) {
|
||||
db, err := sql.Open("sqlite", dbPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, err = db.Exec(`PRAGMA journal_mode=WAL; PRAGMA busy_timeout=5000;`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
schema := `
|
||||
CREATE TABLE IF NOT EXISTS perm_whitelist (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
entry TEXT NOT NULL UNIQUE,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS temp_whitelist (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
ip TEXT NOT NULL UNIQUE,
|
||||
expires_at DATETIME NOT NULL,
|
||||
reason TEXT,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_temp_expires ON temp_whitelist(expires_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
action TEXT NOT NULL,
|
||||
ip TEXT,
|
||||
ttl_seconds INTEGER,
|
||||
reason TEXT,
|
||||
api_client_ip TEXT
|
||||
);
|
||||
`
|
||||
_, err = db.Exec(schema)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return db, nil
|
||||
}
|
||||
|
||||
func AddPermanentEntry(db *sql.DB, entry, apiClientIP string) (bool, error) {
|
||||
_, err := db.Exec(`INSERT INTO perm_whitelist(entry) VALUES(?)`, entry)
|
||||
if err != nil {
|
||||
if isUniqueConstraintError(err) {
|
||||
_, err = db.Exec(`
|
||||
INSERT INTO audit_log(action, ip, api_client_ip)
|
||||
VALUES('add_perm_duplicate', ?, ?)
|
||||
`, entry, apiClientIP)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
_, err = db.Exec(`
|
||||
INSERT INTO audit_log(action, ip, api_client_ip)
|
||||
VALUES('add_perm', ?, ?)
|
||||
`, entry, apiClientIP)
|
||||
if err != nil {
|
||||
return true, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func DeletePermanentEntry(db *sql.DB, entry, apiClientIP string) error {
|
||||
_, err := db.Exec(`
|
||||
DELETE FROM perm_whitelist
|
||||
WHERE entry = ?
|
||||
`, entry)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = db.Exec(`
|
||||
INSERT INTO audit_log(action, ip, api_client_ip)
|
||||
VALUES('delete_perm', ?, ?)
|
||||
`, entry, apiClientIP)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func IsPermanentWhitelisted(db *sql.DB, ip string) (bool, error) {
|
||||
rows, err := db.Query(`
|
||||
SELECT entry
|
||||
FROM perm_whitelist
|
||||
`)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var entry string
|
||||
if err := rows.Scan(&entry); err != nil {
|
||||
continue
|
||||
}
|
||||
matches, err := ipMatchesEntry(ip, entry)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if matches {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func AddTempEntry(db *sql.DB, ip string, ttlSeconds int, reason, apiClientIP string) error {
|
||||
expiresAt := time.Now().Add(time.Duration(ttlSeconds) * time.Second)
|
||||
_, err := db.Exec(`
|
||||
INSERT INTO temp_whitelist(ip, expires_at, reason)
|
||||
VALUES(?, ?, ?)
|
||||
ON CONFLICT(ip) DO UPDATE SET expires_at=excluded.expires_at, reason=excluded.reason
|
||||
`, ip, expiresAt, reason)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = db.Exec(`
|
||||
INSERT INTO audit_log(action, ip, ttl_seconds, reason, api_client_ip)
|
||||
VALUES('add_temp', ?, ?, ?, ?)
|
||||
`, ip, ttlSeconds, reason, apiClientIP)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DeleteTempEntry(db *sql.DB, ip, apiClientIP string) error {
|
||||
_, err := db.Exec(`
|
||||
DELETE FROM temp_whitelist
|
||||
WHERE ip = ?
|
||||
`, ip)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = db.Exec(`
|
||||
INSERT INTO audit_log(action, ip, api_client_ip)
|
||||
VALUES('delete_temp', ?, ?)
|
||||
`, ip, apiClientIP)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func IsTempWhitelisted(db *sql.DB, ip string) (bool, error) {
|
||||
var expiresAt time.Time
|
||||
err := db.QueryRow(`
|
||||
SELECT expires_at
|
||||
FROM temp_whitelist
|
||||
WHERE ip = ?
|
||||
`, ip).Scan(&expiresAt)
|
||||
if err == sql.ErrNoRows {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return expiresAt.After(time.Now()), nil
|
||||
}
|
||||
|
||||
func CleanupExpiredTemp(db *sql.DB) error {
|
||||
rows, err := db.Query(`
|
||||
SELECT ip
|
||||
FROM temp_whitelist
|
||||
WHERE expires_at <= ?
|
||||
`, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var expiredIPs []string
|
||||
for rows.Next() {
|
||||
var ip string
|
||||
if err := rows.Scan(&ip); err == nil {
|
||||
expiredIPs = append(expiredIPs, ip)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
|
||||
_, err = db.Exec(`
|
||||
DELETE FROM temp_whitelist
|
||||
WHERE expires_at <= ?
|
||||
`, time.Now())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var reason string
|
||||
reason = "expired"
|
||||
|
||||
for _, ip := range expiredIPs {
|
||||
_, err = db.Exec(`
|
||||
INSERT INTO audit_log(action, ip, reason)
|
||||
VALUES('expire_temp', ?, ?)
|
||||
`, ip, reason)
|
||||
if err != nil {
|
||||
slog.Warn("failed to log expired temp entry", "ip", ip, "error", err)
|
||||
}
|
||||
slog.Info("expired temporary whitelist", "ip", ip)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ListTempEntries(db *sql.DB) ([]map[string]interface{}, error) {
|
||||
rows, err := db.Query(`
|
||||
SELECT ip, expires_at, reason
|
||||
FROM temp_whitelist
|
||||
WHERE expires_at > ?
|
||||
ORDER BY expires_at
|
||||
`, time.Now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var list []map[string]interface{} = make([]map[string]interface{}, 0)
|
||||
for rows.Next() {
|
||||
var ip string
|
||||
var expiresAt time.Time
|
||||
var reason sql.NullString
|
||||
if err := rows.Scan(&ip, &expiresAt, &reason); err != nil {
|
||||
continue
|
||||
}
|
||||
list = append(list, map[string]interface{}{
|
||||
"ip": ip,
|
||||
"expires": expiresAt,
|
||||
"reason": reason.String,
|
||||
})
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func ListPermEntries(db *sql.DB) ([]map[string]interface{}, error) {
|
||||
rows, err := db.Query(`
|
||||
SELECT entry
|
||||
FROM perm_whitelist
|
||||
ORDER BY created_at
|
||||
`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var list []map[string]interface{} = make([]map[string]interface{}, 0)
|
||||
for rows.Next() {
|
||||
var entry string
|
||||
if err := rows.Scan(&entry); err != nil {
|
||||
continue
|
||||
}
|
||||
list = append(list, map[string]interface{}{
|
||||
"entry": entry,
|
||||
})
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func ListTempEntriesPaginated(db *sql.DB, limit, offset int) ([]map[string]interface{}, error) {
|
||||
rows, err := db.Query(`
|
||||
SELECT ip, expires_at, reason
|
||||
FROM temp_whitelist
|
||||
WHERE expires_at > ?
|
||||
ORDER BY expires_at
|
||||
LIMIT ? OFFSET ?
|
||||
`, time.Now(), limit, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var list []map[string]interface{} = make([]map[string]interface{}, 0)
|
||||
for rows.Next() {
|
||||
var ip string
|
||||
var expiresAt time.Time
|
||||
var reason sql.NullString
|
||||
if err := rows.Scan(&ip, &expiresAt, &reason); err != nil {
|
||||
continue
|
||||
}
|
||||
list = append(list, map[string]interface{}{
|
||||
"ip": ip,
|
||||
"expires": expiresAt,
|
||||
"reason": reason.String,
|
||||
})
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func ListPermEntriesPaginated(db *sql.DB, limit, offset int) ([]map[string]interface{}, error) {
|
||||
rows, err := db.Query(`
|
||||
SELECT entry
|
||||
FROM perm_whitelist
|
||||
ORDER BY created_at
|
||||
LIMIT ? OFFSET ?
|
||||
`, limit, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var list []map[string]interface{} = make([]map[string]interface{}, 0)
|
||||
for rows.Next() {
|
||||
var entry string
|
||||
if err := rows.Scan(&entry); err != nil {
|
||||
continue
|
||||
}
|
||||
list = append(list, map[string]interface{}{
|
||||
"entry": entry,
|
||||
})
|
||||
}
|
||||
return list, nil
|
||||
}
|
||||
|
||||
func ipMatchesEntry(ip, entry string) (bool, error) {
|
||||
if entry == ip {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
if len(entry) > 0 && entry[0] != '/' && containsSlash(entry) {
|
||||
_, ipnet, err := net.ParseCIDR(entry)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
parsedIP := net.ParseIP(ip)
|
||||
if parsedIP == nil {
|
||||
return false, nil
|
||||
}
|
||||
return ipnet.Contains(parsedIP), nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func containsSlash(s string) bool {
|
||||
for i := 0; i < len(s); i++ {
|
||||
if s[i] == '/' {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isUniqueConstraintError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
var sqliteErr *sqlite.Error
|
||||
if errors.As(err, &sqliteErr) {
|
||||
return sqliteErr.Code() == 19
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func IsIP(s string) bool {
|
||||
return net.ParseIP(s) != nil
|
||||
}
|
||||
|
||||
func IsCIDR(s string) bool {
|
||||
_, _, err := net.ParseCIDR(s)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func RotateAuditLog(db *sql.DB, maxEntries int) error {
|
||||
if maxEntries <= 0 {
|
||||
maxEntries = 200000
|
||||
}
|
||||
var count int
|
||||
err := db.QueryRow(`SELECT COUNT(*) FROM audit_log`).Scan(&count)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if count <= maxEntries {
|
||||
return nil
|
||||
}
|
||||
rows, err := db.Query(`
|
||||
SELECT id FROM audit_log
|
||||
ORDER BY timestamp ASC
|
||||
LIMIT ?
|
||||
`, count-maxEntries)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var ids []int64
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
if err := rows.Scan(&id); err == nil {
|
||||
ids = append(ids, id)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
_, err = db.Exec(`
|
||||
DELETE FROM audit_log
|
||||
WHERE id IN (
|
||||
SELECT id FROM audit_log
|
||||
ORDER BY timestamp ASC
|
||||
LIMIT ?
|
||||
)
|
||||
`, count-maxEntries)
|
||||
return err
|
||||
}
|
||||
67
src/main.go
Normal file
67
src/main.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cfg := loadConfig()
|
||||
if cfg.APIToken == "" {
|
||||
log.Fatal("AUTH_PROXY_API_TOKEN environment variable is required")
|
||||
}
|
||||
|
||||
slog.SetDefault(slog.New(slog.NewTextHandler(os.Stdout, nil)))
|
||||
|
||||
db, err := InitDB(cfg.DBPath)
|
||||
if err != nil {
|
||||
slog.Error("failed to init database", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer db.Close()
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
go cleanupLoop(ctx, db, cfg.CleanupInterval)
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/auth", authHandler(cfg, db))
|
||||
mux.HandleFunc("/api/whitelist/temp", whitelistTempHandler(cfg, db))
|
||||
mux.HandleFunc("/api/whitelist/temp/list", whitelistListHandler(cfg, db))
|
||||
mux.HandleFunc("/api/whitelist/temp/{ip}", whitelistDeleteHandler(cfg, db))
|
||||
mux.HandleFunc("/api/whitelist/perm", permWhitelistAddHandler(cfg, db))
|
||||
mux.HandleFunc("/api/whitelist/perm/list", permWhitelistListHandler(cfg, db))
|
||||
mux.HandleFunc("/api/whitelist/perm/{entry}", permWhitelistDeleteHandler(cfg, db))
|
||||
mux.HandleFunc("/api/logs", logsHandler(cfg, db))
|
||||
mux.HandleFunc("/status", statusHandler(db))
|
||||
|
||||
server := &http.Server{
|
||||
Addr: ":" + cfg.Port,
|
||||
Handler: mux,
|
||||
}
|
||||
|
||||
go func() {
|
||||
slog.Info("server listening", "addr", server.Addr)
|
||||
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
||||
slog.Error("server error", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}()
|
||||
|
||||
quit := make(chan os.Signal, 1)
|
||||
signal.Notify(quit, syscall.SIGTERM, syscall.SIGINT)
|
||||
<-quit
|
||||
|
||||
slog.Info("shutting down...")
|
||||
cancel()
|
||||
shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer shutdownCancel()
|
||||
server.Shutdown(shutdownCtx)
|
||||
}
|
||||
Reference in New Issue
Block a user