Compare commits
23 Commits
important-
...
23a2951f8c
| Author | SHA1 | Date | |
|---|---|---|---|
| 23a2951f8c | |||
| ead2b18991 | |||
| 781e4f3100 | |||
| c2d799eb18 | |||
| b4bbaf25c9 | |||
| 524f2deb50 | |||
| b3dcdf09be | |||
| c478a4306a | |||
| 6d60a8663e | |||
| b9c40596b3 | |||
| b31d39d971 | |||
| 253308dcc5 | |||
| 90d1c1b562 | |||
| 1fe45eaed1 | |||
| a6979805c1 | |||
| 644cf426d6 | |||
| f11c758008 | |||
| bfeeaa1190 | |||
| ad656fd636 | |||
|
|
fa8c6d02fd | ||
|
|
fc67533db9 | ||
| ccb4ff7ecb | |||
|
|
ba06fb0c7c |
@@ -1,5 +1,6 @@
|
|||||||
FROM golang:1.26-alpine AS builder
|
FROM golang:1.26-alpine AS builder
|
||||||
|
|
||||||
|
ARG GIT_COMMIT=dev
|
||||||
|
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|
||||||
@@ -13,7 +14,7 @@ COPY . .
|
|||||||
ENV CGO_ENABLED=1
|
ENV CGO_ENABLED=1
|
||||||
ENV GIN_MODE=release
|
ENV GIN_MODE=release
|
||||||
|
|
||||||
RUN go build -o app ./cmd/server
|
RUN go build -ldflags "-X ResendIt/internal/buildinfo.Commit=${GIT_COMMIT}" -o app ./cmd/server
|
||||||
|
|
||||||
FROM alpine:latest
|
FROM alpine:latest
|
||||||
|
|
||||||
@@ -24,7 +25,6 @@ RUN apk add --no-cache ca-certificates tzdata
|
|||||||
COPY --from=builder /app/app .
|
COPY --from=builder /app/app .
|
||||||
COPY --from=builder /app/templates ./templates
|
COPY --from=builder /app/templates ./templates
|
||||||
COPY --from=builder /app/static ./static
|
COPY --from=builder /app/static ./static
|
||||||
COPY --from=builder /app/.env ./
|
|
||||||
|
|
||||||
RUN mkdir -p /app/uploads
|
RUN mkdir -p /app/uploads
|
||||||
|
|
||||||
|
|||||||
115
Jenkinsfile
vendored
Normal file
115
Jenkinsfile
vendored
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
pipeline {
|
||||||
|
agent any
|
||||||
|
|
||||||
|
options {
|
||||||
|
timestamps()
|
||||||
|
disableConcurrentBuilds()
|
||||||
|
}
|
||||||
|
|
||||||
|
environment {
|
||||||
|
REGISTRY = "git.brammie15.dev"
|
||||||
|
IMAGE_NAME = "brammie15/resendit"
|
||||||
|
REGISTRY_CREDS = "registry-creds"
|
||||||
|
IMAGE = "${REGISTRY}/${IMAGE_NAME}"
|
||||||
|
DD_URL = "https://DD.brammie15.dev"
|
||||||
|
DD_API_KEY = credentials('dd-api-key')
|
||||||
|
NVD_API_KEY = credentials("nvd-api-key")
|
||||||
|
}
|
||||||
|
|
||||||
|
stages {
|
||||||
|
|
||||||
|
stage('Debug') {
|
||||||
|
steps {
|
||||||
|
sh 'echo "WORKSPACE: $WORKSPACE" && echo "PWD: $(pwd)" && ls -la'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Checkout') {
|
||||||
|
steps {
|
||||||
|
checkout scm
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('SAST - Semgrep') {
|
||||||
|
steps {
|
||||||
|
sh """
|
||||||
|
docker run --rm -v "\$(pwd):/src" \
|
||||||
|
returntocorp/semgrep \
|
||||||
|
semgrep scan --config=p/ci --debug \
|
||||||
|
--sarif --output /src/semgrep.sarif \
|
||||||
|
/src/internal /src/cmd || true
|
||||||
|
|
||||||
|
echo "After semgrep:"
|
||||||
|
ls -la
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Upload to DefectDojo') {
|
||||||
|
steps {
|
||||||
|
sh """
|
||||||
|
curl -X POST "${DD_URL}/api/v2/import-scan/" \
|
||||||
|
-H "Authorization: Token ${DD_API_KEY}" \
|
||||||
|
-F "scan_type=SARIF" \
|
||||||
|
-F "file=@\$(pwd)/semgrep.sarif" \
|
||||||
|
-F "product_name=ReSendit" \
|
||||||
|
-F "engagement_name=Jenkins-CI" \
|
||||||
|
-F "auto_create_context=true" \
|
||||||
|
-F "close_old_findings=true"
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Build image') {
|
||||||
|
steps {
|
||||||
|
script {
|
||||||
|
def shortSha = sh(script: 'git rev-parse --short=12 HEAD', returnStdout: true).trim()
|
||||||
|
env.IMAGE_TAG_SHA = shortSha
|
||||||
|
sh """
|
||||||
|
docker build \
|
||||||
|
--build-arg GIT_COMMIT=${IMAGE_TAG_SHA} \
|
||||||
|
-t ${IMAGE}:${IMAGE_TAG_SHA} .
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Login to registry') {
|
||||||
|
steps {
|
||||||
|
withCredentials([usernamePassword(credentialsId: "${REGISTRY_CREDS}", usernameVariable: 'REG_USER', passwordVariable: 'REG_PASS')]) {
|
||||||
|
sh 'echo "$REG_PASS" | docker login ${REGISTRY} -u "$REG_USER" --password-stdin'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
stage('Push image') {
|
||||||
|
steps {
|
||||||
|
script {
|
||||||
|
sh "docker push ${IMAGE}:${IMAGE_TAG_SHA}"
|
||||||
|
def branch = (env.BRANCH_NAME ?: sh(script: 'git rev-parse --abbrev-ref HEAD', returnStdout: true).trim())
|
||||||
|
def safeBranch = branch.replaceAll('[^a-zA-Z0-9_.-]', '-')
|
||||||
|
sh """
|
||||||
|
docker tag ${IMAGE}:${IMAGE_TAG_SHA} ${IMAGE}:${safeBranch}
|
||||||
|
docker push ${IMAGE}:${safeBranch}
|
||||||
|
"""
|
||||||
|
if (branch == 'master') {
|
||||||
|
sh """
|
||||||
|
docker tag ${IMAGE}:${IMAGE_TAG_SHA} ${IMAGE}:latest
|
||||||
|
docker push ${IMAGE}:latest
|
||||||
|
"""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
post {
|
||||||
|
always {
|
||||||
|
sh 'docker logout ${REGISTRY} || true'
|
||||||
|
sh 'docker image rm -f ${IMAGE}:${IMAGE_TAG_SHA} || true'
|
||||||
|
sh 'docker image prune -f || true'
|
||||||
|
// sh 'rm -f semgrep.sarif || true'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"ResendIt/internal/api/middleware"
|
"ResendIt/internal/api/middleware"
|
||||||
"ResendIt/internal/auth"
|
"ResendIt/internal/auth"
|
||||||
|
"ResendIt/internal/config"
|
||||||
"ResendIt/internal/db"
|
"ResendIt/internal/db"
|
||||||
"ResendIt/internal/file"
|
"ResendIt/internal/file"
|
||||||
"ResendIt/internal/user"
|
"ResendIt/internal/user"
|
||||||
@@ -32,7 +33,7 @@ func main() {
|
|||||||
panic(fmt.Errorf("failed to connect database: %w", err))
|
panic(fmt.Errorf("failed to connect database: %w", err))
|
||||||
}
|
}
|
||||||
|
|
||||||
err = dbCon.AutoMigrate(&user.User{}, &file.FileRecord{})
|
err = dbCon.AutoMigrate(&user.User{}, &file.FileRecord{}, &config.ConfigEntry{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
fmt.Printf("Error migrating database: %v\n", err)
|
fmt.Printf("Error migrating database: %v\n", err)
|
||||||
return
|
return
|
||||||
@@ -69,22 +70,33 @@ func main() {
|
|||||||
userService := user.NewService(userRepo)
|
userService := user.NewService(userRepo)
|
||||||
userHandler := user.NewHandler(userService)
|
userHandler := user.NewHandler(userService)
|
||||||
|
|
||||||
|
configRepo := config.NewRepository(dbCon)
|
||||||
|
configService := config.NewService(configRepo)
|
||||||
|
|
||||||
fileRepo := file.NewRepository(dbCon)
|
fileRepo := file.NewRepository(dbCon)
|
||||||
fileService := file.NewService(fileRepo, "./uploads")
|
fileService := file.NewService(fileRepo, "./uploads")
|
||||||
fileHandler := file.NewHandler(fileService)
|
fileHandler := file.NewHandler(fileService, configService)
|
||||||
|
|
||||||
createAdminUser(userService)
|
createAdminUser(userService)
|
||||||
|
|
||||||
apiRoute := r.Group("/api")
|
apiRoute := r.Group("/api")
|
||||||
// General API rate limiting to reduce abuse/spam.
|
// General API rate limiting to reduce abuse/spam.
|
||||||
// ~60 req/min per IP with some burst room.
|
apiRoute.Use(middleware.RateLimitByIPDynamic(
|
||||||
apiRoute.Use(middleware.RateLimitByIP(60, time.Minute, 30, 5*time.Minute))
|
func() int {
|
||||||
|
return configService.GetIntDefault(config.KeyRateLimitApiPerMinute, config.DefaultRateLimitApiPerMinute)
|
||||||
|
},
|
||||||
|
time.Minute,
|
||||||
|
func() int {
|
||||||
|
return configService.GetIntDefault(config.KeyRateLimitApiBurst, config.DefaultRateLimitApiBurst)
|
||||||
|
},
|
||||||
|
5*time.Minute,
|
||||||
|
))
|
||||||
|
|
||||||
auth.RegisterRoutes(apiRoute, authHandler)
|
auth.RegisterRoutes(apiRoute, authHandler, configService)
|
||||||
user.RegisterRoutes(apiRoute, userHandler)
|
user.RegisterRoutes(apiRoute, userHandler)
|
||||||
file.RegisterRoutes(apiRoute, fileHandler)
|
file.RegisterRoutes(apiRoute, fileHandler)
|
||||||
|
|
||||||
webHandler := web.NewHandler(fileService)
|
webHandler := web.NewHandler(fileService, configService)
|
||||||
web.RegisterRoutes(r, webHandler, userService)
|
web.RegisterRoutes(r, webHandler, userService)
|
||||||
|
|
||||||
port := os.Getenv("PORT")
|
port := os.Getenv("PORT")
|
||||||
|
|||||||
@@ -48,6 +48,8 @@ func (b *tokenBucket) allow() bool {
|
|||||||
|
|
||||||
type ipClient struct {
|
type ipClient struct {
|
||||||
bucket *tokenBucket
|
bucket *tokenBucket
|
||||||
|
max int
|
||||||
|
burst int
|
||||||
lastSeen time.Time
|
lastSeen time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,6 +60,12 @@ type ipClient struct {
|
|||||||
// burst: optional burst capacity (defaults to max if <=0)
|
// burst: optional burst capacity (defaults to max if <=0)
|
||||||
// ttl: how long to keep idle IP buckets around
|
// ttl: how long to keep idle IP buckets around
|
||||||
func RateLimitByIP(max int, per time.Duration, burst int, ttl time.Duration) gin.HandlerFunc {
|
func RateLimitByIP(max int, per time.Duration, burst int, ttl time.Duration) gin.HandlerFunc {
|
||||||
|
return RateLimitByIPDynamic(func() int { return max }, per, func() int { return burst }, ttl)
|
||||||
|
}
|
||||||
|
|
||||||
|
// RateLimitByIPDynamic is like RateLimitByIP but reads max/burst dynamically.
|
||||||
|
// This allows changing limits at runtime (e.g. from an admin config page).
|
||||||
|
func RateLimitByIPDynamic(maxFn func() int, per time.Duration, burstFn func() int, ttl time.Duration) gin.HandlerFunc {
|
||||||
var (
|
var (
|
||||||
mu sync.Mutex
|
mu sync.Mutex
|
||||||
clients = make(map[string]*ipClient)
|
clients = make(map[string]*ipClient)
|
||||||
@@ -86,16 +94,22 @@ func RateLimitByIP(max int, per time.Duration, burst int, ttl time.Duration) gin
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
getClient := func(ip string, now time.Time) *ipClient {
|
getClient := func(ip string, now time.Time, max int, burst int) *ipClient {
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
defer mu.Unlock()
|
defer mu.Unlock()
|
||||||
c, ok := clients[ip]
|
c, ok := clients[ip]
|
||||||
if !ok {
|
if !ok {
|
||||||
c = &ipClient{bucket: newTokenBucket(max, per, burst), lastSeen: now}
|
c = &ipClient{bucket: newTokenBucket(max, per, burst), max: max, burst: burst, lastSeen: now}
|
||||||
clients[ip] = c
|
clients[ip] = c
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
c.lastSeen = now
|
c.lastSeen = now
|
||||||
|
// If settings changed, reset the bucket.
|
||||||
|
if c.max != max || c.burst != burst {
|
||||||
|
c.bucket = newTokenBucket(max, per, burst)
|
||||||
|
c.max = max
|
||||||
|
c.burst = burst
|
||||||
|
}
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -104,7 +118,15 @@ func RateLimitByIP(max int, per time.Duration, burst int, ttl time.Duration) gin
|
|||||||
cleanup(now)
|
cleanup(now)
|
||||||
|
|
||||||
ip := c.ClientIP()
|
ip := c.ClientIP()
|
||||||
client := getClient(ip, now)
|
max := maxFn()
|
||||||
|
if max <= 0 {
|
||||||
|
max = 1
|
||||||
|
}
|
||||||
|
burst := burstFn()
|
||||||
|
if burst <= 0 {
|
||||||
|
burst = max
|
||||||
|
}
|
||||||
|
client := getClient(ip, now, max, burst)
|
||||||
|
|
||||||
if !client.bucket.allow() {
|
if !client.bucket.allow() {
|
||||||
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{
|
||||||
|
|||||||
@@ -1,64 +0,0 @@
|
|||||||
package middleware
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"net/http/httptest"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestRateLimitByIP_BlocksAfterLimit(t *testing.T) {
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
r := gin.New()
|
|
||||||
// 1 request per hour, burst 1 => second immediate request should 429.
|
|
||||||
r.Use(RateLimitByIP(1, time.Hour, 1, time.Minute))
|
|
||||||
r.GET("/", func(c *gin.Context) { c.String(200, "ok") })
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
||||||
req.RemoteAddr = "203.0.113.10:1234"
|
|
||||||
|
|
||||||
w1 := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w1, req)
|
|
||||||
if w1.Code != http.StatusOK {
|
|
||||||
t.Fatalf("first request code = %d, want %d", w1.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
w2 := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w2, req)
|
|
||||||
if w2.Code != http.StatusTooManyRequests {
|
|
||||||
t.Fatalf("second request code = %d, want %d", w2.Code, http.StatusTooManyRequests)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestRateLimitByIP_AllowsBurst(t *testing.T) {
|
|
||||||
gin.SetMode(gin.TestMode)
|
|
||||||
|
|
||||||
r := gin.New()
|
|
||||||
// 1 per hour, but burst 2 => first two immediate requests should pass.
|
|
||||||
r.Use(RateLimitByIP(1, time.Hour, 2, time.Minute))
|
|
||||||
r.GET("/", func(c *gin.Context) { c.String(200, "ok") })
|
|
||||||
|
|
||||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
|
||||||
req.RemoteAddr = "203.0.113.11:1234"
|
|
||||||
|
|
||||||
w1 := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w1, req)
|
|
||||||
if w1.Code != http.StatusOK {
|
|
||||||
t.Fatalf("first request code = %d, want %d", w1.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
w2 := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w2, req)
|
|
||||||
if w2.Code != http.StatusOK {
|
|
||||||
t.Fatalf("second request code = %d, want %d", w2.Code, http.StatusOK)
|
|
||||||
}
|
|
||||||
|
|
||||||
w3 := httptest.NewRecorder()
|
|
||||||
r.ServeHTTP(w3, req)
|
|
||||||
if w3.Code != http.StatusTooManyRequests {
|
|
||||||
t.Fatalf("third request code = %d, want %d", w3.Code, http.StatusTooManyRequests)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,17 +2,30 @@ package auth
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"ResendIt/internal/api/middleware"
|
"ResendIt/internal/api/middleware"
|
||||||
|
"ResendIt/internal/config"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
)
|
)
|
||||||
|
|
||||||
func RegisterRoutes(r *gin.RouterGroup, h *Handler) {
|
type ConfigService interface {
|
||||||
|
GetIntDefault(key string, def int) int
|
||||||
|
}
|
||||||
|
|
||||||
|
func RegisterRoutes(r *gin.RouterGroup, h *Handler, cfg ConfigService) {
|
||||||
auth := r.Group("/auth")
|
auth := r.Group("/auth")
|
||||||
|
|
||||||
// Stricter rate limit on login to reduce brute-force / log spam.
|
// Stricter rate limit on login to reduce brute-force / log spam.
|
||||||
// 5 attempts per minute per IP, burst 10.
|
auth.POST("/login", middleware.RateLimitByIPDynamic(
|
||||||
auth.POST("/login", middleware.RateLimitByIP(5, time.Minute, 10, 15*time.Minute), h.Login)
|
func() int {
|
||||||
|
return cfg.GetIntDefault(config.KeyRateLimitLoginPerMinute, config.DefaultRateLimitLoginPerMinute)
|
||||||
|
},
|
||||||
|
time.Minute,
|
||||||
|
func() int {
|
||||||
|
return cfg.GetIntDefault(config.KeyRateLimitLoginBurst, config.DefaultRateLimitLoginBurst)
|
||||||
|
},
|
||||||
|
15*time.Minute,
|
||||||
|
), h.Login)
|
||||||
|
|
||||||
protected := auth.Group("/")
|
protected := auth.Group("/")
|
||||||
protected.Use(middleware.AuthMiddleware())
|
protected.Use(middleware.AuthMiddleware())
|
||||||
|
|||||||
@@ -1,82 +0,0 @@
|
|||||||
package auth
|
|
||||||
|
|
||||||
import (
|
|
||||||
"ResendIt/internal/security"
|
|
||||||
"ResendIt/internal/user"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestServiceLogin_InvalidUserDoesNotEnumerate(t *testing.T) {
|
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open sqlite: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(&user.User{}); err != nil {
|
|
||||||
t.Fatalf("migrate: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
svc := NewService(NewRepository(db))
|
|
||||||
|
|
||||||
_, err = svc.Login("does-not-exist", "whatever")
|
|
||||||
if err != ErrInvalidCredentials {
|
|
||||||
t.Fatalf("expected ErrInvalidCredentials for missing user, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestServiceLogin_WrongPassword(t *testing.T) {
|
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open sqlite: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(&user.User{}); err != nil {
|
|
||||||
t.Fatalf("migrate: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
hash, err := security.HashPassword("right")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hash: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
u := user.User{Username: "alice", PasswordHash: hash, Role: "user"}
|
|
||||||
if err := db.Create(&u).Error; err != nil {
|
|
||||||
t.Fatalf("create user: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
svc := NewService(NewRepository(db))
|
|
||||||
_, err = svc.Login("alice", "wrong")
|
|
||||||
if err != ErrInvalidCredentials {
|
|
||||||
t.Fatalf("expected ErrInvalidCredentials for wrong password, got %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestServiceLogin_SuccessReturnsJWT(t *testing.T) {
|
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open sqlite: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(&user.User{}); err != nil {
|
|
||||||
t.Fatalf("migrate: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
hash, err := security.HashPassword("right")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("hash: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
u := user.User{Username: "alice", PasswordHash: hash, Role: "user"}
|
|
||||||
if err := db.Create(&u).Error; err != nil {
|
|
||||||
t.Fatalf("create user: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
svc := NewService(NewRepository(db))
|
|
||||||
token, err := svc.Login("alice", "right")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("expected success, got error: %v", err)
|
|
||||||
}
|
|
||||||
if token == "" {
|
|
||||||
t.Fatalf("expected non-empty jwt token")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
7
internal/buildinfo/buildinfo.go
Normal file
7
internal/buildinfo/buildinfo.go
Normal file
@@ -0,0 +1,7 @@
|
|||||||
|
package buildinfo
|
||||||
|
|
||||||
|
// Commit is the git commit SHA the binary was built from.
|
||||||
|
//
|
||||||
|
// Set at build time via:
|
||||||
|
// -ldflags "-X ResendIt/internal/buildinfo.Commit=<sha>"
|
||||||
|
var Commit = "dev"
|
||||||
23
internal/config/defaults.go
Normal file
23
internal/config/defaults.go
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
const (
|
||||||
|
KeyUploadMaxFileSizeBytes = "upload.max_file_size_bytes"
|
||||||
|
KeyUploadMultiMaxFiles = "upload.multi.max_files"
|
||||||
|
KeyUploadMaxHours = "upload.max_hours"
|
||||||
|
KeyRateLimitLoginPerMinute = "ratelimit.login.per_minute"
|
||||||
|
KeyRateLimitApiPerMinute = "ratelimit.api.per_minute"
|
||||||
|
KeyRateLimitApiBurst = "ratelimit.api.burst"
|
||||||
|
KeyRateLimitLoginBurst = "ratelimit.login.burst"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Defaults (used when DB does not have an override)
|
||||||
|
const (
|
||||||
|
DefaultUploadMaxFileSizeBytes int64 = 10 << 30 // 10 GiB (matches MaxMultipartMemory intent)
|
||||||
|
DefaultUploadMultiMaxFiles = 50
|
||||||
|
DefaultUploadMaxHours = 24 * 7 // 7 days
|
||||||
|
|
||||||
|
DefaultRateLimitLoginPerMinute = 5
|
||||||
|
DefaultRateLimitLoginBurst = 10
|
||||||
|
DefaultRateLimitApiPerMinute = 60
|
||||||
|
DefaultRateLimitApiBurst = 30
|
||||||
|
)
|
||||||
18
internal/config/model.go
Normal file
18
internal/config/model.go
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import "time"
|
||||||
|
|
||||||
|
// ConfigEntry stores runtime-tunable configuration in the database.
|
||||||
|
// Values are stored as strings but helpers exist for ints/bools/durations.
|
||||||
|
//
|
||||||
|
// Example keys:
|
||||||
|
// - upload.max_file_size_bytes
|
||||||
|
// - upload.multi.max_files
|
||||||
|
// - upload.max_hours
|
||||||
|
// - ratelimit.login.per_minute
|
||||||
|
// - ratelimit.api.per_minute
|
||||||
|
type ConfigEntry struct {
|
||||||
|
Key string `gorm:"primaryKey;size:128"`
|
||||||
|
Value string `gorm:"size:2048"`
|
||||||
|
UpdatedAt time.Time
|
||||||
|
}
|
||||||
39
internal/config/repository.go
Normal file
39
internal/config/repository.go
Normal file
@@ -0,0 +1,39 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import "gorm.io/gorm"
|
||||||
|
|
||||||
|
type Repository struct {
|
||||||
|
db *gorm.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewRepository(db *gorm.DB) *Repository {
|
||||||
|
return &Repository{db: db}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) Get(key string) (*ConfigEntry, error) {
|
||||||
|
var e ConfigEntry
|
||||||
|
if err := r.db.First(&e, "key = ?", key).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return &e, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) Upsert(key, value string) error {
|
||||||
|
// Try update first, then insert if nothing updated.
|
||||||
|
res := r.db.Model(&ConfigEntry{}).Where("key = ?", key).Update("value", value)
|
||||||
|
if res.Error != nil {
|
||||||
|
return res.Error
|
||||||
|
}
|
||||||
|
if res.RowsAffected > 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return r.db.Create(&ConfigEntry{Key: key, Value: value}).Error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r *Repository) List() ([]ConfigEntry, error) {
|
||||||
|
var entries []ConfigEntry
|
||||||
|
if err := r.db.Order("key asc").Find(&entries).Error; err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
125
internal/config/service.go
Normal file
125
internal/config/service.go
Normal file
@@ -0,0 +1,125 @@
|
|||||||
|
package config
|
||||||
|
|
||||||
|
import (
|
||||||
|
"errors"
|
||||||
|
"strconv"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"gorm.io/gorm"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Service struct {
|
||||||
|
repo *Repository
|
||||||
|
|
||||||
|
// Small in-memory cache to avoid hitting the DB on every request.
|
||||||
|
// Updated on SetString; lazy-filled on first Get.
|
||||||
|
mu sync.RWMutex
|
||||||
|
cache map[string]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(r *Repository) *Service {
|
||||||
|
return &Service{repo: r, cache: make(map[string]string)}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) List() ([]ConfigEntry, error) {
|
||||||
|
entries, err := s.repo.List()
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
// refresh cache snapshot
|
||||||
|
s.mu.Lock()
|
||||||
|
for _, e := range entries {
|
||||||
|
s.cache[e.Key] = e.Value
|
||||||
|
}
|
||||||
|
s.mu.Unlock()
|
||||||
|
return entries, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) SetString(key, value string) error {
|
||||||
|
if err := s.repo.Upsert(key, value); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
s.mu.Lock()
|
||||||
|
s.cache[key] = value
|
||||||
|
s.mu.Unlock()
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetStringDefault(key, def string) string {
|
||||||
|
s.mu.RLock()
|
||||||
|
v, ok := s.cache[key]
|
||||||
|
s.mu.RUnlock()
|
||||||
|
if ok {
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
e, err := s.repo.Get(key)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
|
||||||
|
s.mu.Lock()
|
||||||
|
s.cache[key] = e.Value
|
||||||
|
s.mu.Unlock()
|
||||||
|
|
||||||
|
if e.Value == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return e.Value
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetIntDefault(key string, def int) int {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetInt64Default(key string, def int64) int64 {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.ParseInt(v, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return n
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetBoolDefault(key string, def bool) bool {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
b, err := strconv.ParseBool(v)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return b
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Service) GetDurationSecondsDefault(key string, def time.Duration) time.Duration {
|
||||||
|
v := s.GetStringDefault(key, "")
|
||||||
|
if v == "" {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil {
|
||||||
|
return def
|
||||||
|
}
|
||||||
|
return time.Duration(n) * time.Second
|
||||||
|
}
|
||||||
|
|
||||||
|
func IsNotFound(err error) bool {
|
||||||
|
return errors.Is(err, gorm.ErrRecordNotFound)
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package file
|
package file
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/config"
|
||||||
"ResendIt/internal/util"
|
"ResendIt/internal/util"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
@@ -12,11 +13,19 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
service *Service
|
service *Service
|
||||||
|
configService ConfigService
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(s *Service) *Handler {
|
// ConfigService is the small interface we need from the config package.
|
||||||
return &Handler{service: s}
|
// Keeping it as an interface avoids import cycles and keeps file.Handler easy to test.
|
||||||
|
type ConfigService interface {
|
||||||
|
GetIntDefault(key string, def int) int
|
||||||
|
GetInt64Default(key string, def int64) int64
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(s *Service, cfg ConfigService) *Handler {
|
||||||
|
return &Handler{service: s, configService: cfg}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Upload(c *gin.Context) {
|
func (h *Handler) Upload(c *gin.Context) {
|
||||||
@@ -32,6 +41,12 @@ func (h *Handler) Upload(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
maxSize := h.configService.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
if file.Size > maxSize {
|
||||||
|
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "file too large"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
f, err := file.Open()
|
f, err := file.Open()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot open file"})
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "cannot open file"})
|
||||||
@@ -46,6 +61,10 @@ func (h *Handler) Upload(c *gin.Context) {
|
|||||||
if err != nil || hours <= 0 {
|
if err != nil || hours <= 0 {
|
||||||
hours = 24 // default
|
hours = 24 // default
|
||||||
}
|
}
|
||||||
|
maxHours := h.configService.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours)
|
||||||
|
if hours > maxHours {
|
||||||
|
hours = maxHours
|
||||||
|
}
|
||||||
|
|
||||||
duration := time.Duration(hours) * time.Hour
|
duration := time.Duration(hours) * time.Hour
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package file
|
package file
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/config"
|
||||||
"net/http"
|
"net/http"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
@@ -26,11 +27,27 @@ func (h *Handler) UploadMulti(c *gin.Context) {
|
|||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "missing files"})
|
c.JSON(http.StatusBadRequest, gin.H{"error": "missing files"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if len(files) > 50 {
|
maxFiles := h.configService.GetIntDefault(config.KeyUploadMultiMaxFiles, config.DefaultUploadMultiMaxFiles)
|
||||||
c.JSON(http.StatusBadRequest, gin.H{"error": "too many files (max 50)"})
|
if len(files) > maxFiles {
|
||||||
|
c.JSON(http.StatusBadRequest, gin.H{"error": "too many files"})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
maxSize := h.configService.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
var total int64
|
||||||
|
for _, fh := range files {
|
||||||
|
if fh.Size > maxSize {
|
||||||
|
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "file too large"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
total += fh.Size
|
||||||
|
if total > maxSize {
|
||||||
|
// crude guard against huge bundles; you can add a separate config later.
|
||||||
|
c.JSON(http.StatusRequestEntityTooLarge, gin.H{"error": "bundle too large"})
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
once := c.PostForm("once") == "true"
|
once := c.PostForm("once") == "true"
|
||||||
|
|
||||||
durationStr := c.PostForm("duration")
|
durationStr := c.PostForm("duration")
|
||||||
@@ -38,6 +55,10 @@ func (h *Handler) UploadMulti(c *gin.Context) {
|
|||||||
if err != nil || hours <= 0 {
|
if err != nil || hours <= 0 {
|
||||||
hours = 24
|
hours = 24
|
||||||
}
|
}
|
||||||
|
maxHours := h.configService.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours)
|
||||||
|
if hours > maxHours {
|
||||||
|
hours = maxHours
|
||||||
|
}
|
||||||
duration := time.Duration(hours) * time.Hour
|
duration := time.Duration(hours) * time.Hour
|
||||||
|
|
||||||
record, err := h.service.UploadBundle(files, once, duration)
|
record, err := h.service.UploadBundle(files, once, duration)
|
||||||
|
|||||||
@@ -1,22 +0,0 @@
|
|||||||
package security
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestHashAndCheckPassword(t *testing.T) {
|
|
||||||
pw := "correct horse battery staple"
|
|
||||||
|
|
||||||
hash, err := HashPassword(pw)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("HashPassword returned error: %v", err)
|
|
||||||
}
|
|
||||||
if hash == "" {
|
|
||||||
t.Fatalf("expected non-empty hash")
|
|
||||||
}
|
|
||||||
|
|
||||||
if !CheckPassword(pw, hash) {
|
|
||||||
t.Fatalf("expected CheckPassword to succeed for correct password")
|
|
||||||
}
|
|
||||||
if CheckPassword("wrong", hash) {
|
|
||||||
t.Fatalf("expected CheckPassword to fail for wrong password")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
package util
|
|
||||||
|
|
||||||
import "testing"
|
|
||||||
|
|
||||||
func TestHumanSize(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
in int64
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{0, "0 B"},
|
|
||||||
{1, "1 B"},
|
|
||||||
{1023, "1023 B"},
|
|
||||||
{1024, "1.0 KB"},
|
|
||||||
{1024 * 1024, "1.0 MB"},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
if got := HumanSize(tt.in); got != tt.want {
|
|
||||||
t.Fatalf("HumanSize(%d) = %q, want %q", tt.in, got, tt.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSafeFilename(t *testing.T) {
|
|
||||||
if got := SafeFilename(" hello.txt "); got != "hello.txt" {
|
|
||||||
t.Fatalf("expected trimmed filename, got %q", got)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Strips control characters, quotes, and backslashes.
|
|
||||||
in := "a\n\rb\t\"c\\d"
|
|
||||||
got := SafeFilename(in)
|
|
||||||
if got != "abcd" {
|
|
||||||
t.Fatalf("SafeFilename(%q) = %q, want %q", in, got, "abcd")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Empty after sanitization becomes default.
|
|
||||||
if got := SafeFilename("\n\r\t"); got != "file" {
|
|
||||||
t.Fatalf("expected default filename, got %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
151
internal/web/config.go
Normal file
151
internal/web/config.go
Normal file
@@ -0,0 +1,151 @@
|
|||||||
|
package web
|
||||||
|
|
||||||
|
import (
|
||||||
|
"ResendIt/internal/config"
|
||||||
|
"net/http"
|
||||||
|
"strconv"
|
||||||
|
|
||||||
|
"github.com/gin-gonic/gin"
|
||||||
|
)
|
||||||
|
|
||||||
|
type ConfigPageData struct {
|
||||||
|
Success bool
|
||||||
|
Error string
|
||||||
|
|
||||||
|
UploadMaxFileSizeMB int64
|
||||||
|
UploadMultiMaxFiles int
|
||||||
|
UploadMaxHours int
|
||||||
|
|
||||||
|
RateLimitLoginPerMinute int
|
||||||
|
RateLimitLoginBurst int
|
||||||
|
RateLimitApiPerMinute int
|
||||||
|
RateLimitApiBurst int
|
||||||
|
}
|
||||||
|
|
||||||
|
// ConfigPage renders a modular admin config screen.
|
||||||
|
func (h *Handler) ConfigPage(c *gin.Context) {
|
||||||
|
cfg := h.configService
|
||||||
|
|
||||||
|
maxBytes := cfg.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
data := ConfigPageData{
|
||||||
|
Success: c.Query("saved") == "1",
|
||||||
|
UploadMaxFileSizeMB: maxBytes / (1024 * 1024),
|
||||||
|
UploadMultiMaxFiles: cfg.GetIntDefault(config.KeyUploadMultiMaxFiles, config.DefaultUploadMultiMaxFiles),
|
||||||
|
UploadMaxHours: cfg.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours),
|
||||||
|
RateLimitLoginPerMinute: cfg.GetIntDefault(config.KeyRateLimitLoginPerMinute, config.DefaultRateLimitLoginPerMinute),
|
||||||
|
RateLimitLoginBurst: cfg.GetIntDefault(config.KeyRateLimitLoginBurst, config.DefaultRateLimitLoginBurst),
|
||||||
|
RateLimitApiPerMinute: cfg.GetIntDefault(config.KeyRateLimitApiPerMinute, config.DefaultRateLimitApiPerMinute),
|
||||||
|
RateLimitApiBurst: cfg.GetIntDefault(config.KeyRateLimitApiBurst, config.DefaultRateLimitApiBurst),
|
||||||
|
}
|
||||||
|
|
||||||
|
c.HTML(http.StatusOK, "config.html", data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) ConfigSave(c *gin.Context) {
|
||||||
|
cfg := h.configService
|
||||||
|
|
||||||
|
// Parse + validate.
|
||||||
|
parseInt := func(name string, min, max int) (int, error) {
|
||||||
|
v := c.PostForm(name)
|
||||||
|
n, err := strconv.Atoi(v)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if n < min {
|
||||||
|
n = min
|
||||||
|
}
|
||||||
|
if max > 0 && n > max {
|
||||||
|
n = max
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
parseInt64 := func(name string, min int64, max int64) (int64, error) {
|
||||||
|
v := c.PostForm(name)
|
||||||
|
n, err := strconv.ParseInt(v, 10, 64)
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if n < min {
|
||||||
|
n = min
|
||||||
|
}
|
||||||
|
if max > 0 && n > max {
|
||||||
|
n = max
|
||||||
|
}
|
||||||
|
return n, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
maxMB, err := parseInt64("upload_max_file_size_mb", 1, 1024*1024)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid max file size")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxFiles, err := parseInt("upload_multi_max_files", 1, 500)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid max files")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
maxHours, err := parseInt("upload_max_hours", 1, 24*365)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid max hours")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Rate limits: stored, but not applied dynamically yet.
|
||||||
|
loginPerMin, err := parseInt("ratelimit_login_per_minute", 1, 10000)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid login rate")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
loginBurst, err := parseInt("ratelimit_login_burst", 1, 10000)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid login burst")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
apiPerMin, err := parseInt("ratelimit_api_per_minute", 1, 100000)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid api rate")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
apiBurst, err := parseInt("ratelimit_api_burst", 1, 100000)
|
||||||
|
if err != nil {
|
||||||
|
h.renderConfigError(c, "invalid api burst")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// Persist.
|
||||||
|
if err := cfg.SetString(config.KeyUploadMaxFileSizeBytes, strconv.FormatInt(maxMB*1024*1024, 10)); err != nil {
|
||||||
|
h.renderConfigError(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := cfg.SetString(config.KeyUploadMultiMaxFiles, strconv.Itoa(maxFiles)); err != nil {
|
||||||
|
h.renderConfigError(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err := cfg.SetString(config.KeyUploadMaxHours, strconv.Itoa(maxHours)); err != nil {
|
||||||
|
h.renderConfigError(c, err.Error())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitLoginPerMinute, strconv.Itoa(loginPerMin))
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitLoginBurst, strconv.Itoa(loginBurst))
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitApiPerMinute, strconv.Itoa(apiPerMin))
|
||||||
|
_ = cfg.SetString(config.KeyRateLimitApiBurst, strconv.Itoa(apiBurst))
|
||||||
|
|
||||||
|
c.Redirect(http.StatusFound, "/config?saved=1")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) renderConfigError(c *gin.Context, msg string) {
|
||||||
|
maxBytes := h.configService.GetInt64Default(config.KeyUploadMaxFileSizeBytes, config.DefaultUploadMaxFileSizeBytes)
|
||||||
|
data := ConfigPageData{
|
||||||
|
Error: msg,
|
||||||
|
UploadMaxFileSizeMB: maxBytes / (1024 * 1024),
|
||||||
|
UploadMultiMaxFiles: h.configService.GetIntDefault(config.KeyUploadMultiMaxFiles, config.DefaultUploadMultiMaxFiles),
|
||||||
|
UploadMaxHours: h.configService.GetIntDefault(config.KeyUploadMaxHours, config.DefaultUploadMaxHours),
|
||||||
|
RateLimitLoginPerMinute: h.configService.GetIntDefault(config.KeyRateLimitLoginPerMinute, config.DefaultRateLimitLoginPerMinute),
|
||||||
|
RateLimitLoginBurst: h.configService.GetIntDefault(config.KeyRateLimitLoginBurst, config.DefaultRateLimitLoginBurst),
|
||||||
|
RateLimitApiPerMinute: h.configService.GetIntDefault(config.KeyRateLimitApiPerMinute, config.DefaultRateLimitApiPerMinute),
|
||||||
|
RateLimitApiBurst: h.configService.GetIntDefault(config.KeyRateLimitApiBurst, config.DefaultRateLimitApiBurst),
|
||||||
|
}
|
||||||
|
c.HTML(http.StatusBadRequest, "config.html", data)
|
||||||
|
}
|
||||||
@@ -1,6 +1,7 @@
|
|||||||
package web
|
package web
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"ResendIt/internal/buildinfo"
|
||||||
"ResendIt/internal/file"
|
"ResendIt/internal/file"
|
||||||
"os"
|
"os"
|
||||||
"strconv"
|
"strconv"
|
||||||
@@ -9,12 +10,21 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
fileService *file.Service
|
fileService *file.Service
|
||||||
|
configService ConfigService
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewHandler(fileService *file.Service) *Handler {
|
// ConfigService is the small interface needed by the web layer.
|
||||||
|
type ConfigService interface {
|
||||||
|
GetIntDefault(key string, def int) int
|
||||||
|
GetInt64Default(key string, def int64) int64
|
||||||
|
SetString(key, value string) error
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewHandler(fileService *file.Service, cfg ConfigService) *Handler {
|
||||||
return &Handler{
|
return &Handler{
|
||||||
fileService: fileService,
|
fileService: fileService,
|
||||||
|
configService: cfg,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,9 +109,10 @@ func (h *Handler) AdminPage(c *gin.Context) {
|
|||||||
totalPages := (totalCount + limit - 1) / limit
|
totalPages := (totalCount + limit - 1) / limit
|
||||||
|
|
||||||
c.HTML(200, "admin.html", gin.H{
|
c.HTML(200, "admin.html", gin.H{
|
||||||
"Files": adminFiles,
|
"Files": adminFiles,
|
||||||
"Page": page,
|
"Page": page,
|
||||||
"TotalPages": totalPages,
|
"TotalPages": totalPages,
|
||||||
|
"BuildCommit": buildinfo.Commit,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,6 +20,8 @@ func RegisterRoutes(r *gin.Engine, h *Handler, userService *user.Service) {
|
|||||||
adminRoutes.Use(user.ForcePasswordChangeMiddleware(userService))
|
adminRoutes.Use(user.ForcePasswordChangeMiddleware(userService))
|
||||||
|
|
||||||
adminRoutes.GET("/admin", h.AdminPage)
|
adminRoutes.GET("/admin", h.AdminPage)
|
||||||
|
adminRoutes.GET("/config", h.ConfigPage)
|
||||||
|
adminRoutes.POST("/config", h.ConfigSave)
|
||||||
adminRoutes.GET("/logout", h.Logout)
|
adminRoutes.GET("/logout", h.Logout)
|
||||||
adminRoutes.GET("/change-password", h.ChangePasswordPage)
|
adminRoutes.GET("/change-password", h.ChangePasswordPage)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -113,6 +113,7 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="flex flex-col items-end gap-2">
|
<div class="flex flex-col items-end gap-2">
|
||||||
<a href="/" class="nav-link">← BACK_TO_UPLOADER</a>
|
<a href="/" class="nav-link">← BACK_TO_UPLOADER</a>
|
||||||
|
<a href="/config" class="nav-link">CONFIG_MODULE</a>
|
||||||
<a href="/logout" class="nav-link text-red-600">LOGOUT_SESSION</a>
|
<a href="/logout" class="nav-link text-red-600">LOGOUT_SESSION</a>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@@ -208,6 +209,9 @@
|
|||||||
<div class="text-[12px] font-black uppercase">
|
<div class="text-[12px] font-black uppercase">
|
||||||
Data_Density: {{len .Files}} records | Page: {{.Page}}/{{.TotalPages}}
|
Data_Density: {{len .Files}} records | Page: {{.Page}}/{{.TotalPages}}
|
||||||
</div>
|
</div>
|
||||||
|
<div class="text-[11px] font-black uppercase text-gray-600">
|
||||||
|
Build_Commit: {{.BuildCommit}}
|
||||||
|
</div>
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
256
templates/config.html
Normal file
256
templates/config.html
Normal file
@@ -0,0 +1,256 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Config Module</title>
|
||||||
|
<script src="https://cdn.tailwindcss.com"></script>
|
||||||
|
<link rel="icon" type="image/x-icon" href="/static/favicon.ico">
|
||||||
|
|
||||||
|
<style>
|
||||||
|
* { border-radius: 0 !important; }
|
||||||
|
body {
|
||||||
|
font-family: ui-monospace, 'Cascadia Code', 'Source Code Pro', monospace;
|
||||||
|
background: #fff;
|
||||||
|
color: #000;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.box { border: 3px solid #000; background: #fff; padding: 20px; }
|
||||||
|
|
||||||
|
.section-title {
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
border-bottom: 3px solid #000;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
padding-bottom: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.row {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 300px 1fr;
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
label {
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
input {
|
||||||
|
border: 2px solid #000;
|
||||||
|
padding: 6px 8px;
|
||||||
|
font-size: 13px;
|
||||||
|
width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hint {
|
||||||
|
font-size: 11px;
|
||||||
|
font-style: italic;
|
||||||
|
margin-top: 4px;
|
||||||
|
border-left: 4px solid #000;
|
||||||
|
padding-left: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button, .button {
|
||||||
|
border: 2px solid #000;
|
||||||
|
background: #fff;
|
||||||
|
padding: 6px 12px;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
box-shadow: 3px 3px 0px #000;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover, .button:hover {
|
||||||
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
box-shadow: none;
|
||||||
|
transform: translate(2px, 2px);
|
||||||
|
}
|
||||||
|
|
||||||
|
button:active {
|
||||||
|
background: #ff0000;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link {
|
||||||
|
font-weight: 900;
|
||||||
|
text-decoration: underline;
|
||||||
|
text-transform: uppercase;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-link:hover {
|
||||||
|
background: #000;
|
||||||
|
color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ok {
|
||||||
|
border: 3px solid #000;
|
||||||
|
background: #00ff00;
|
||||||
|
padding: 10px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
|
||||||
|
.err {
|
||||||
|
border: 3px solid #000;
|
||||||
|
background: #ff0000;
|
||||||
|
color: #fff;
|
||||||
|
padding: 10px;
|
||||||
|
font-weight: 900;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<div class="max-w-4xl mx-auto">
|
||||||
|
|
||||||
|
<!-- HEADER -->
|
||||||
|
<header class="mb-6 border-b-8 border-black pb-4 flex justify-between items-start">
|
||||||
|
<h1 class="text-4xl font-black uppercase tracking-tighter leading-none">
|
||||||
|
Config_Settings
|
||||||
|
</h1>
|
||||||
|
|
||||||
|
<div class="flex flex-col items-end gap-2">
|
||||||
|
<a href="/admin" class="nav-link">Admin_Panel</a>
|
||||||
|
<a href="/config" class="nav-link">Reload_Config</a>
|
||||||
|
<a href="/logout" class="nav-link text-red-600">Logout</a>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- STATUS -->
|
||||||
|
{{if .Success}}
|
||||||
|
<div class="ok mb-4">CONFIG_SAVED_SUCCESSFULLY</div>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
{{if .Error}}
|
||||||
|
<div class="err mb-4">{{.Error}}</div>
|
||||||
|
{{end}}
|
||||||
|
|
||||||
|
<form method="POST" action="/config">
|
||||||
|
|
||||||
|
<!-- UPLOAD SETTINGS -->
|
||||||
|
<div class="box mb-6">
|
||||||
|
<div class="section-title">Upload_Control</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Max_File_Size_MB</label>
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<div class="flex gap-2 items-center">
|
||||||
|
<input id="fileSizeMB" type="number" min="1" name="upload_max_file_size_mb" value="{{.UploadMaxFileSizeMB}}">
|
||||||
|
|
||||||
|
<input id="fileSizeGB" type="text" readonly placeholder="GB"
|
||||||
|
class="w-24 bg-gray-100 cursor-not-allowed">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="hint">Hard limit enforced by upload endpoints</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Multi_Upload_Limit</label>
|
||||||
|
<div>
|
||||||
|
<input type="number" min="1" name="upload_multi_max_files" value="{{.UploadMultiMaxFiles}}">
|
||||||
|
<div class="hint">Max files per multi-upload request</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Max_Expiry_Hours</label>
|
||||||
|
<div class="flex flex-col gap-1">
|
||||||
|
<div class="flex gap-2 items-center">
|
||||||
|
<input id="hoursInput" type="number" min="1" name="upload_max_hours" value="{{.UploadMaxHours}}">
|
||||||
|
|
||||||
|
<input id="daysOutput" type="text" readonly placeholder="Days" class="w-24 bg-gray-100 cursor-not-allowed">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="hint">User duration capped to this value</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- RATE LIMITS -->
|
||||||
|
<div class="box mb-6">
|
||||||
|
<div class="section-title">Rate_Limits_(Static)</div>
|
||||||
|
|
||||||
|
<div class="hint mb-4">
|
||||||
|
Changes require server restart to take effect
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Login_Per_Minute</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_login_per_minute" value="{{.RateLimitLoginPerMinute}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>Login_Burst</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_login_burst" value="{{.RateLimitLoginBurst}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>API_Per_Minute</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_api_per_minute" value="{{.RateLimitApiPerMinute}}">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row">
|
||||||
|
<label>API_Burst</label>
|
||||||
|
<input type="number" min="1" name="ratelimit_api_burst" value="{{.RateLimitApiBurst}}">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- ACTIONS -->
|
||||||
|
<div class="flex justify-between items-center border-t-8 border-black pt-4">
|
||||||
|
<button type="submit">SAVE</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</form>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<a href="/change-password" class="fixed bottom-1 left-1 text-[10px] underline">
|
||||||
|
CHANGE_PASSWORD
|
||||||
|
</a>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function formatNumber(num) {
|
||||||
|
return parseFloat(num.toFixed(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateConversions() {
|
||||||
|
const mb = parseFloat(document.getElementById('fileSizeMB')?.value);
|
||||||
|
const gbField = document.getElementById('fileSizeGB');
|
||||||
|
|
||||||
|
if (!isNaN(mb) && gbField) {
|
||||||
|
gbField.value = formatNumber(mb / 1024) + " GB";
|
||||||
|
} else if (gbField) {
|
||||||
|
gbField.value = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
const hours = parseFloat(document.getElementById('hoursInput')?.value);
|
||||||
|
const daysField = document.getElementById('daysOutput');
|
||||||
|
|
||||||
|
if (!isNaN(hours) && daysField) {
|
||||||
|
daysField.value = formatNumber(hours / 24) + " days";
|
||||||
|
} else if (daysField) {
|
||||||
|
daysField.value = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Run on load
|
||||||
|
window.addEventListener('DOMContentLoaded', updateConversions);
|
||||||
|
|
||||||
|
// Listen for changes
|
||||||
|
document.addEventListener('input', updateConversions);
|
||||||
|
</script>
|
||||||
|
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Reference in New Issue
Block a user