Skip to content

Commit ff68a3b

Browse files
authored
[FIX] accounting for weights in cluster should be handled separate (#222)
Fixes nats-io/nsc#657
1 parent 41dad79 commit ff68a3b

File tree

2 files changed

+47
-3
lines changed

2 files changed

+47
-3
lines changed

v2/account_claims.go

+13-3
Original file line numberDiff line numberDiff line change
@@ -152,10 +152,20 @@ type Mapping map[Subject][]WeightedMapping
152152
func (m *Mapping) Validate(vr *ValidationResults) {
153153
for ubFrom, wm := range (map[Subject][]WeightedMapping)(*m) {
154154
ubFrom.Validate(vr)
155+
perCluster := make(map[string]uint8)
155156
total := uint8(0)
156-
for _, wm := range wm {
157-
wm.Subject.Validate(vr)
158-
total += wm.GetWeight()
157+
for _, e := range wm {
158+
e.Subject.Validate(vr)
159+
if e.Cluster != "" {
160+
t := perCluster[e.Cluster]
161+
t += e.Weight
162+
perCluster[e.Cluster] = t
163+
if t > 100 {
164+
vr.AddError("Mapping %q in cluster %q exceeds 100%% among all of it's weighted to mappings", ubFrom, e.Cluster)
165+
}
166+
} else {
167+
total += e.GetWeight()
168+
}
159169
}
160170
if total > 100 {
161171
vr.AddError("Mapping %q exceeds 100%% among all of it's weighted to mappings", ubFrom)

v2/account_claims_test.go

+34
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,40 @@ func TestAccountMapping(t *testing.T) { // don't block encoding!!!
709709
}
710710
}
711711

712+
func TestAccountClusterMany100MappingOK(t *testing.T) { // don't block encoding!!!
713+
akp := createAccountNKey(t)
714+
apk := publicKey(akp, t)
715+
716+
account := NewAccountClaims(apk)
717+
vr := &ValidationResults{}
718+
719+
account.AddMapping("q",
720+
WeightedMapping{Subject: "qq", Weight: 100, Cluster: "A"},
721+
WeightedMapping{Subject: "qq", Weight: 100, Cluster: "B"},
722+
WeightedMapping{Subject: "bb", Weight: 100, Cluster: "C"},
723+
WeightedMapping{Subject: "qq", Weight: 100})
724+
account.Validate(vr)
725+
if !vr.IsEmpty() {
726+
t.Fatal("Expected no errors")
727+
}
728+
}
729+
730+
func TestAccountClusterNoOver100Mapping(t *testing.T) { // don't block encoding!!!
731+
akp := createAccountNKey(t)
732+
apk := publicKey(akp, t)
733+
734+
account := NewAccountClaims(apk)
735+
vr := &ValidationResults{}
736+
737+
account.AddMapping("q",
738+
WeightedMapping{Subject: "qq", Weight: 100, Cluster: "A"},
739+
WeightedMapping{Subject: "qq", Weight: 5, Cluster: "A"})
740+
account.Validate(vr)
741+
if !vr.IsBlocking(false) {
742+
t.Fatal("Expected blocking error as sum of weights is > 100")
743+
}
744+
}
745+
712746
func TestAccountExternalAuthorization(t *testing.T) {
713747
akp := createAccountNKey(t)
714748
apk := publicKey(akp, t)

0 commit comments

Comments
 (0)