| 1 |
package user |
| 2 |
|
| 3 |
import ( |
| 4 |
"regexp" |
| 5 |
"strings" |
| 6 |
"sync" |
| 7 |
"time" |
| 8 |
|
| 9 |
"heckel.io/ntfy/v2/db" |
| 10 |
"heckel.io/ntfy/v2/log" |
| 11 |
) |
| 12 |
|
| 13 |
// accessCache is an in-memory index over the entire user_access table. |
| 14 |
// |
| 15 |
// exact[username][escapedTopic] returns the matching entry in O(1) for the common |
| 16 |
// case where the requested topic appears verbatim in some rule. The key is the |
| 17 |
// stored form of the topic (i.e. with \_ escapes), so Lookup escapes incoming |
| 18 |
// topics through escapeUnderscore before probing. |
| 19 |
// |
| 20 |
// pattern[username] is the linear-scan list of %-bearing rules for that user. |
| 21 |
// Walked per request; trivially small in practice. Wildcards are NOT u_everyone- |
| 22 |
// only -- any user can create them. |
| 23 |
type accessCache struct { |
| 24 |
exact map[string]map[string]aclEntry |
| 25 |
pattern map[string][]aclEntry |
| 26 |
seq uint64 // Bumped on every reload; lets a full reload detect a per-user reload that raced its scan |
| 27 |
mu sync.RWMutex // Protect exact, pattern, and seq |
| 28 |
} |
| 29 |
|
| 30 |
// testHookReloadScanned, if non-nil, is invoked by Reload after the DB scan but |
| 31 |
// before the result is applied. Tests use it to inject a concurrent mutation |
| 32 |
// into the full-reload race window; it is always nil in production. |
| 33 |
var testHookReloadScanned func() |
| 34 |
|
| 35 |
// aclEntry mirrors one user_access row. length feeds better()'s "longer |
| 36 |
// pattern wins" tie-break; the stored topic/pattern string itself is not kept |
| 37 |
// on the entry (the exact map already keys on it; surfacing wildcard "topics" |
| 38 |
// like "up%" alongside real ones would invite misuse). pattern is the |
| 39 |
// compiled regex form of the LIKE pattern; nil for exact entries. |
| 40 |
type aclEntry struct { |
| 41 |
length int |
| 42 |
pattern *regexp.Regexp |
| 43 |
read bool |
| 44 |
write bool |
| 45 |
} |
| 46 |
|
| 47 |
func newAccessCache() *accessCache { |
| 48 |
return &accessCache{ |
| 49 |
exact: make(map[string]map[string]aclEntry), |
| 50 |
pattern: make(map[string][]aclEntry), |
| 51 |
} |
| 52 |
} |
| 53 |
|
| 54 |
// Lookup returns the effective (read, write, found) permission for the given |
| 55 |
// (username, topic), preserving the priority ordering of the original SQL query: |
| 56 |
// 1. specific user beats Everyone |
| 57 |
// 2. longer pattern beats shorter (more specific wins) |
| 58 |
// 3. write beats read at equal length (write is "stronger") |
| 59 |
func (c *accessCache) Lookup(username, topic string) (read, write, found bool) { |
| 60 |
escapedTopic := escapeUnderscore(topic) |
| 61 |
c.mu.RLock() |
| 62 |
if username != Everyone { |
| 63 |
if entry, found := c.lookupNoLock(username, topic, escapedTopic); found { |
| 64 |
c.mu.RUnlock() |
| 65 |
maybeLogACLDecision(username, username, topic, entry.read, entry.write) |
| 66 |
return entry.read, entry.write, true |
| 67 |
} |
| 68 |
} |
| 69 |
if entry, found := c.lookupNoLock(Everyone, topic, escapedTopic); found { |
| 70 |
c.mu.RUnlock() |
| 71 |
maybeLogACLDecision(username, Everyone, topic, entry.read, entry.write) |
| 72 |
return entry.read, entry.write, true |
| 73 |
} |
| 74 |
c.mu.RUnlock() |
| 75 |
maybeLogACLDecision(username, "", topic, false, false) |
| 76 |
return false, false, false |
| 77 |
} |
| 78 |
|
| 79 |
// Reload scans (user_name, topic, read, write) rows and merges them into the |
| 80 |
// cache. With no usernames the cache is replaced wholesale; otherwise the |
| 81 |
// query is invoked with those usernames as positional args and only the |
| 82 |
// listed users' slices are touched (a username absent from the result drops |
| 83 |
// them from both maps). Runs against the primary so a reload after a |
| 84 |
// mutation sees the just-written rows. |
| 85 |
// |
| 86 |
// Since Reload can be triggered from different places and for different scopes (full |
| 87 |
// and user-specific), the function may cause races and lost-updates. This is solved |
| 88 |
// with the sequence number. |
| 89 |
func (c *accessCache) Reload(d *db.DB, query string, usernames ...string) error { |
| 90 |
started := time.Now() |
| 91 |
scope := "full" |
| 92 |
if len(usernames) > 0 { |
| 93 |
scope = "users=" + strings.Join(usernames, ",") |
| 94 |
} |
| 95 |
// Read the sequence number before the SQL query so we can detect races later |
| 96 |
c.mu.RLock() |
| 97 |
seqBefore := c.seq |
| 98 |
c.mu.RUnlock() |
| 99 |
args := make([]any, len(usernames)) |
| 100 |
for i, u := range usernames { |
| 101 |
args[i] = u |
| 102 |
} |
| 103 |
// Query the database for all ACL entries |
| 104 |
rows, err := d.Query(query, args...) |
| 105 |
if err != nil { |
| 106 |
return err |
| 107 |
} |
| 108 |
defer rows.Close() |
| 109 |
exacts := make(map[string]map[string]aclEntry) |
| 110 |
patterns := make(map[string][]aclEntry) |
| 111 |
updatedEntries := 0 |
| 112 |
for rows.Next() { |
| 113 |
var username, escapedTopic string |
| 114 |
var read, write bool |
| 115 |
if err := rows.Scan(&username, &escapedTopic, &read, &write); err != nil { |
| 116 |
return err |
| 117 |
} |
| 118 |
entry, hasWildcard, err := toACLEntry(escapedTopic, read, write) |
| 119 |
if err != nil { |
| 120 |
return err |
| 121 |
} |
| 122 |
if hasWildcard { |
| 123 |
patterns[username] = append(patterns[username], entry) |
| 124 |
} else { |
| 125 |
if exacts[username] == nil { |
| 126 |
exacts[username] = make(map[string]aclEntry) |
| 127 |
} |
| 128 |
exacts[username][escapedTopic] = entry |
| 129 |
} |
| 130 |
updatedEntries++ |
| 131 |
} |
| 132 |
if err := rows.Err(); err != nil { |
| 133 |
return err |
| 134 |
} |
| 135 |
if testHookReloadScanned != nil { |
| 136 |
testHookReloadScanned() |
| 137 |
} |
| 138 |
// Replace or update the internal maps |
| 139 |
c.mu.Lock() |
| 140 |
if len(usernames) == 0 { |
| 141 |
if c.seq != seqBefore { |
| 142 |
c.mu.Unlock() |
| 143 |
log.Tag(tag). |
| 144 |
Field("reload_scope", scope). |
| 145 |
Field("duration_ms", time.Since(started).Milliseconds()). |
| 146 |
Warn("ACL cache reload skipped due to race") |
| 147 |
return nil |
| 148 |
} |
| 149 |
c.exact = exacts |
| 150 |
c.pattern = patterns |
| 151 |
} else { |
| 152 |
for _, u := range usernames { |
| 153 |
if e, ok := exacts[u]; ok { |
| 154 |
c.exact[u] = e |
| 155 |
} else { |
| 156 |
delete(c.exact, u) |
| 157 |
} |
| 158 |
if p, ok := patterns[u]; ok { |
| 159 |
c.pattern[u] = p |
| 160 |
} else { |
| 161 |
delete(c.pattern, u) |
| 162 |
} |
| 163 |
} |
| 164 |
} |
| 165 |
c.seq++ |
| 166 |
c.mu.Unlock() |
| 167 |
log.Tag(tag). |
| 168 |
Field("reload_scope", scope). |
| 169 |
Field("updated_entries", updatedEntries). |
| 170 |
Field("duration_ms", time.Since(started).Milliseconds()). |
| 171 |
Debug("ACL cache reloaded") |
| 172 |
return nil |
| 173 |
} |
| 174 |
|
| 175 |
// lookupNoLock returns the highest-priority entry for a single user. When |
| 176 |
// more than one of that user's rules matches the requested topic, the winner |
| 177 |
// is chosen by: |
| 178 |
// |
| 179 |
// 1. longer stored pattern beats shorter (a more specific rule wins over a |
| 180 |
// more general one) |
| 181 |
// 2. at equal length, write beats read (a stronger permission wins the tie) |
| 182 |
// |
| 183 |
// Exact and wildcard rules are ranked together under the same criteria, so |
| 184 |
// an exact "foo" (length 3) beats a wildcard "f%" (length 2), but a wildcard |
| 185 |
// "foo%" (length 4) beats an exact "foo" (length 3). |
| 186 |
func (c *accessCache) lookupNoLock(username, topic, escapedTopic string) (*aclEntry, bool) { |
| 187 |
var best aclEntry |
| 188 |
var found bool |
| 189 |
if exact, exists := c.exact[username]; exists { |
| 190 |
if entry, exists := exact[escapedTopic]; exists { |
| 191 |
best, found = entry, true |
| 192 |
} |
| 193 |
} |
| 194 |
for _, pattern := range c.pattern[username] { |
| 195 |
if !pattern.pattern.MatchString(topic) { |
| 196 |
continue |
| 197 |
} else if !found || better(pattern, best) { |
| 198 |
best, found = pattern, true |
| 199 |
} |
| 200 |
} |
| 201 |
return &best, found |
| 202 |
} |
| 203 |
|
| 204 |
// toACLEntry builds an aclEntry from one user_access row's values. The |
| 205 |
// isWildcard return tells the caller which storage slot the entry belongs in: |
| 206 |
// the per-user wildcard slice if true, the per-user exact map if false. |
| 207 |
// Wildcards have their LIKE pattern pre-compiled into entry.pattern; exact |
| 208 |
// entries leave entry.pattern nil. |
| 209 |
func toACLEntry(escapedTopic string, read, write bool) (entry aclEntry, hasWildcard bool, err error) { |
| 210 |
entry = aclEntry{ |
| 211 |
length: len(escapedTopic), |
| 212 |
read: read, |
| 213 |
write: write, |
| 214 |
} |
| 215 |
if !strings.Contains(escapedTopic, "%") { |
| 216 |
return entry, false, nil |
| 217 |
} |
| 218 |
pattern, err := compileLikeToRegex(escapedTopic) |
| 219 |
if err != nil { |
| 220 |
return entry, true, err |
| 221 |
} |
| 222 |
entry.pattern = pattern |
| 223 |
return entry, true, nil |
| 224 |
} |
| 225 |
|
| 226 |
// better implements the (length DESC, write DESC) tie-break used by the original |
| 227 |
// query's ORDER BY for entries owned by the same user. |
| 228 |
func better(a, b aclEntry) bool { |
| 229 |
if a.length != b.length { |
| 230 |
return a.length > b.length |
| 231 |
} else if a.write != b.write { |
| 232 |
return a.write |
| 233 |
} |
| 234 |
return false |
| 235 |
} |
| 236 |
|
| 237 |
// compileLikeToRegex converts a stored ntfy LIKE pattern into an equivalent Go |
| 238 |
// regexp. In ntfy's stored form, % is the only wildcard (translated from *) and |
| 239 |
// \_ is a literal underscore; no other backslashes occur. Topics themselves are |
| 240 |
// restricted to [A-Za-z0-9_-] (see AllowedTopic), so neither % nor stray |
| 241 |
// backslashes appear in user-supplied input. |
| 242 |
func compileLikeToRegex(pattern string) (*regexp.Regexp, error) { |
| 243 |
var sb strings.Builder |
| 244 |
sb.WriteString("^") |
| 245 |
i := 0 |
| 246 |
for i < len(pattern) { |
| 247 |
switch { |
| 248 |
case pattern[i] == '\\' && i+1 < len(pattern) && pattern[i+1] == '_': |
| 249 |
sb.WriteString(regexp.QuoteMeta("_")) |
| 250 |
i += 2 |
| 251 |
case pattern[i] == '%': |
| 252 |
sb.WriteString(".*") |
| 253 |
i++ |
| 254 |
default: |
| 255 |
sb.WriteString(regexp.QuoteMeta(string(pattern[i]))) |
| 256 |
i++ |
| 257 |
} |
| 258 |
} |
| 259 |
sb.WriteString("$") |
| 260 |
return regexp.Compile(sb.String()) |
| 261 |
} |
| 262 |
|
| 263 |
// maybeLogACLDecision logs an ACL lookup result |
| 264 |
func maybeLogACLDecision(requestUser, matchedUser, topic string, read, write bool) { |
| 265 |
ev := log.Tag(tag). |
| 266 |
Field("user_name", requestUser). |
| 267 |
Field("topic", topic). |
| 268 |
Field("read", read). |
| 269 |
Field("write", write) |
| 270 |
if !ev.IsTrace() { |
| 271 |
return |
| 272 |
} |
| 273 |
if matchedUser == "" { |
| 274 |
ev.Trace("ACL no match") |
| 275 |
return |
| 276 |
} |
| 277 |
ev.Field("matched_user", matchedUser).Trace("ACL match") |
| 278 |
} |