core: Check for nil event origin (#7047)

* fix: crash - null check on event origin

* chore: use accessor instead of property
pull/6772/head^2
Laurin 2025-06-05 21:10:08 +02:00 committed by GitHub
parent 45c9341deb
commit 7099892958
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 26 additions and 1 deletions

View File

@ -1104,9 +1104,15 @@ func (e Event) Origin() Module { return e.origin } // Returns the module t
// CloudEvents spec. // CloudEvents spec.
func (e Event) CloudEvent() CloudEvent { func (e Event) CloudEvent() CloudEvent {
dataJSON, _ := json.Marshal(e.Data) dataJSON, _ := json.Marshal(e.Data)
var source string
if e.Origin() == nil {
source = "caddy"
} else {
source = string(e.Origin().CaddyModule().ID)
}
return CloudEvent{ return CloudEvent{
ID: e.id.String(), ID: e.id.String(),
Source: e.origin.CaddyModule().String(), Source: source,
SpecVersion: "1.0", SpecVersion: "1.0",
Type: e.name, Type: e.name,
Time: e.ts, Time: e.ts,

View File

@ -15,6 +15,7 @@
package caddy package caddy
import ( import (
"context"
"testing" "testing"
"time" "time"
) )
@ -72,3 +73,21 @@ func TestParseDuration(t *testing.T) {
} }
} }
} }
func TestEvent_CloudEvent_NilOrigin(t *testing.T) {
ctx, _ := NewContext(Context{Context: context.Background()}) // module will be nil by default
event, err := NewEvent(ctx, "started", nil)
if err != nil {
t.Fatalf("NewEvent() error = %v", err)
}
// This should not panic
ce := event.CloudEvent()
if ce.Source != "caddy" {
t.Errorf("Expected CloudEvent Source to be 'caddy', got '%s'", ce.Source)
}
if ce.Type != "started" {
t.Errorf("Expected CloudEvent Type to be 'started', got '%s'", ce.Type)
}
}