auth.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. package raft
  2. import (
  3. "crypto/hmac"
  4. "crypto/sha1"
  5. "crypto/sha256"
  6. "encoding/base32"
  7. "encoding/binary"
  8. "encoding/hex"
  9. "encoding/json"
  10. "fmt"
  11. "strconv"
  12. "strings"
  13. "sync"
  14. "time"
  15. "igit.com/xbase/raft/db"
  16. )
  17. // ==================== Auth Constants ====================
  18. const (
  19. ActionRead = "read"
  20. ActionWrite = "write" // Includes Set, Del
  21. ActionAdmin = "admin" // Cluster ops
  22. SystemKeyPrefix = "system."
  23. AuthUserPrefix = "system.user."
  24. AuthRolePrefix = "system.role."
  25. AuthSessionPrefix = "system.session."
  26. AuthConfigKey = "system.config"
  27. )
  28. // ==================== Auth Data Structures ====================
  29. // Constraint defines numeric constraints on values
  30. type Constraint struct {
  31. Min *float64 `json:"min,omitempty"`
  32. Max *float64 `json:"max,omitempty"`
  33. }
  34. // Permission defines access to a key pattern
  35. type Permission struct {
  36. KeyPattern string `json:"key"` // Prefix match. "*" means all.
  37. Actions []string `json:"actions"` // "read", "write", "admin"
  38. Constraint *Constraint `json:"constraint,omitempty"`
  39. }
  40. // Role defines a set of permissions
  41. type Role struct {
  42. Name string `json:"name"`
  43. Permissions []Permission `json:"permissions"`
  44. ParentRoles []string `json:"parent_roles,omitempty"` // Inherit permissions from these roles
  45. }
  46. // User defines a system user
  47. type User struct {
  48. Username string `json:"username"`
  49. PasswordHash string `json:"password_hash"` // SHA256(salt + password)
  50. Salt string `json:"salt"`
  51. Roles []string `json:"roles"`
  52. // Specific overrides
  53. AllowPermissions []Permission `json:"allow_permissions"`
  54. DenyPermissions []Permission `json:"deny_permissions"` // Higher priority
  55. Email string `json:"email"`
  56. Icon string `json:"icon"`
  57. IsOnline bool `json:"is_online"`
  58. MFASecret string `json:"mfa_secret"` // Base32 encoded TOTP secret
  59. MFAEnabled bool `json:"mfa_enabled"`
  60. WhitelistIPs []string `json:"whitelist_ips"`
  61. BlacklistIPs []string `json:"blacklist_ips"`
  62. }
  63. // Session represents an active login session
  64. // Modified: Sessions are stored in Raft, but permCache is transient
  65. type Session struct {
  66. Token string `json:"token"`
  67. Username string `json:"username"`
  68. LoginIP string `json:"login_ip"`
  69. Expiry int64 `json:"expiry"` // Unix timestamp
  70. // Permission Cache: key+action -> bool
  71. // Used to speed up frequent checks (e.g. loops)
  72. // Not serialized to JSON (rebuilt on demand)
  73. permCache sync.Map `json:"-"`
  74. }
  75. // AuthConfig defines global auth settings
  76. type AuthConfig struct {
  77. Enabled bool `json:"enabled"`
  78. }
  79. // ==================== Auth Manager ====================
  80. // AuthManager handles authentication and authorization
  81. type AuthManager struct {
  82. server *KVServer
  83. mu sync.RWMutex
  84. // In-memory cache
  85. users map[string]*User
  86. roles map[string]*Role
  87. // sessions are now ONLY in-memory (local cache)
  88. sessions map[string]*Session
  89. enabled bool
  90. }
  91. // NewAuthManager creates a new AuthManager
  92. func NewAuthManager(server *KVServer) *AuthManager {
  93. return &AuthManager{
  94. server: server,
  95. users: make(map[string]*User),
  96. roles: make(map[string]*Role),
  97. sessions: make(map[string]*Session),
  98. enabled: false,
  99. }
  100. }
  101. // HashPassword hashes a password with salt (Exported for tools)
  102. func HashPassword(password, salt string) string {
  103. hash := sha256.Sum256([]byte(salt + password))
  104. return hex.EncodeToString(hash[:])
  105. }
  106. // Internal helper
  107. func hashPassword(password, salt string) string {
  108. return HashPassword(password, salt)
  109. }
  110. // Helper to generate token
  111. func generateToken() string {
  112. // In a real system use crypto/rand, but here we use math/rand seeded in main or just simple timestamp mix for example
  113. // Since we can't easily access crypto/rand without import and "no external lib" usually implies standard lib only,
  114. // crypto/rand IS standard lib.
  115. h := sha256.Sum256([]byte(fmt.Sprintf("%d", time.Now().UnixNano())))
  116. return hex.EncodeToString(h[:])
  117. }
  118. // Helper for TOTP (Google Authenticator)
  119. func validateTOTP(secret string, code string) bool {
  120. // Decode base32 secret
  121. key, err := base32.StdEncoding.DecodeString(strings.ToUpper(secret))
  122. if err != nil {
  123. return false
  124. }
  125. // Current time steps (30s window)
  126. // Check current, prev, and next window to allow for slight skew
  127. now := time.Now().Unix()
  128. return checkTOTP(key, now, code) || checkTOTP(key, now-30, code) || checkTOTP(key, now+30, code)
  129. }
  130. func checkTOTP(key []byte, timestamp int64, code string) bool {
  131. step := timestamp / 30
  132. buf := make([]byte, 8)
  133. binary.BigEndian.PutUint64(buf, uint64(step))
  134. h := hmac.New(sha1.New, key)
  135. h.Write(buf)
  136. sum := h.Sum(nil)
  137. offset := sum[len(sum)-1] & 0xf
  138. val := int64(((int(sum[offset]) & 0x7f) << 24) |
  139. ((int(sum[offset+1]) & 0xff) << 16) |
  140. ((int(sum[offset+2]) & 0xff) << 8) |
  141. (int(sum[offset+3]) & 0xff))
  142. otp := val % 1000000
  143. expected := fmt.Sprintf("%06d", otp)
  144. return expected == code
  145. }
  146. // UpdateCache updates the internal cache based on key-value changes
  147. // Called by the state machine when applying logs
  148. func (am *AuthManager) UpdateCache(key, value string, isDelete bool) {
  149. am.mu.Lock()
  150. defer am.mu.Unlock()
  151. if key == AuthConfigKey {
  152. if isDelete {
  153. am.enabled = false
  154. } else {
  155. var config AuthConfig
  156. if err := json.Unmarshal([]byte(value), &config); err == nil {
  157. am.enabled = config.Enabled
  158. }
  159. }
  160. return
  161. }
  162. if strings.HasPrefix(key, AuthUserPrefix) {
  163. username := strings.TrimPrefix(key, AuthUserPrefix)
  164. if isDelete {
  165. delete(am.users, username)
  166. } else {
  167. var user User
  168. if err := json.Unmarshal([]byte(value), &user); err == nil {
  169. am.users[username] = &user
  170. am.server.Raft.config.Logger.Info("Updated user cache for %s (hash prefix: %s)", username, user.PasswordHash[:8])
  171. } else {
  172. am.server.Raft.config.Logger.Error("Failed to unmarshal user %s: %v", username, err)
  173. }
  174. }
  175. return
  176. }
  177. if strings.HasPrefix(key, AuthRolePrefix) {
  178. rolename := strings.TrimPrefix(key, AuthRolePrefix)
  179. if isDelete {
  180. delete(am.roles, rolename)
  181. } else {
  182. var role Role
  183. if err := json.Unmarshal([]byte(value), &role); err == nil {
  184. am.roles[rolename] = &role
  185. }
  186. }
  187. return
  188. }
  189. // Note: AuthSessionPrefix is no longer handled here because sessions are local only.
  190. if strings.HasPrefix(key, AuthSessionPrefix) {
  191. token := strings.TrimPrefix(key, AuthSessionPrefix)
  192. if isDelete {
  193. delete(am.sessions, token)
  194. } else {
  195. var session Session
  196. if err := json.Unmarshal([]byte(value), &session); err == nil {
  197. // Check expiry (though normally we'd replicate delete on expiry, but follower can check too)
  198. if time.Now().Unix() > session.Expiry {
  199. delete(am.sessions, token)
  200. } else {
  201. am.sessions[token] = &session
  202. }
  203. }
  204. }
  205. return
  206. }
  207. // Invalidate permission cache on any auth change (Users, Roles, or Sessions changed)
  208. // Even though session changes are frequent, for safety/simplicity we can clear cache.
  209. // But optimizing: Session change only affects THAT session.
  210. // User/Role change affects potentially all sessions.
  211. // Let's clear cache if User/Role changed.
  212. // If Session changed (added/removed), CheckPermission will hit/miss am.sessions map anyway.
  213. // So we don't strictly need to clear permCache for session changes unless we cache existence.
  214. // We cache (token:key:action -> result).
  215. // If session is deleted, we should clear its cache entries?
  216. // The sync.Map doesn't support easy clearing by pattern.
  217. // Given we want High Performance for search (loops), cache is useful.
  218. // But if we use "Cluster Shared Session", updates come via Raft.
  219. // Let's just clear everything on User/Role update.
  220. // For Session update, we don't clear global cache, relying on GetSession check in CheckPermission.
  221. }
  222. // IsEnabled checks if auth is enabled
  223. func (am *AuthManager) IsEnabled() bool {
  224. am.mu.RLock()
  225. defer am.mu.RUnlock()
  226. return am.enabled
  227. }
  228. // CheckPermission checks if a user has permission to perform an action on a key
  229. func (am *AuthManager) CheckPermission(token string, key string, action string, value string) error {
  230. am.mu.RLock()
  231. enabled := am.enabled
  232. am.mu.RUnlock()
  233. if !enabled {
  234. return nil
  235. }
  236. // Internal system bypass
  237. if token == "SYSTEM_INTERNAL" {
  238. return nil
  239. }
  240. am.mu.RLock()
  241. session, ok := am.sessions[token]
  242. am.mu.RUnlock()
  243. if !ok {
  244. return fmt.Errorf("invalid or expired session")
  245. }
  246. if time.Now().Unix() > session.Expiry {
  247. return fmt.Errorf("session expired")
  248. }
  249. // Check Session Local Cache
  250. // Cache key: "action:key" (value is harder to cache due to constraints, but if value is empty/read, we can cache)
  251. // For writes with value constraints, caching is risky unless we include value in cache key or don't cache constraint checks.
  252. // For READS (action="read"), value is empty, so we can cache.
  253. // For WRITES without value (Del), or simple sets, we can cache if no constraints.
  254. // Let's safe cache only for Read or if we verify constraint logic is stable.
  255. // To be safe and simple: Cache the result of (key, action). If constraints exist, the checkPerms function will fail if value invalid.
  256. // But if we cache "true", we skip checkPerms.
  257. // So we can only cache if the permission granted did NOT depend on value constraints.
  258. // That's complex.
  259. // Simplified: Cache only "read" and "admin" actions?
  260. cacheKey := action + ":" + key
  261. if action == ActionRead {
  262. if val, hit := session.permCache.Load(cacheKey); hit {
  263. if allowed, ok := val.(bool); ok {
  264. if allowed {
  265. return nil
  266. } else {
  267. return fmt.Errorf("permission denied (cached)")
  268. }
  269. }
  270. }
  271. }
  272. am.mu.RLock()
  273. user, userOk := am.users[session.Username]
  274. am.mu.RUnlock()
  275. if !userOk {
  276. return fmt.Errorf("user not found")
  277. }
  278. err := am.checkUserPermission(user, key, action, value)
  279. // Update Cache for Read
  280. if action == ActionRead {
  281. session.permCache.Store(cacheKey, err == nil)
  282. }
  283. return err
  284. }
  285. func (am *AuthManager) checkUserPermission(user *User, key, action, value string) error {
  286. // 1. Check Deny Permissions (User level)
  287. for _, perm := range user.DenyPermissions {
  288. if matchKey(perm.KeyPattern, key) && hasAction(perm.Actions, action) {
  289. return fmt.Errorf("permission denied (explicit deny)")
  290. }
  291. }
  292. // 2. Check Allow Permissions (User level)
  293. if checkPerms(user.AllowPermissions, key, action, value) {
  294. return nil
  295. }
  296. // 3. Check Roles
  297. for _, roleName := range user.Roles {
  298. if am.checkRole(roleName, key, action, value, make(map[string]bool)) {
  299. return nil
  300. }
  301. }
  302. return fmt.Errorf("permission denied")
  303. }
  304. func (am *AuthManager) checkRole(roleName string, key, action, value string, visited map[string]bool) bool {
  305. if visited[roleName] {
  306. return false
  307. }
  308. visited[roleName] = true
  309. am.mu.RLock()
  310. role, ok := am.roles[roleName]
  311. am.mu.RUnlock()
  312. if !ok {
  313. return false
  314. }
  315. if checkPerms(role.Permissions, key, action, value) {
  316. return true
  317. }
  318. // Check parent roles
  319. for _, parent := range role.ParentRoles {
  320. if am.checkRole(parent, key, action, value, visited) {
  321. return true
  322. }
  323. }
  324. return false
  325. }
  326. func matchKey(pattern, key string) bool {
  327. if pattern == "*" {
  328. return true
  329. }
  330. if pattern == key {
  331. return true
  332. }
  333. // Prefix match: "user.asin" matches "user.asin.china"
  334. if strings.HasSuffix(pattern, "*") {
  335. prefix := strings.TrimSuffix(pattern, "*")
  336. return strings.HasPrefix(key, prefix)
  337. }
  338. // Hierarchy match: pattern "a.b" matches "a.b.c"
  339. if strings.HasPrefix(key, pattern+".") {
  340. return true
  341. }
  342. return false
  343. }
  344. func hasAction(actions []string, target string) bool {
  345. for _, a := range actions {
  346. if a == target || a == "*" {
  347. return true
  348. }
  349. }
  350. return false
  351. }
  352. func checkPerms(perms []Permission, key, action, value string) bool {
  353. for _, perm := range perms {
  354. if matchKey(perm.KeyPattern, key) && hasAction(perm.Actions, action) {
  355. // Check Value Constraints if action is write
  356. if action == ActionWrite && perm.Constraint != nil && value != "" {
  357. // Try to parse value as float
  358. val, err := strconv.ParseFloat(value, 64)
  359. if err == nil {
  360. if perm.Constraint.Min != nil && val < *perm.Constraint.Min {
  361. return false
  362. }
  363. if perm.Constraint.Max != nil && val > *perm.Constraint.Max {
  364. return false
  365. }
  366. } else {
  367. // If value is not a number but constraint exists, what to do?
  368. // Strict mode: fail.
  369. return false
  370. }
  371. }
  372. return true
  373. }
  374. }
  375. return false
  376. }
  377. // Login authenticates a user and returns a token
  378. // Modified: Sessions are stored in RAFT (Cluster Shared)
  379. func (am *AuthManager) Login(username, password, totpCode, ip string) (string, error) {
  380. am.mu.RLock()
  381. if !am.enabled {
  382. am.mu.RUnlock()
  383. return "", fmt.Errorf("auth not enabled")
  384. }
  385. user, ok := am.users[username]
  386. am.mu.RUnlock()
  387. if !ok {
  388. return "", fmt.Errorf("invalid credentials")
  389. }
  390. // Check IP
  391. if len(user.WhitelistIPs) > 0 {
  392. allowed := false
  393. for _, w := range user.WhitelistIPs {
  394. if w == ip {
  395. allowed = true
  396. break
  397. }
  398. }
  399. if !allowed {
  400. return "", fmt.Errorf("ip not allowed")
  401. }
  402. }
  403. if len(user.BlacklistIPs) > 0 {
  404. for _, b := range user.BlacklistIPs {
  405. if b == ip {
  406. return "", fmt.Errorf("ip blacklisted")
  407. }
  408. }
  409. }
  410. // Verify Password
  411. if hashPassword(password, user.Salt) != user.PasswordHash {
  412. return "", fmt.Errorf("invalid credentials")
  413. }
  414. // Verify TOTP
  415. if user.MFAEnabled {
  416. if totpCode == "" {
  417. return "", fmt.Errorf("mfa code required")
  418. }
  419. if !validateTOTP(user.MFASecret, totpCode) {
  420. return "", fmt.Errorf("invalid mfa code")
  421. }
  422. }
  423. // Create Session
  424. token := generateToken()
  425. session := &Session{
  426. Token: token,
  427. Username: username,
  428. LoginIP: ip,
  429. Expiry: time.Now().Add(24 * time.Hour).Unix(),
  430. }
  431. // Store session via Raft (Propose)
  432. data, _ := json.Marshal(session)
  433. if err := am.server.Set(AuthSessionPrefix+token, string(data)); err != nil {
  434. return "", err
  435. }
  436. return token, nil
  437. }
  438. // Logout invalidates a session (Cluster Shared)
  439. func (am *AuthManager) Logout(token string) error {
  440. return am.server.Del(AuthSessionPrefix + token)
  441. }
  442. // GetSession returns session info
  443. func (am *AuthManager) GetSession(token string) (*Session, error) {
  444. am.mu.RLock()
  445. defer am.mu.RUnlock()
  446. if token == "SYSTEM_INTERNAL" {
  447. return &Session{Username: "system"}, nil
  448. }
  449. session, ok := am.sessions[token]
  450. if !ok {
  451. return nil, fmt.Errorf("invalid session")
  452. }
  453. if time.Now().Unix() > session.Expiry {
  454. return nil, fmt.Errorf("session expired")
  455. }
  456. return session, nil
  457. }
  458. // GetUser returns user info (Public for internal use)
  459. func (am *AuthManager) GetUser(username string) (*User, error) {
  460. am.mu.RLock()
  461. defer am.mu.RUnlock()
  462. user, ok := am.users[username]
  463. if !ok {
  464. return nil, fmt.Errorf("user not found")
  465. }
  466. return user, nil
  467. }
  468. // RegisterUser creates a new user
  469. func (am *AuthManager) RegisterUser(username, password string, roles []string) error {
  470. am.mu.RLock()
  471. if _, exists := am.users[username]; exists {
  472. am.mu.RUnlock()
  473. return fmt.Errorf("user already exists")
  474. }
  475. am.mu.RUnlock()
  476. salt := fmt.Sprintf("%d", time.Now().UnixNano()) // Simple salt
  477. user := User{
  478. Username: username,
  479. Salt: salt,
  480. PasswordHash: hashPassword(password, salt),
  481. Roles: roles,
  482. }
  483. data, _ := json.Marshal(user)
  484. // Use SetSync to ensure user is created before returning
  485. return am.server.SetSync(AuthUserPrefix+username, string(data))
  486. }
  487. // ChangePassword updates a user's password
  488. func (am *AuthManager) ChangePassword(username, newPassword string) error {
  489. am.mu.RLock()
  490. user, exists := am.users[username]
  491. am.mu.RUnlock()
  492. if !exists {
  493. return fmt.Errorf("user not found")
  494. }
  495. newUser := *user // Shallow copy to modify
  496. newUser.Salt = fmt.Sprintf("%d", time.Now().UnixNano())
  497. newUser.PasswordHash = hashPassword(newPassword, newUser.Salt)
  498. data, _ := json.Marshal(newUser)
  499. // Use SetSync to ensure password is updated before returning
  500. return am.server.SetSync(AuthUserPrefix+username, string(data))
  501. }
  502. // UpdateUser updates generic fields of a user (including roles)
  503. func (am *AuthManager) UpdateUser(user User) error {
  504. am.mu.RLock()
  505. _, exists := am.users[user.Username]
  506. am.mu.RUnlock()
  507. if !exists {
  508. return fmt.Errorf("user not found")
  509. }
  510. // Ensure we don't overwrite passwordhash/salt blindly if they are empty
  511. // But usually UpdateUser is called with a fully populated user object from GetUser + mods
  512. // So we just save it.
  513. data, _ := json.Marshal(user)
  514. return am.server.SetSync(AuthUserPrefix+user.Username, string(data))
  515. }
  516. // CreateRole creates a new role
  517. func (am *AuthManager) CreateRole(name string) error {
  518. am.mu.RLock()
  519. if _, exists := am.roles[name]; exists {
  520. am.mu.RUnlock()
  521. return fmt.Errorf("role already exists")
  522. }
  523. am.mu.RUnlock()
  524. role := Role{Name: name}
  525. data, _ := json.Marshal(role)
  526. return am.server.SetSync(AuthRolePrefix+name, string(data))
  527. }
  528. // DeleteRole deletes a role
  529. func (am *AuthManager) DeleteRole(name string) error {
  530. am.mu.RLock()
  531. if _, exists := am.roles[name]; !exists {
  532. am.mu.RUnlock()
  533. return fmt.Errorf("role not found")
  534. }
  535. am.mu.RUnlock()
  536. return am.server.DelSync(AuthRolePrefix + name)
  537. }
  538. // UpdateRole updates an existing role
  539. func (am *AuthManager) UpdateRole(role Role) error {
  540. am.mu.RLock()
  541. if _, exists := am.roles[role.Name]; !exists {
  542. am.mu.RUnlock()
  543. return fmt.Errorf("role not found")
  544. }
  545. am.mu.RUnlock()
  546. data, _ := json.Marshal(role)
  547. return am.server.SetSync(AuthRolePrefix+role.Name, string(data))
  548. }
  549. // GetRole returns a role definition
  550. func (am *AuthManager) GetRole(name string) (*Role, error) {
  551. am.mu.RLock()
  552. defer am.mu.RUnlock()
  553. role, ok := am.roles[name]
  554. if !ok {
  555. return nil, fmt.Errorf("role not found")
  556. }
  557. return role, nil
  558. }
  559. // ListUsers lists all users
  560. func (am *AuthManager) ListUsers() []*User {
  561. am.mu.RLock()
  562. defer am.mu.RUnlock()
  563. users := make([]*User, 0, len(am.users))
  564. for _, u := range am.users {
  565. users = append(users, u)
  566. }
  567. return users
  568. }
  569. // ListRoles lists all roles
  570. func (am *AuthManager) ListRoles() []*Role {
  571. am.mu.RLock()
  572. defer am.mu.RUnlock()
  573. roles := make([]*Role, 0, len(am.roles))
  574. for _, r := range am.roles {
  575. roles = append(roles, r)
  576. }
  577. return roles
  578. }
  579. // HasFullAccess checks if the user has "*" permission on all keys (superuser)
  580. // allowing optimizations like pushing limits to DB engine.
  581. func (am *AuthManager) HasFullAccess(token string) bool {
  582. am.mu.RLock()
  583. defer am.mu.RUnlock()
  584. if !am.enabled {
  585. return true
  586. }
  587. if token == "SYSTEM_INTERNAL" {
  588. return true
  589. }
  590. session, ok := am.sessions[token]
  591. if !ok || time.Now().Unix() > session.Expiry {
  592. return false
  593. }
  594. user, ok := am.users[session.Username]
  595. if !ok {
  596. return false
  597. }
  598. // Must not have any deny permissions that could block "*"
  599. // Actually if Deny is empty, and Allow has "*", it's full access.
  600. // If Deny has something, we can't assume full access blindly.
  601. if len(user.DenyPermissions) > 0 {
  602. return false
  603. }
  604. // Check Allow
  605. for _, perm := range user.AllowPermissions {
  606. if perm.KeyPattern == "*" && hasAction(perm.Actions, "*") {
  607. return true
  608. }
  609. }
  610. // Check Roles
  611. // This is recursive, so we might skip deeply checking roles for optimization simplicity
  612. // and only support direct "*" assignment for this optimization.
  613. // Or we can quickly check if any role has "*"
  614. for _, roleName := range user.Roles {
  615. if am.checkRoleFullAccess(roleName, make(map[string]bool)) {
  616. return true
  617. }
  618. }
  619. return false
  620. }
  621. func (am *AuthManager) checkRoleFullAccess(roleName string, visited map[string]bool) bool {
  622. if visited[roleName] {
  623. return false
  624. }
  625. visited[roleName] = true
  626. role, ok := am.roles[roleName]
  627. if !ok {
  628. return false
  629. }
  630. for _, perm := range role.Permissions {
  631. if perm.KeyPattern == "*" && hasAction(perm.Actions, "*") {
  632. return true
  633. }
  634. }
  635. for _, parent := range role.ParentRoles {
  636. if am.checkRoleFullAccess(parent, visited) {
  637. return true
  638. }
  639. }
  640. return false
  641. }
  642. // Admin helpers to bootstrap
  643. func (am *AuthManager) CreateRootUser(password string) error {
  644. salt := "somesalt" // In production use random
  645. user := User{
  646. Username: "root",
  647. Salt: salt,
  648. PasswordHash: hashPassword(password, salt),
  649. AllowPermissions: []Permission{
  650. {KeyPattern: "*", Actions: []string{"*"}},
  651. },
  652. }
  653. data, _ := json.Marshal(user)
  654. return am.server.Set(AuthUserPrefix+"root", string(data))
  655. }
  656. func (am *AuthManager) EnableAuth() error {
  657. config := AuthConfig{Enabled: true}
  658. data, _ := json.Marshal(config)
  659. return am.server.Set(AuthConfigKey, string(data))
  660. }
  661. func (am *AuthManager) DisableAuth() error {
  662. // Only admin can do this via normal SetAuthenticated
  663. config := AuthConfig{Enabled: false}
  664. data, _ := json.Marshal(config)
  665. return am.server.Set(AuthConfigKey, string(data))
  666. }
  667. // LoadFromDB loads auth data from existing DB
  668. func (am *AuthManager) LoadFromDB() error {
  669. prefix := SystemKeyPrefix
  670. // We use the DB engine's index to find all system keys
  671. am.server.DB.Index.WalkPrefix(prefix, func(key string, entry db.IndexEntry) bool {
  672. // Read value from storage
  673. // We need to access Storage via Engine.
  674. // Engine.Storage is exported.
  675. val, err := am.server.DB.Storage.ReadValue(entry.ValueOffset)
  676. if err != nil {
  677. // Skip corrupted or missing values
  678. return true
  679. }
  680. // Update Cache
  681. // Note: We are essentially replaying the state into the cache
  682. am.UpdateCache(key, val, false)
  683. return true
  684. })
  685. return nil
  686. }