abuse

package
v0.0.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 5 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

http-keystone Abuse Middleware

Docs Status

A smart behavioral firewall for Echo v5. http-keystone/abuse tracks client reputation using a Heat scoring system to identify and neutralize scrapers, scanners, and malicious actors.

→ View API eference


How It Works:

Unlike standard rate-limiters that reset every minute, think of this like a heat meter. While normal limits reset quickly, this middleware remembers a user's actions over time. Every bad request adds points that only disappear after the user stops for a while.

  1. Passive Monitoring: Every request is checked against a list of Rules.
  2. Penalty Scoring: If a client hits a sensitive path (e.g., /.env or /phpmyadmin), their "Heat" score increases.
  3. Tarpit delay (Optional): As the score approaches the threshold, the middleware artificially delays responses, wasting the attacker's time and resources.
  4. The Block: Once the Threshold is met, all further requests are rejected with a 403 Forbidden until the Cooldown period expires.

Installation

go get github.com/its-ernest/http-keystone@latest

Then import github.com/its-ernest/http-keystone/abuse.


Basic Usage

package main

import (
	"time"
	"github.com/labstack/echo/v5"
	"github.com/its-ernest/http-keystone/abuse"
	"github.com/its-ernest/http-keystone/store"
)

func main() {
	e := echo.New()

	// 1. Setup a Counter store (separate from Cache store for performance)
	abuseStore := store.NewMemoryCounter()

	// 2. Configure the Firewall
	e.Use(abuse.New(abuse.Config{
		Store:     abuseStore,
		Threshold: 100,        // Max heat before a total ban
		Cooldown:  1 * time.Hour, // Until forgetting about a ban
		EnableDelay: true,     // Slow down warm IPs
		Rules: []abuse.Rule{
			{Path: "/.env", Score: 100},       // Instant ban
			{Path: "/.git*", Score: 100},      // Instant ban
			{Path: "/wp-admin*", Score: 50},    // Two hits and the IP is banned
			{Path: "/api/v1/login", Method: "POST", Score: 5},  // Penalize brute-force attempts
		},
	}))

	e.Start(":8080")
}

Distributed tracking with Redis

store.RedisCounter implements store.Counter and stores scores in Redis, so every application instance sees the same heat for a client. Increment runs INCRBY and PEXPIRE in one Lua script, making each update atomic: no lost increments and no counter left without a cooldown TTL.

redisCounter := store.NewRedisCounter("localhost:6379")
defer redisCounter.Close()

e.Use(abuse.New(abuse.Config{
	Store:     redisCounter,
	Threshold: 100,
	Cooldown:  time.Hour,
	Rules: []abuse.Rule{
		{Path: "/.env", Score: 100},
	},
}))

Use store.NewRedisCounterWithOptions(store.RedisStoreOptions{...}) to set a password, database, or pool sizes, or store.NewRedisCounterWithClient(client) to share one *redis.Client with store.NewRedisStore. A counter created with a borrowed client does not close it.

Keys are written exactly as the middleware builds them (for example abuse:heat:<client-ip>), so services sharing one Redis instance must use compatible rules and thresholds.


Configuration Options

Field Type Default Description
Store store.Counter Required Atomic counter backend (Memory or Redis).
Threshold int 100 The score at which a client is fully blocked. <= 0 uses the default.
Rules []Rule nil List of paths and their associated penalty scores. Copied by New.
Cooldown time.Duration 30m Time before a client's heat starts to reset. <= 0 uses the default.
EnableDelay bool false If true, applies a linear delay as heat rises.
ErrorHandler func(*echo.Context, int) Default Custom logic for when a user is blocked.

Zero config is safe. abuse.New(Config{Store: counter}) uses Threshold: 100, Cooldown: 30m, and the default error handler, so it will not reject every request. Rules are copied, so mutating your slice after New has no effect.


delay effect

When EnableDelay is active, the middleware calculates a sleep duration based on the current score: $$Delay = CurrentScore \times 10ms$$

If a user has 80 points of heat, every request they make will be artificially slowed down by 800ms. This makes your API an expensive and frustrating target for automated crawlers without affecting legitimate users.


  • Order Matters: Place this middleware above your Logger and above your Cache. There is no point in logging or caching a request from a known malicious actor.
  • Real IP: Ensure your echo.IPExtractor is configured correctly if you are running behind Nginx, Cloudflare, or AWS ALB.
  • Multi-instance deployments: Use store.NewRedisCounter (or share a *redis.Client with NewRedisCounterWithClient) so heat scores are consistent across replicas. MemoryCounter is per-process.
  • Gradual Penalties: Use small scores (2-5) for general API endpoints to catch high scrapers, and large scores (50-100) for sensitive system files.

Documentation

Overview

Package abuse provides behavioral analysis middleware for Echo v5. It tracks client reputation via a scoring system to mitigate scrapers and scanners.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultConfig = Config{
	Threshold: 100,
	Cooldown:  30 * time.Minute,
	ErrorHandler: func(c *echo.Context, score int) error {
		return echo.NewHTTPError(http.StatusForbidden, "Access denied due to suspicious activity")
	},
}

DefaultConfig provides the standard settings for abuse detection middleware.

Functions

func New

func New(config Config) echo.MiddlewareFunc

New returns an Echo middleware that monitors and limits abusive behavior. It should be placed early in the middleware stack to protect downstream resources.

Example
package main

import (
	"github.com/its-ernest/http-keystone/abuse"
	"github.com/labstack/echo/v5"
)

func main() {
	e := echo.New()

	// Instant-ban on sensitive files, warn on API spam
	e.Use(abuse.New(abuse.Config{
		Threshold: 100,
		Rules: []abuse.Rule{
			// immediate ban for ANY attempt on .env
			{Path: "/.env", Score: 100},

			// heavy score only for POST requests to login (brute force protection)
			{Path: "/api/v1/login", Method: "POST", Score: 20},

			// light score for general API exploration
			{Path: "/api/v1/*", Method: "GET", Score: 2},
		},
	}))
}

Types

type Config

type Config struct {
	Store store.Counter
	// Threshold is the heat score at which requests are rejected.
	// Values <= 0 fall back to DefaultConfig.Threshold (100) so a zero
	// Config can never block every request.
	Threshold int
	Rules     []Rule
	// Cooldown is how long heat is remembered. Values <= 0 fall back to
	// DefaultConfig.Cooldown (30 minutes).
	Cooldown time.Duration
	// EnableDelay adds latency to suspicious requests instead of a hard block.
	EnableDelay  bool
	ErrorHandler func(c *echo.Context, score int) error
}

Config defines the settings for the abuse detection middleware.

type Rule

type Rule struct {
	// Path is the URL path to match. It supports exact matches and a
	// trailing "*" wildcard on a path-segment boundary; Echo's router is
	// not involved. Matching is case-sensitive and ignores query strings.
	Path string

	// Method is the HTTP method to match (GET, POST, etc.). Empty means match all.
	Method string

	// Score is the amount of *heat* to add when this rule matches
	Score int
}

Rule defines the "heat" points added for specific path patterns. Path supports exact matches (e.g., "/.env") and a trailing "*" wildcard on a path-segment boundary: "/admin*" matches "/admin" and "/admin/config" but not "/administrator".

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL