auth.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  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. }
  171. }
  172. return
  173. }
  174. if strings.HasPrefix(key, AuthRolePrefix) {
  175. rolename := strings.TrimPrefix(key, AuthRolePrefix)
  176. if isDelete {
  177. delete(am.roles, rolename)
  178. } else {
  179. var role Role
  180. if err := json.Unmarshal([]byte(value), &role); err == nil {
  181. am.roles[rolename] = &role
  182. }
  183. }
  184. return
  185. }
  186. // Note: AuthSessionPrefix is no longer handled here because sessions are local only.
  187. if strings.HasPrefix(key, AuthSessionPrefix) {
  188. token := strings.TrimPrefix(key, AuthSessionPrefix)
  189. if isDelete {
  190. delete(am.sessions, token)
  191. } else {
  192. var session Session
  193. if err := json.Unmarshal([]byte(value), &session); err == nil {
  194. // Check expiry (though normally we'd replicate delete on expiry, but follower can check too)
  195. if time.Now().Unix() > session.Expiry {
  196. delete(am.sessions, token)
  197. } else {
  198. am.sessions[token] = &session
  199. }
  200. }
  201. }
  202. return
  203. }
  204. // Invalidate permission cache on any auth change (Users, Roles, or Sessions changed)
  205. // Even though session changes are frequent, for safety/simplicity we can clear cache.
  206. // But optimizing: Session change only affects THAT session.
  207. // User/Role change affects potentially all sessions.
  208. // Let's clear cache if User/Role changed.
  209. // If Session changed (added/removed), CheckPermission will hit/miss am.sessions map anyway.
  210. // So we don't strictly need to clear permCache for session changes unless we cache existence.
  211. // We cache (token:key:action -> result).
  212. // If session is deleted, we should clear its cache entries?
  213. // The sync.Map doesn't support easy clearing by pattern.
  214. // Given we want High Performance for search (loops), cache is useful.
  215. // But if we use "Cluster Shared Session", updates come via Raft.
  216. // Let's just clear everything on User/Role update.
  217. // For Session update, we don't clear global cache, relying on GetSession check in CheckPermission.
  218. }
  219. // IsEnabled checks if auth is enabled
  220. func (am *AuthManager) IsEnabled() bool {
  221. am.mu.RLock()
  222. defer am.mu.RUnlock()
  223. return am.enabled
  224. }
  225. // CheckPermission checks if a user has permission to perform an action on a key
  226. func (am *AuthManager) CheckPermission(token string, key string, action string, value string) error {
  227. am.mu.RLock()
  228. enabled := am.enabled
  229. am.mu.RUnlock()
  230. if !enabled {
  231. return nil
  232. }
  233. // Internal system bypass
  234. if token == "SYSTEM_INTERNAL" {
  235. return nil
  236. }
  237. am.mu.RLock()
  238. session, ok := am.sessions[token]
  239. am.mu.RUnlock()
  240. if !ok {
  241. return fmt.Errorf("invalid or expired session")
  242. }
  243. if time.Now().Unix() > session.Expiry {
  244. return fmt.Errorf("session expired")
  245. }
  246. // Check Session Local Cache
  247. // Cache key: "action:key" (value is harder to cache due to constraints, but if value is empty/read, we can cache)
  248. // For writes with value constraints, caching is risky unless we include value in cache key or don't cache constraint checks.
  249. // For READS (action="read"), value is empty, so we can cache.
  250. // For WRITES without value (Del), or simple sets, we can cache if no constraints.
  251. // Let's safe cache only for Read or if we verify constraint logic is stable.
  252. // To be safe and simple: Cache the result of (key, action). If constraints exist, the checkPerms function will fail if value invalid.
  253. // But if we cache "true", we skip checkPerms.
  254. // So we can only cache if the permission granted did NOT depend on value constraints.
  255. // That's complex.
  256. // Simplified: Cache only "read" and "admin" actions?
  257. cacheKey := action + ":" + key
  258. if action == ActionRead {
  259. if val, hit := session.permCache.Load(cacheKey); hit {
  260. if allowed, ok := val.(bool); ok {
  261. if allowed {
  262. return nil
  263. } else {
  264. return fmt.Errorf("permission denied (cached)")
  265. }
  266. }
  267. }
  268. }
  269. am.mu.RLock()
  270. user, userOk := am.users[session.Username]
  271. am.mu.RUnlock()
  272. if !userOk {
  273. return fmt.Errorf("user not found")
  274. }
  275. err := am.checkUserPermission(user, key, action, value)
  276. // Update Cache for Read
  277. if action == ActionRead {
  278. session.permCache.Store(cacheKey, err == nil)
  279. }
  280. return err
  281. }
  282. func (am *AuthManager) checkUserPermission(user *User, key, action, value string) error {
  283. // 1. Check Deny Permissions (User level)
  284. for _, perm := range user.DenyPermissions {
  285. if matchKey(perm.KeyPattern, key) && hasAction(perm.Actions, action) {
  286. return fmt.Errorf("permission denied (explicit deny)")
  287. }
  288. }
  289. // 2. Check Allow Permissions (User level)
  290. if checkPerms(user.AllowPermissions, key, action, value) {
  291. return nil
  292. }
  293. // 3. Check Roles
  294. for _, roleName := range user.Roles {
  295. if am.checkRole(roleName, key, action, value, make(map[string]bool)) {
  296. return nil
  297. }
  298. }
  299. return fmt.Errorf("permission denied")
  300. }
  301. func (am *AuthManager) checkRole(roleName string, key, action, value string, visited map[string]bool) bool {
  302. if visited[roleName] {
  303. return false
  304. }
  305. visited[roleName] = true
  306. am.mu.RLock()
  307. role, ok := am.roles[roleName]
  308. am.mu.RUnlock()
  309. if !ok {
  310. return false
  311. }
  312. if checkPerms(role.Permissions, key, action, value) {
  313. return true
  314. }
  315. // Check parent roles
  316. for _, parent := range role.ParentRoles {
  317. if am.checkRole(parent, key, action, value, visited) {
  318. return true
  319. }
  320. }
  321. return false
  322. }
  323. func matchKey(pattern, key string) bool {
  324. if pattern == "*" {
  325. return true
  326. }
  327. if pattern == key {
  328. return true
  329. }
  330. // Prefix match: "user.asin" matches "user.asin.china"
  331. if strings.HasSuffix(pattern, "*") {
  332. prefix := strings.TrimSuffix(pattern, "*")
  333. return strings.HasPrefix(key, prefix)
  334. }
  335. // Hierarchy match: pattern "a.b" matches "a.b.c"
  336. if strings.HasPrefix(key, pattern+".") {
  337. return true
  338. }
  339. return false
  340. }
  341. func hasAction(actions []string, target string) bool {
  342. for _, a := range actions {
  343. if a == target || a == "*" {
  344. return true
  345. }
  346. }
  347. return false
  348. }
  349. func checkPerms(perms []Permission, key, action, value string) bool {
  350. for _, perm := range perms {
  351. if matchKey(perm.KeyPattern, key) && hasAction(perm.Actions, action) {
  352. // Check Value Constraints if action is write
  353. if action == ActionWrite && perm.Constraint != nil && value != "" {
  354. // Try to parse value as float
  355. val, err := strconv.ParseFloat(value, 64)
  356. if err == nil {
  357. if perm.Constraint.Min != nil && val < *perm.Constraint.Min {
  358. return false
  359. }
  360. if perm.Constraint.Max != nil && val > *perm.Constraint.Max {
  361. return false
  362. }
  363. } else {
  364. // If value is not a number but constraint exists, what to do?
  365. // Strict mode: fail.
  366. return false
  367. }
  368. }
  369. return true
  370. }
  371. }
  372. return false
  373. }
  374. // Login authenticates a user and returns a token
  375. // Modified: Sessions are stored in RAFT (Cluster Shared)
  376. func (am *AuthManager) Login(username, password, totpCode, ip string) (string, error) {
  377. am.mu.RLock()
  378. if !am.enabled {
  379. am.mu.RUnlock()
  380. return "", fmt.Errorf("auth not enabled")
  381. }
  382. user, ok := am.users[username]
  383. am.mu.RUnlock()
  384. if !ok {
  385. return "", fmt.Errorf("invalid credentials")
  386. }
  387. // Check IP
  388. if len(user.WhitelistIPs) > 0 {
  389. allowed := false
  390. for _, w := range user.WhitelistIPs {
  391. if w == ip {
  392. allowed = true
  393. break
  394. }
  395. }
  396. if !allowed {
  397. return "", fmt.Errorf("ip not allowed")
  398. }
  399. }
  400. if len(user.BlacklistIPs) > 0 {
  401. for _, b := range user.BlacklistIPs {
  402. if b == ip {
  403. return "", fmt.Errorf("ip blacklisted")
  404. }
  405. }
  406. }
  407. // Verify Password
  408. if hashPassword(password, user.Salt) != user.PasswordHash {
  409. return "", fmt.Errorf("invalid credentials")
  410. }
  411. // Verify TOTP
  412. if user.MFAEnabled {
  413. if totpCode == "" {
  414. return "", fmt.Errorf("mfa code required")
  415. }
  416. if !validateTOTP(user.MFASecret, totpCode) {
  417. return "", fmt.Errorf("invalid mfa code")
  418. }
  419. }
  420. // Create Session
  421. token := generateToken()
  422. session := &Session{
  423. Token: token,
  424. Username: username,
  425. LoginIP: ip,
  426. Expiry: time.Now().Add(24 * time.Hour).Unix(),
  427. }
  428. // Store session via Raft (Propose)
  429. data, _ := json.Marshal(session)
  430. if err := am.server.Set(AuthSessionPrefix+token, string(data)); err != nil {
  431. return "", err
  432. }
  433. return token, nil
  434. }
  435. // Logout invalidates a session (Cluster Shared)
  436. func (am *AuthManager) Logout(token string) error {
  437. return am.server.Del(AuthSessionPrefix + token)
  438. }
  439. // GetSession returns session info
  440. func (am *AuthManager) GetSession(token string) (*Session, error) {
  441. am.mu.RLock()
  442. defer am.mu.RUnlock()
  443. if token == "SYSTEM_INTERNAL" {
  444. return &Session{Username: "system"}, nil
  445. }
  446. session, ok := am.sessions[token]
  447. if !ok {
  448. return nil, fmt.Errorf("invalid session")
  449. }
  450. if time.Now().Unix() > session.Expiry {
  451. return nil, fmt.Errorf("session expired")
  452. }
  453. return session, nil
  454. }
  455. // HasFullAccess checks if the user has "*" permission on all keys (superuser)
  456. // allowing optimizations like pushing limits to DB engine.
  457. func (am *AuthManager) HasFullAccess(token string) bool {
  458. am.mu.RLock()
  459. defer am.mu.RUnlock()
  460. if !am.enabled {
  461. return true
  462. }
  463. if token == "SYSTEM_INTERNAL" {
  464. return true
  465. }
  466. session, ok := am.sessions[token]
  467. if !ok || time.Now().Unix() > session.Expiry {
  468. return false
  469. }
  470. user, ok := am.users[session.Username]
  471. if !ok {
  472. return false
  473. }
  474. // Must not have any deny permissions that could block "*"
  475. // Actually if Deny is empty, and Allow has "*", it's full access.
  476. // If Deny has something, we can't assume full access blindly.
  477. if len(user.DenyPermissions) > 0 {
  478. return false
  479. }
  480. // Check Allow
  481. for _, perm := range user.AllowPermissions {
  482. if perm.KeyPattern == "*" && hasAction(perm.Actions, "*") {
  483. return true
  484. }
  485. }
  486. // Check Roles
  487. // This is recursive, so we might skip deeply checking roles for optimization simplicity
  488. // and only support direct "*" assignment for this optimization.
  489. // Or we can quickly check if any role has "*"
  490. for _, roleName := range user.Roles {
  491. if am.checkRoleFullAccess(roleName, make(map[string]bool)) {
  492. return true
  493. }
  494. }
  495. return false
  496. }
  497. func (am *AuthManager) checkRoleFullAccess(roleName string, visited map[string]bool) bool {
  498. if visited[roleName] {
  499. return false
  500. }
  501. visited[roleName] = true
  502. role, ok := am.roles[roleName]
  503. if !ok {
  504. return false
  505. }
  506. for _, perm := range role.Permissions {
  507. if perm.KeyPattern == "*" && hasAction(perm.Actions, "*") {
  508. return true
  509. }
  510. }
  511. for _, parent := range role.ParentRoles {
  512. if am.checkRoleFullAccess(parent, visited) {
  513. return true
  514. }
  515. }
  516. return false
  517. }
  518. // Admin helpers to bootstrap
  519. func (am *AuthManager) CreateRootUser(password string) error {
  520. salt := "somesalt" // In production use random
  521. user := User{
  522. Username: "root",
  523. Salt: salt,
  524. PasswordHash: hashPassword(password, salt),
  525. AllowPermissions: []Permission{
  526. {KeyPattern: "*", Actions: []string{"*"}},
  527. },
  528. }
  529. data, _ := json.Marshal(user)
  530. return am.server.Set(AuthUserPrefix+"root", string(data))
  531. }
  532. func (am *AuthManager) EnableAuth() error {
  533. config := AuthConfig{Enabled: true}
  534. data, _ := json.Marshal(config)
  535. return am.server.Set(AuthConfigKey, string(data))
  536. }
  537. func (am *AuthManager) DisableAuth() error {
  538. // Only admin can do this via normal SetAuthenticated
  539. config := AuthConfig{Enabled: false}
  540. data, _ := json.Marshal(config)
  541. return am.server.Set(AuthConfigKey, string(data))
  542. }
  543. // LoadFromDB loads auth data from existing DB
  544. func (am *AuthManager) LoadFromDB() error {
  545. prefix := SystemKeyPrefix
  546. // We use the DB engine's index to find all system keys
  547. am.server.DB.Index.WalkPrefix(prefix, func(key string, entry db.IndexEntry) bool {
  548. // Read value from storage
  549. // We need to access Storage via Engine.
  550. // Engine.Storage is exported.
  551. val, err := am.server.DB.Storage.ReadValue(entry.ValueOffset)
  552. if err != nil {
  553. // Skip corrupted or missing values
  554. return true
  555. }
  556. // Update Cache
  557. // Note: We are essentially replaying the state into the cache
  558. am.UpdateCache(key, val, false)
  559. return true
  560. })
  561. return nil
  562. }