Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(experimental): adds transaction started and transaction closed hooks to the middleware. #987

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure if it's fine for these not to return context, if not then started is probably even less useful.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are you thinking of injecting the tx into the context and passing down to the next middleware? The reason why I added this hooks to avoid the addition to yet another middleware to do stuff with the transaction.


// 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
Loading