echo

package module
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Oct 16, 2026 License: MIT Imports: 14 Imported by: 0

README

Guard Core


Echo middleware adapter for [guard-core-go](https://github.com/Guard-Core/guard-core-go). Translates `echo.Context` into the guardcore request surface, runs the engine, and translates verdicts to exact Echo responses (status, headers, body, then stop the chain). Works with any `echo.Echo` or `echo.Group` chain via `e.Use`.

Release tag Docs Release License CI CodeQL

PagesBuildDeployment DocsUpdate last-commit

Echo

Website · Docs · Playground · Dashboard · Discord


Ecosystem

Guard Core is the Python engine. Framework adapters are thin wrappers that translate native request/response types into Guard Core's protocols. The telemetry agents ship security events and metrics to the monitoring backend. Parallel engine implementations exist for Go, PHP, TypeScript (on npm), and Rust (on crates.io) - all ports of the same reference semantics, conformance-tested against the shared adversarial corpus.

Python

Package Role PyPI
guard-core Framework-agnostic security engine PyPI
guard-agent Telemetry agent PyPI
fastapi-guard FastAPI / Starlette adapter PyPI
flaskapi-guard Flask adapter PyPI
djapi-guard Django adapter PyPI
tornadoapi-guard Tornado adapter PyPI

Go

Go modules published via GitHub releases. Production-ready.

Package Role Release
guard-core-go Go engine release
nethttp-guard net/http adapter release
gin-guard Gin adapter release
echo-guard Echo (v4) adapter release
fiber-guard Fiber (v3) adapter release
guard-agent-go Telemetry agent release

PHP

Published on Packagist under the rennf93 vendor. Production-ready.

Package Role Packagist
guard-core-php PHP engine Packagist
laravel-guard Laravel adapter Packagist
symfony-guard Symfony adapter Packagist
psr15-guard PSR-15 adapter Packagist
slim-guard Slim 4 adapter Packagist
guard-agent-php Telemetry agent Packagist

TypeScript / JavaScript

Published under the @guardcore npm scope; source in the guard-core-ts monorepo. Production-ready.

Package Role npm
@guardcore/core Core engine
@guardcore/express Express adapter npm
@guardcore/nestjs NestJS adapter npm
@guardcore/fastify Fastify adapter npm
@guardcore/hono Hono (edge) adapter npm
guardagent Telemetry agent npm

Rust

Published on crates.io. Production-ready.

Package Role crates.io
guard-core-engine Core engine crate crates.io
guard-core-rs Facade crate (consumer entry point) crates.io
actix-guard-rs Actix Web adapter crates.io
axum-guard-rs Axum adapter crates.io
tower-guard-rs Tower adapter crates.io
rocket-guard-rs Rocket adapter crates.io
guard-agent-rs Telemetry agent crates.io

AI Coding Agents

Package Role PyPI
guard-core-mcp MCP server: config validation, docs search, detection sandbox PyPI

Features

  • The full guard-core-go engine pipeline over Echo (v4) requests: rate limiting, IP policy, payload inspection across 19 attack categories, auto-banning
  • Security headers and behavioral response rules applied on the pass-through path
  • Bounded body buffering with replay for downstream handlers
  • Fail-closed on engine malfunction - a broken engine never turns into an open gate

Documentation

📚 Documentation - full technical documentation for this package.

🛡️ Guard Core - the engine's reference documentation.

🤖 Monitoring Agent Integration - monitor your Guard instance with a monitoring agent.


Install

Released: v1.5.0 on the Go module proxy, flooring the guard-core-go v4.4.0 reference-alignment engine:

go get github.com/rennf93/echo-guard@v1.5.0 github.com/rennf93/guard-core-go/v4@v4.4.0

The package name is echo, which collides with github.com/labstack/echo/v4 (also package echo), so import the adapter with an explicit alias such as guardecho.

Usage

package main

import (
	"log"

	echolib "github.com/labstack/echo/v4"
	guardcore "github.com/rennf93/guard-core-go/v4/guardcore"
	guardecho "github.com/rennf93/echo-guard"
)

func main() {
	cfg := guardcore.DefaultSecurityConfig()
	engine, err := guardcore.NewEngine(cfg)
	if err != nil {
		log.Fatal(err)
	}
	if err := engine.Initialize(); err != nil {
		log.Fatal(err)
	}

	guard, err := guardecho.New(engine)
	if err != nil {
		log.Fatal(err)
	}

	router := echolib.New()
	router.Use(guard)
	router.GET("/", func(c echolib.Context) error {
		return c.String(200, "ok")
	})

	log.Fatal(router.Start(":8080"))
}

Options: guardecho.WithMaxBodyBytes(n) bounds the body bytes the engine scans (default 262144), guardecho.WithLogger(l) swaps the fail-closed logger. Route-level configuration uses engine.Routes.Register plus guardecho.WithRouteID(ctx, id) on the request context (set the wrapped request with c.SetRequest in a middleware registered before the guard).

Every engine SecurityConfig field is reachable through this adapter: global tuning (behavior rules with BehaviorScanResponseBody and the inspect-bytes budget, the geo lifecycle with IPInfoToken/OnGeoEvent, CORS, security headers, custom error bodies) goes through the SecurityConfig you hand to guardcore.NewEngine, per-route detection exclusions and per-route behavior/IP rules through engine.Routes.Register. On every pass-through response the adapter merges Engine.ResponseHeaders() with Engine.CORSResponseHeaders(req) and reports the response (status plus the leading inspect-budget bytes of the body when BehaviorScanResponseBody is on) to Engine.ProcessResponse for the behavioral return rules. See docs/configuration.md.

Echo's middleware contract has no explicit abort call: a verdict is written to c.Response() and the chain stops by not calling next(c). Engine malfunctions fail closed with a 500. Detection covers at most the first MaxBodyBytes of the body; payloads beyond the bound are not scanned, and the full body still reaches your handler untouched.

Development

The middleware consumes the core as a normal module dependency, currently pinned to the guard-core-go master surface (v4.0.5-0.20260926230539-e39ac203568b, the behavior-rules / geo-lifecycle / route-detection-exclusions wave); no replace directive is used or needed. For cross-repo work on the core itself, add a temporary local replace line in your own checkout and drop it before committing.

Integration tests run against real Redis:

REDIS_HOST=127.0.0.1 go test -tags integration ./...

License

MIT

Documentation

Index

Constants

View Source
const DefaultMaxBodyBytes int64 = 262144
View Source
const DefaultStatusPath = "/_guard/status"

DefaultStatusPath is the route path add_status_route registers by default (the reference's /_guard/status).

Variables

This section is empty.

Functions

func AddStatusRoute added in v1.4.0

func AddStatusRoute(app *echolib.Echo, engine *guardcore.Engine, path string) error

AddStatusRoute registers the status handler on the echo instance at path (the empty string picks DefaultStatusPath), mirroring fastapi-guard add_status_route:

if err := echo.AddStatusRoute(app, engine, ""); err != nil { ... }

The method-scoped route answers GET only; other methods fall through to the framework's not-found handling.

func AgentStats added in v1.4.0

func AgentStats(engine *guardcore.Engine) map[string]any

AgentStats mirrors the reference agent_stats property: agentless answers {"enabled": false, "degraded": <degraded>}; a wired handler answers {"enabled": true, "degraded": false} merged with its AgentStats() dict when it provides the stats surface.

func GuardWebSocket added in v1.4.0

func GuardWebSocket(engine *guardcore.Engine, c echolib.Context) *guardcore.WebSocketCloseReason

GuardWebSocket runs the engine's websocket handshake checks over the upgrade request: identity resolution, the fail-secure unknown-address close, the ban check, the is_ip_allowed verdict, the ws rate limit, and the penetration detection pass sharing the HTTP pipeline's suspicious counts. A nil result allows the upgrade; a non-nil reason closes it. A nil engine fails closed with the security-check-failed reason.

func MarkInitialized added in v1.4.0

func MarkInitialized(engine *guardcore.Engine)

MarkInitialized marks the engine initialized without running the startup I/O (the reference mark_initialized: a stack warmed externally tells the middleware to consider itself initialized); a later engine.Initialize becomes a no-op.

func New

func New(engine *guardcore.Engine, opts ...Option) (echolib.MiddlewareFunc, error)

func NewStatusHandler added in v1.4.0

func NewStatusHandler(engine *guardcore.Engine) (echolib.HandlerFunc, error)

NewStatusHandler returns the echo handler serving the engine's initialization status JSON (the reference guard_initialization_status). Mount it behind the security middleware like any other route and exclude it from the checks via the config's path exclusions when it should answer unguarded.

func RefreshCloudIPRanges added in v1.4.0

func RefreshCloudIPRanges(engine *guardcore.Engine) error

RefreshCloudIPRanges refreshes the blocked cloud providers' ranges on demand (the reference refresh_cloud_ip_ranges): with redis configured the refresh runs through the redis-backed store at the configured TTL (the reference cloud_handler.refresh_async), otherwise in memory (the reference cloud_handler.refresh). A config without blocked providers is a no-op, exactly like the reference early return.

func Reset added in v1.4.0

func Reset(engine *guardcore.Engine)

Reset drops the rate limiter's state (the reference reset, which awaits rate_limit_handler.reset): the redis sliding windows and the in-memory fallback counters.

func WebSocketHTTPStatus added in v1.4.0

func WebSocketHTTPStatus(reason *guardcore.WebSocketCloseReason) int

WebSocketHTTPStatus maps a close reason onto the HTTP status an upgrade rejection carries: 503 for the try-again-later security-check failure, 403 for every policy-violation reason, 200 for a nil (allowed) verdict.

func WithRouteID

func WithRouteID(ctx context.Context, routeID string) context.Context

Types

type ComponentStatus added in v1.4.0

type ComponentStatus struct {
	Ready         bool       `json:"ready"`
	LastRefreshed *time.Time `json:"last_refreshed"`
	Entries       int        `json:"entries"`
}

ComponentStatus is one cloud provider's row of the reference cloud_handler.get_status payload.

type InitializationStatus added in v1.4.0

type InitializationStatus struct {
	CloudProviders map[string]ComponentStatus `json:"cloud_providers"`
	GeoIP          map[string]any             `json:"geo_ip"`
	Redis          RedisStatus                `json:"redis"`
}

InitializationStatus is the JSON payload the status route serves.

func GetInitializationStatus added in v1.4.0

func GetInitializationStatus(engine *guardcore.Engine) (InitializationStatus, error)

GetInitializationStatus snapshots the engine's initialization surface (the reference get_initialization_status serving the handler initializer's payload): the cloud-provider table, the geo-ip snapshot and the redis probe. AddStatusRoute serves the same payload over HTTP.

type Option

type Option func(*middleware)

func WithLogger

func WithLogger(logger *log.Logger) Option

func WithMaxBodyBytes

func WithMaxBodyBytes(maxBodyBytes int64) Option

type RedisStatus added in v1.4.0

type RedisStatus struct {
	Enabled bool    `json:"enabled"`
	OK      bool    `json:"ok"`
	Error   *string `json:"error"`
}

RedisStatus is the redis component of the status payload: whether the engine was configured with redis, and - when it was - whether the manager answers a probe right now. ok defaults true when redis is disabled (there is nothing to be down), mirroring the PHP siblings' initialize() snapshot.

Directories

Path Synopsis
examples
advanced_app/cmd/server command
Command server assembles the advanced example: tuned engine config, the engine's route registry, echo route groups, the echo-guard middleware, and graceful shutdown.
Command server assembles the advanced example: tuned engine config, the engine's route registry, echo route groups, the echo-guard middleware, and graceful shutdown.
advanced_app/internal/config
Package config builds the engine's SecurityConfig from environment variables with production-oriented defaults.
Package config builds the engine's SecurityConfig from environment variables with production-oriented defaults.
advanced_app/internal/routes
Package routes holds the HTTP handlers of the advanced example, split by concern the way the Python advanced example splits routers.
Package routes holds the HTTP handlers of the advanced example, split by concern the way the Python advanced example splits routers.
simple_app command
Command simple_app is a minimal guarded Echo server.
Command simple_app is a minimal guarded Echo server.

Jump to

Keyboard shortcuts

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