Debian Codegraph @

user/access_cache_test.go

raw
1 package user
2
3 import (
4 "regexp"
5 "strings"
6 "sync"
7 "sync/atomic"
8 "testing"
9
10 "github.com/stretchr/testify/require"
11 )
12
13 // Cache-only unit tests. Integration with the Manager (loading from the DB,
14 // reload-after-mutation, end-to-end Authorize behavior) is covered by the
15 // existing TestStoreAuthorizeTopicAccess* tests in manager_test.go via
16 // forEachStoreBackend.
17
18 func TestCompileLikeToRegex_Exact(t *testing.T) {
19 r := mustCompileLikeToRegex(t, "foo")
20 require.True(t, r.MatchString("foo"))
21 require.False(t, r.MatchString("foox"))
22 require.False(t, r.MatchString("xfoo"))
23 }
24
25 func TestCompileLikeToRegex_TrailingPercent(t *testing.T) {
26 r := mustCompileLikeToRegex(t, "up%")
27 require.True(t, r.MatchString("up"))
28 require.True(t, r.MatchString("up123"))
29 require.False(t, r.MatchString("xup"))
30 }
31
32 func TestCompileLikeToRegex_LeadingAndEmbeddedPercent(t *testing.T) {
33 r := mustCompileLikeToRegex(t, "%test%")
34 require.True(t, r.MatchString("test"))
35 require.True(t, r.MatchString("mytest"))
36 require.True(t, r.MatchString("testxxx"))
37 require.True(t, r.MatchString("xtestx"))
38 require.False(t, r.MatchString("nope"))
39 }
40
41 func TestCompileLikeToRegex_EscapedUnderscore(t *testing.T) {
42 // "my\_topic" is the stored form of a literal "my_topic" -- the underscore
43 // must match itself, NOT act as a SQL one-character wildcard.
44 r := mustCompileLikeToRegex(t, `my\_topic`)
45 require.True(t, r.MatchString("my_topic"))
46 require.False(t, r.MatchString("myXtopic"))
47 require.False(t, r.MatchString("mytopic"))
48 }
49
50 func TestCompileLikeToRegex_EscapedUnderscoreAdjacentToPercent(t *testing.T) {
51 // "nz\_vip\_%" is the stored form of "nz_vip_*" -- literal "nz_vip_" prefix
52 // followed by any suffix.
53 r := mustCompileLikeToRegex(t, `nz\_vip\_%`)
54 require.True(t, r.MatchString("nz_vip_"))
55 require.True(t, r.MatchString("nz_vip_alpha"))
56 require.False(t, r.MatchString("nz_vipX"))
57 require.False(t, r.MatchString("nzvip_alpha"))
58 }
59
60 func TestCompileLikeToRegex_RegexMetaCharsInTopic(t *testing.T) {
61 // Topics in ntfy can include '-', which is benign, but make sure
62 // regex metacharacters in the pattern are escaped properly anyway.
63 r := mustCompileLikeToRegex(t, "foo-bar")
64 require.True(t, r.MatchString("foo-bar"))
65 require.False(t, r.MatchString("foo.bar")) // would match if '-' leaked into a character class
66 }
67
68 func TestACLCache_LookupBeforeReload(t *testing.T) {
69 // A freshly-constructed cache has empty exact and wildcards maps. The
70 // cache treats this as "no rule found", which the caller resolves via
71 // DefaultAccess.
72 c := newAccessCache()
73 read, write, found := c.Lookup("phil", "mytopic")
74 require.False(t, found)
75 require.False(t, read)
76 require.False(t, write)
77 }
78
79 func TestACLCache_ExactMatchHit(t *testing.T) {
80 c := newAccessCache()
81 loadCache(t, c, []rawACLRow{
82 {user: "phil", topic: "mytopic", read: true, write: true},
83 })
84 read, write, found := c.Lookup("phil", "mytopic")
85 require.True(t, found)
86 require.True(t, read)
87 require.True(t, write)
88 }
89
90 func TestACLCache_ExactMatchMiss(t *testing.T) {
91 c := newAccessCache()
92 loadCache(t, c, []rawACLRow{
93 {user: "phil", topic: "mytopic", read: true, write: true},
94 })
95 _, _, found := c.Lookup("phil", "othertopic")
96 require.False(t, found)
97 }
98
99 func TestACLCache_LiteralUnderscoreExactMatch(t *testing.T) {
100 // Stored as "my\_topic" (toSQLWildcard of "my_topic"). A literal underscore
101 // in the requested topic must match, while any other single char must not.
102 c := newAccessCache()
103 loadCache(t, c, []rawACLRow{
104 {user: "phil", topic: `my\_topic`, read: true, write: false},
105 })
106 read, write, found := c.Lookup("phil", "my_topic")
107 require.True(t, found)
108 require.True(t, read)
109 require.False(t, write)
110
111 _, _, found = c.Lookup("phil", "myXtopic")
112 require.False(t, found)
113 }
114
115 func TestACLCache_WildcardMatch(t *testing.T) {
116 c := newAccessCache()
117 loadCache(t, c, []rawACLRow{
118 {user: Everyone, topic: "up%", read: false, write: true},
119 })
120 read, write, found := c.Lookup("phil", "up42")
121 require.True(t, found)
122 require.False(t, read)
123 require.True(t, write)
124 }
125
126 func TestACLCache_SpecificUserBeatsEveryone(t *testing.T) {
127 c := newAccessCache()
128 loadCache(t, c, []rawACLRow{
129 {user: Everyone, topic: "mytopic", read: true, write: false},
130 {user: "phil", topic: "mytopic", read: false, write: false}, // deny-all for phil
131 })
132 read, write, found := c.Lookup("phil", "mytopic")
133 require.True(t, found)
134 require.False(t, read)
135 require.False(t, write)
136 }
137
138 func TestACLCache_SpecificUserBeatsEveryoneEvenWhenShorter(t *testing.T) {
139 // The SQL's "user_name DESC" sort key takes precedence over LENGTH(topic).
140 // Concretely: a specific user with a shorter matching rule still wins over
141 // Everyone with a longer matching rule.
142 c := newAccessCache()
143 loadCache(t, c, []rawACLRow{
144 {user: Everyone, topic: "foo", read: true, write: true}, // exact, length 3
145 {user: "phil", topic: "f%", read: false, write: false}, // wildcard, length 2, deny-all
146 })
147 read, write, found := c.Lookup("phil", "foo")
148 require.True(t, found)
149 require.False(t, read)
150 require.False(t, write)
151 }
152
153 func TestACLCache_SpecificUserBeatsEveryoneRegardlessOfWrite(t *testing.T) {
154 // Same-length rules but conflicting permissions across user boundary: the
155 // specific user always wins, even if its permission set is weaker (or
156 // stronger, in either direction).
157 c := newAccessCache()
158 loadCache(t, c, []rawACLRow{
159 {user: Everyone, topic: "mytopic", read: true, write: true}, // wide-open
160 {user: "phil", topic: "mytopic", read: true, write: false}, // read-only for phil
161 })
162 read, write, found := c.Lookup("phil", "mytopic")
163 require.True(t, found)
164 require.True(t, read)
165 require.False(t, write)
166 }
167
168 func TestACLCache_AnonymousReadsEveryone(t *testing.T) {
169 c := newAccessCache()
170 loadCache(t, c, []rawACLRow{
171 {user: Everyone, topic: "announcements", read: true, write: false},
172 })
173 read, write, found := c.Lookup(Everyone, "announcements")
174 require.True(t, found)
175 require.True(t, read)
176 require.False(t, write)
177 }
178
179 func TestACLCache_LongerPatternWinsForSameUser(t *testing.T) {
180 // Both rules belong to the same user (Everyone). The more specific (longer)
181 // "mytopic%" should beat the catch-all "%".
182 c := newAccessCache()
183 loadCache(t, c, []rawACLRow{
184 {user: Everyone, topic: "%", read: true, write: false},
185 {user: Everyone, topic: "mytopic%", read: true, write: true},
186 })
187 read, write, found := c.Lookup(Everyone, "mytopicX")
188 require.True(t, found)
189 require.True(t, read)
190 require.True(t, write)
191 }
192
193 func TestACLCache_ExactBeatsShorterWildcardSameUser(t *testing.T) {
194 // Same user, two matching rules: exact "foo" (length 3) and wildcard "f%"
195 // (length 2). The longer one wins, which is the exact rule -- mirroring
196 // the SQL's "LENGTH(topic) DESC" tie-break. Crucially, the cache must seed
197 // "best" from the exact map probe before walking wildcards, otherwise a
198 // shorter wildcard could overwrite a longer exact.
199 c := newAccessCache()
200 loadCache(t, c, []rawACLRow{
201 {user: "phil", topic: "foo", read: true, write: true}, // exact, length 3
202 {user: "phil", topic: "f%", read: false, write: false}, // wildcard, length 2, deny-all
203 })
204 read, write, found := c.Lookup("phil", "foo")
205 require.True(t, found)
206 require.True(t, read)
207 require.True(t, write)
208 }
209
210 func TestACLCache_LongerWildcardBeatsExactSameUser(t *testing.T) {
211 // Same user, two matching rules: exact "foo" (length 3) and wildcard "foo%"
212 // (length 4). The wildcard wins on length DESC. Exercises the "swap best
213 // to wildcard when better() returns true" path.
214 c := newAccessCache()
215 loadCache(t, c, []rawACLRow{
216 {user: "phil", topic: "foo", read: false, write: false}, // exact, length 3, deny-all
217 {user: "phil", topic: "foo%", read: true, write: true}, // wildcard, length 4
218 })
219 read, write, found := c.Lookup("phil", "foo")
220 require.True(t, found)
221 require.True(t, read)
222 require.True(t, write)
223 }
224
225 func TestACLCache_WriteBeatsReadAtEqualLength(t *testing.T) {
226 // Two wildcard rules of identical length for the same user. The write rule
227 // should win the tie-break. The two-rows-with-same-topic shape is
228 // impossible via real upsert (pkey would conflict), so we inject the entries
229 // directly into the cache's wildcard slice.
230 c := newAccessCache()
231 c.mu.Lock()
232 c.exact = map[string]map[string]aclEntry{}
233 c.pattern = map[string][]aclEntry{
234 Everyone: {
235 {length: len("ab%"), read: true, write: false, pattern: mustCompileLikeToRegex(t, "ab%")},
236 {length: len("ab%"), read: false, write: true, pattern: mustCompileLikeToRegex(t, "ab%")},
237 },
238 }
239 c.mu.Unlock()
240 _, write, found := c.Lookup(Everyone, "abc")
241 require.True(t, found)
242 require.True(t, write)
243 }
244
245 func TestACLCache_ConcurrentLookupAndReload(t *testing.T) {
246 // Lock-based swap must be safe under concurrent reads. The race detector
247 // catches any unsafe shared mutation.
248 c := newAccessCache()
249 loadCache(t, c, []rawACLRow{
250 {user: Everyone, topic: "mytopic", read: true, write: true},
251 })
252
253 var stop atomic.Bool
254 var wg sync.WaitGroup
255 wg.Add(2)
256 go func() {
257 defer wg.Done()
258 for !stop.Load() {
259 _, _, _ = c.Lookup(Everyone, "mytopic")
260 }
261 }()
262 go func() {
263 defer wg.Done()
264 for i := 0; i < 100; i++ {
265 loadCache(t, c, []rawACLRow{
266 {user: Everyone, topic: "mytopic", read: i%2 == 0, write: i%2 == 1},
267 })
268 }
269 stop.Store(true)
270 }()
271 wg.Wait()
272 }
273
274 // rawACLRow models the rows that reload would Scan from the DB but avoids
275 // actually opening a DB for these unit tests.
276 type rawACLRow struct {
277 user string
278 topic string
279 read bool
280 write bool
281 }
282
283 // loadCache writes the given rows into the cache under its write lock,
284 // preserving the same exact/wildcard partitioning that reload would produce.
285 func loadCache(t *testing.T, c *accessCache, rows []rawACLRow) {
286 t.Helper()
287 exact := make(map[string]map[string]aclEntry)
288 wildcards := make(map[string][]aclEntry)
289 for _, r := range rows {
290 e := aclEntry{length: len(r.topic), read: r.read, write: r.write}
291 if strings.Contains(r.topic, "%") {
292 e.pattern = mustCompileLikeToRegex(t, r.topic)
293 wildcards[r.user] = append(wildcards[r.user], e)
294 } else {
295 if exact[r.user] == nil {
296 exact[r.user] = make(map[string]aclEntry)
297 }
298 exact[r.user][r.topic] = e
299 }
300 }
301 c.mu.Lock()
302 c.exact = exact
303 c.pattern = wildcards
304 c.mu.Unlock()
305 }
306
307 func mustCompileLikeToRegex(t *testing.T, pattern string) *regexp.Regexp {
308 t.Helper()
309 r, err := compileLikeToRegex(pattern)
310 require.NoError(t, err)
311 return r
312 }