Skip to content

Commit b8b84c8

Browse files
committed
fix: add defensive map copies to preserve ObservationContext immutability
Copy the Attributes map in both NewObservationContext (inbound) and the ObservationContext getter (outbound) to prevent callers from mutating the internal state of MarketPriceObservation through shared map references.
1 parent 96cdbaa commit b8b84c8

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

services/market-information/domain/observation.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,8 +227,18 @@ func (o MarketPriceObservation) TrustLevel() int {
227227
}
228228

229229
// ObservationContext returns the typed metadata about collection and processing.
230+
// Returns a defensive copy to preserve the immutability contract (the Attributes
231+
// map is a reference type).
230232
func (o MarketPriceObservation) ObservationContext() ObservationContext {
231-
return o.observationContext
233+
ctx := o.observationContext
234+
if ctx.Attributes != nil {
235+
cp := make(map[string]string, len(ctx.Attributes))
236+
for k, v := range ctx.Attributes {
237+
cp[k] = v
238+
}
239+
ctx.Attributes = cp
240+
}
241+
return ctx
232242
}
233243

234244
// MarketPriceObservationBuilder provides a builder pattern for reconstructing

services/market-information/domain/observation_context.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,12 @@ type ObservationContext struct {
3535
// This is the primary constructor used during observation ingestion where
3636
// attributes come from the proto AttributeEntry list.
3737
func NewObservationContext(attributes map[string]string) ObservationContext {
38-
if attributes == nil {
39-
attributes = make(map[string]string)
38+
cp := make(map[string]string, len(attributes))
39+
for k, v := range attributes {
40+
cp[k] = v
4041
}
4142
return ObservationContext{
42-
Attributes: attributes,
43+
Attributes: cp,
4344
}
4445
}
4546

0 commit comments

Comments
 (0)