Repository navigation
Expand file tree
/
Copy pathplugin_test.go
More file actions
295 lines (240 loc) · 9.46 KB
/
Copy pathplugin_test.go
File metadata and controls
295 lines (240 loc) · 9.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
package riskengine
import (
"context"
"errors"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
log "github.com/xraph/go-utils/log"
"github.com/xraph/authsome/account"
"github.com/xraph/authsome/bridge"
"github.com/xraph/authsome/id"
"github.com/xraph/authsome/plugin"
"github.com/xraph/authsome/principal"
)
type mockContributor struct {
name string
score int
weight float64
err error
}
func (m *mockContributor) Name() string { return m.name }
func (m *mockContributor) EvaluateRisk(_ context.Context, _ *RiskRequest) (*RiskSignal, error) {
if m.err != nil {
return nil, m.err
}
return &RiskSignal{Source: m.name, Score: m.score, Weight: m.weight, Reason: "test"}, nil
}
func newTestPlugin(cfg Config, contributors ...RiskContributor) *Plugin {
p := NewWithConfig(cfg, contributors...)
p.logger = log.NewNoopLogger()
return p
}
func TestPlugin_Name(t *testing.T) {
p := New()
assert.Equal(t, "riskengine", p.Name())
}
func TestPlugin_ImplementsInterfaces(t *testing.T) {
var p interface{} = New()
_, ok := p.(plugin.Plugin)
assert.True(t, ok)
_, ok = p.(plugin.OnInit)
assert.True(t, ok)
_, ok = p.(plugin.BeforeSignIn)
assert.True(t, ok)
_, ok = p.(plugin.BeforeSessionCreate)
assert.True(t, ok)
_, ok = p.(plugin.BeforePrincipalAuth)
assert.True(t, ok)
}
func TestNoContributors_Allow(t *testing.T) {
p := newTestPlugin(Config{})
appID, _ := id.ParseAppID("aapp_01jf0000000000000000000000")
err := p.OnBeforeSignIn(context.Background(), &account.SignInRequest{AppID: appID})
assert.NoError(t, err)
}
func TestLowScore_Allow(t *testing.T) {
contrib := &mockContributor{name: "test", score: 20, weight: 1.0}
p := newTestPlugin(Config{}, contrib)
assessment := p.evaluate(context.Background(), &RiskRequest{IPAddress: "1.2.3.4"})
assert.Equal(t, "allow", assessment.Decision)
assert.Equal(t, 20, assessment.OverallScore)
}
func TestMediumScore_Challenge(t *testing.T) {
contrib := &mockContributor{name: "test", score: 65, weight: 1.0}
p := newTestPlugin(Config{}, contrib)
assessment := p.evaluate(context.Background(), &RiskRequest{IPAddress: "1.2.3.4"})
assert.Equal(t, "challenge", assessment.Decision)
assert.Equal(t, 65, assessment.OverallScore)
}
func TestHighScore_Block(t *testing.T) {
contrib := &mockContributor{name: "test", score: 90, weight: 1.0}
p := newTestPlugin(Config{}, contrib)
assessment := p.evaluate(context.Background(), &RiskRequest{IPAddress: "1.2.3.4"})
assert.Equal(t, "block", assessment.Decision)
assert.Equal(t, 90, assessment.OverallScore)
// OnBeforeSignIn should return an error for a blocked request.
appID, _ := id.ParseAppID("aapp_01jf0000000000000000000000")
err := p.OnBeforeSignIn(context.Background(), &account.SignInRequest{
AppID: appID,
IPAddress: "1.2.3.4",
})
require.Error(t, err)
assert.Contains(t, err.Error(), "riskengine:")
}
func TestWeightedScoring(t *testing.T) {
c1 := &mockContributor{name: "c1", score: 80, weight: 1.0}
c2 := &mockContributor{name: "c2", score: 20, weight: 1.0}
// With configured weights: c1 has weight 2.0, c2 has weight 1.0.
// Weighted average: (80*2 + 20*1) / (2+1) = 180/3 = 60
p := newTestPlugin(Config{
Weights: map[string]float64{"c1": 2.0, "c2": 1.0},
}, c1, c2)
assessment := p.evaluate(context.Background(), &RiskRequest{})
assert.Equal(t, 60, assessment.OverallScore)
}
func TestContributorError_Skipped(t *testing.T) {
good := &mockContributor{name: "good", score: 20, weight: 1.0}
bad := &mockContributor{name: "bad", err: errors.New("failed")}
p := newTestPlugin(Config{}, good, bad)
assessment := p.evaluate(context.Background(), &RiskRequest{})
assert.Equal(t, 20, assessment.OverallScore)
assert.Len(t, assessment.Signals, 1)
}
func TestAddContributor(t *testing.T) {
p := newTestPlugin(Config{})
assert.Empty(t, p.contributors)
c := &mockContributor{name: "added", score: 50, weight: 1.0}
p.AddContributor(c)
assert.Len(t, p.contributors, 1)
assessment := p.evaluate(context.Background(), &RiskRequest{})
assert.Equal(t, 50, assessment.OverallScore)
}
func TestAuditAssessment(t *testing.T) { //nolint:revive // test function signature
// Verify auditAssessment does not panic when chronicle is nil.
contrib := &mockContributor{name: "test", score: 50, weight: 1.0}
p := newTestPlugin(Config{}, contrib)
req := &RiskRequest{IPAddress: "1.2.3.4", AppID: "app1"}
assessment := p.evaluate(context.Background(), req)
p.auditAssessment(context.Background(), req, assessment)
}
// capturingContributor records the request it was handed so we can assert on
// what the engine actually populates.
type capturingContributor struct {
got *RiskRequest
}
func (c *capturingContributor) Name() string { return "capturing" }
func (c *capturingContributor) EvaluateRisk(_ context.Context, req *RiskRequest) (*RiskSignal, error) {
c.got = req
return &RiskSignal{Source: "capturing", Score: 0, Weight: 1}, nil
}
// A user-scoped contributor needs something to identify the user by. Before
// this fix the engine passed neither, so the whole class of contributor was
// dead on arrival.
func TestOnBeforeSignIn_PassesIdentifierToContributors(t *testing.T) {
c := &capturingContributor{}
p := New(c)
p.logger = log.NewNoopLogger()
appID := id.NewAppID()
err := p.OnBeforeSignIn(context.Background(), &account.SignInRequest{
AppID: appID,
Email: "target@corp.com",
IPAddress: "203.0.113.10",
UserAgent: "test-agent",
})
require.NoError(t, err)
require.NotNil(t, c.got)
assert.Equal(t, "203.0.113.10", c.got.IPAddress)
assert.Equal(t, appID.String(), c.got.AppID)
assert.Equal(t, "target@corp.com", c.got.Email,
"contributors that score a user need the sign-in identifier")
}
// A high-risk machine caller must be denied, exactly as a high-risk sign-in
// is. This is the gap: API-key traffic never reached OnBeforeSignIn.
func TestOnBeforePrincipalAuth_Blocks(t *testing.T) {
contrib := &mockContributor{name: "test", score: 90, weight: 1.0}
p := newTestPlugin(Config{}, contrib)
err := p.OnBeforePrincipalAuth(context.Background(), &principal.AuthAttempt{
Subject: principal.Ref{Kind: principal.KindAgent, ID: "svc_1"},
AppID: id.NewAppID(),
IPAddress: "1.2.3.4",
CredentialKind: "api_key",
})
require.Error(t, err, "a high-risk machine caller must be denied")
assert.Contains(t, err.Error(), "riskengine:")
}
// With no contributors the hook is a no-op, matching OnBeforeSignIn.
// Otherwise installing riskengine alone would deny every machine caller.
func TestOnBeforePrincipalAuth_AllowsWithNoContributors(t *testing.T) {
p := newTestPlugin(Config{})
err := p.OnBeforePrincipalAuth(context.Background(), &principal.AuthAttempt{
Subject: principal.Ref{Kind: principal.KindAgent, ID: "svc_1"},
})
assert.NoError(t, err)
}
// The contributor must be able to tell a machine caller from a person.
// UserID stays empty for machines rather than being filled with a
// service-account id, which an existing contributor would misread.
func TestOnBeforePrincipalAuth_SetsPrincipalNotUserID(t *testing.T) {
spy := &capturingContributor{}
p := New(spy)
p.logger = log.NewNoopLogger()
require.NoError(t, p.OnBeforePrincipalAuth(context.Background(), &principal.AuthAttempt{
Subject: principal.Ref{Kind: principal.KindAgent, ID: "svc_1"},
AppID: id.NewAppID(),
IPAddress: "1.2.3.4",
}))
require.NotNil(t, spy.got)
assert.Equal(t, "agent:svc_1", spy.got.Principal)
assert.Empty(t, spy.got.UserID, "a machine caller has no user id")
}
// A blocked machine caller must still leave an audit row with an actor
// attached. Before the Principal fallback in auditAssessment, ActorID stayed
// empty for every agent or workload riskengine blocked or challenged, since
// UserID is empty by design on that path: an audit row with no actor is not
// an audit row.
func TestOnBeforePrincipalAuth_AuditsBlockedCallerWithPrincipalActor(t *testing.T) {
contrib := &mockContributor{name: "test", score: 90, weight: 1.0}
p := newTestPlugin(Config{}, contrib)
var captured *bridge.AuditEvent
p.chronicle = bridge.ChronicleFunc(func(_ context.Context, event *bridge.AuditEvent) error {
captured = event
return nil
})
err := p.OnBeforePrincipalAuth(context.Background(), &principal.AuthAttempt{
Subject: principal.Ref{Kind: principal.KindAgent, ID: "svc_1"},
AppID: id.NewAppID(),
IPAddress: "1.2.3.4",
CredentialKind: "api_key",
})
require.Error(t, err, "a high-risk machine caller must still be denied")
require.NotNil(t, captured, "a blocked machine caller must still write an audit row")
assert.Equal(t, "agent:svc_1", captured.ActorID,
"the audit actor must be the principal ref, not empty")
}
// OnBeforeSignIn must leave Principal empty: account.SignInRequest carries
// no user id at this point, only Email and Username, and putting an email in
// an id position would be wrong.
func TestOnBeforeSignIn_LeavesPrincipalEmpty(t *testing.T) {
spy := &capturingContributor{}
p := New(spy)
p.logger = log.NewNoopLogger()
require.NoError(t, p.OnBeforeSignIn(context.Background(), &account.SignInRequest{
AppID: id.NewAppID(),
Email: "target@corp.com",
}))
require.NotNil(t, spy.got)
assert.Empty(t, spy.got.Principal)
}
func TestOnBeforeSignIn_PassesUsernameWhenEmailAbsent(t *testing.T) {
c := &capturingContributor{}
p := New(c)
p.logger = log.NewNoopLogger()
err := p.OnBeforeSignIn(context.Background(), &account.SignInRequest{
AppID: id.NewAppID(),
Username: "targetuser",
})
require.NoError(t, err)
require.NotNil(t, c.got)
assert.Equal(t, "targetuser", c.got.Username)
}