Skip to content

Commit

Permalink
feat(experimental): adds transaction started and transaction closed h…
Browse files Browse the repository at this point in the history
…ooks to the middleware.

This is specially useful when you want to use transaction data to populate things like logs or spans in a trace enriching the experience and connecting the dots with observability.
  • Loading branch information
jcchavezs committed Feb 7, 2024
1 parent 3c15624 commit c9180ed
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 0 deletions.
6 changes: 6 additions & 0 deletions experimental/plugins/plugintypes/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
package plugintypes

import (
"context"

"github.com/corazawaf/coraza/v3/collection"
"github.com/corazawaf/coraza/v3/debuglog"
"github.com/corazawaf/coraza/v3/types"
Expand Down Expand Up @@ -34,7 +36,11 @@ type TransactionState interface {
// CaptureField captures a field.
CaptureField(idx int, value string)

// LastPhase that was evaluated
LastPhase() types.RulePhase

// Context returns the context of the transaction.
Context() context.Context
}

// TransactionVariables has pointers to all the variables of the transaction
Expand Down
40 changes: 40 additions & 0 deletions http/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (

"github.com/corazawaf/coraza/v3"
"github.com/corazawaf/coraza/v3/experimental"
"github.com/corazawaf/coraza/v3/experimental/plugins/plugintypes"
"github.com/corazawaf/coraza/v3/types"
)

Expand Down Expand Up @@ -113,7 +114,43 @@ func processRequest(tx types.Transaction, req *http.Request) (*types.Interruptio
return tx.ProcessRequestBody()
}

// Options is a set of options for the middleware
type Options struct {
// OnTransactionStarted is called when a new transaction is started. It is useful to
// complement observability signals like metrics, traces and logs by providing additional
// context about the transaction.
OnTransactionStarted func(tx plugintypes.TransactionState)

// OnTransactionClosed is called when a transaction is closed, after the response has been
// written. It is useful to complement observability signals like metrics, traces and logs
// by providing additional context about the transaction and the rules that were matched.
OnTransactionClosed func(tx plugintypes.TransactionState, matchedRules []types.MatchedRule)
}

var defaultOptions = Options{
OnTransactionStarted: func(plugintypes.TransactionState) {},
OnTransactionClosed: func(plugintypes.TransactionState, []types.MatchedRule) {},
}

func (o *Options) loadDefaults() {
if o.OnTransactionStarted == nil {
o.OnTransactionStarted = defaultOptions.OnTransactionStarted
}
if o.OnTransactionClosed == nil {
o.OnTransactionClosed = defaultOptions.OnTransactionClosed
}
}

func WrapHandler(waf coraza.WAF, h http.Handler) http.Handler {
return wrapHandler(waf, h, defaultOptions)
}

func WrapHandlerWithOptions(waf coraza.WAF, h http.Handler, opts Options) http.Handler {
opts.loadDefaults()
return wrapHandler(waf, h, opts)
}

func wrapHandler(waf coraza.WAF, h http.Handler, opts Options) http.Handler {
if waf == nil {
return h
}
Expand All @@ -132,13 +169,16 @@ func WrapHandler(waf coraza.WAF, h http.Handler) http.Handler {

fn := func(w http.ResponseWriter, r *http.Request) {
tx := newTX(r)
txs := tx.(plugintypes.TransactionState)
opts.OnTransactionStarted(txs)
defer func() {
// We run phase 5 rules and create audit logs (if enabled)
tx.ProcessLogging()
// we remove temporary files and free some memory
if err := tx.Close(); err != nil {
tx.DebugLogger().Error().Err(err).Msg("Failed to close the transaction")
}
opts.OnTransactionClosed(txs, tx.MatchedRules())
}()

// Early return, Coraza is not going to process any rule
Expand Down
23 changes: 23 additions & 0 deletions http/middleware_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ package http
import (
"bufio"
"bytes"
"context"
"fmt"
"io"
"mime/multipart"
Expand All @@ -23,6 +24,7 @@ import (
"github.com/corazawaf/coraza/v3"
"github.com/corazawaf/coraza/v3/debuglog"
"github.com/corazawaf/coraza/v3/experimental/plugins/macro"
"github.com/corazawaf/coraza/v3/experimental/plugins/plugintypes"
"github.com/corazawaf/coraza/v3/internal/corazawaf"
"github.com/corazawaf/coraza/v3/internal/seclang"
"github.com/corazawaf/coraza/v3/types"
Expand Down Expand Up @@ -213,6 +215,7 @@ func TestChainEvaluation(t *testing.T) {
}

func errLogger(t *testing.T) func(rule types.MatchedRule) {
t.Helper()
return func(rule types.MatchedRule) {
t.Log(rule.ErrorLog())
}
Expand Down Expand Up @@ -606,3 +609,23 @@ func TestHandlerAPI(t *testing.T) {
})
}
}

type ctxKey struct{}

func TestWrapHandlerWithOptions(t *testing.T) {
waf, _ := coraza.NewWAF(coraza.NewWAFConfig())
delegateHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {})

ctx := context.WithValue(context.Background(), ctxKey{}, "value")
req, _ := http.NewRequestWithContext(ctx, "GET", "https://www.coraza.io/test", nil)

wrappedHandler := WrapHandlerWithOptions(waf, delegateHandler, Options{
OnTransactionStarted: func(tx plugintypes.TransactionState) {
if want, have := "value", tx.Context().Value(ctxKey{}).(string); want != have {
t.Errorf("unexpected context value, want: %s, have: %s", want, have)
}
},
}).(http.HandlerFunc)

wrappedHandler(httptest.NewRecorder(), req)
}
4 changes: 4 additions & 0 deletions internal/corazawaf/transaction.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,10 @@ func (tx *Transaction) ID() string {
return tx.id
}

func (tx *Transaction) Context() context.Context {
return tx.context
}

func (tx *Transaction) Variables() plugintypes.TransactionVariables {
return &tx.variables
}
Expand Down

0 comments on commit c9180ed

Please sign in to comment.