auth_sqlite.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. package auth
  2. import (
  3. "database/sql"
  4. "errors"
  5. "fmt"
  6. _ "github.com/mattn/go-sqlite3" // SQLite driver
  7. "golang.org/x/crypto/bcrypt"
  8. "strings"
  9. )
  10. const (
  11. bcryptCost = 10
  12. intentionalSlowDownHash = "$2a$10$YFCQvqQDwIIwnJM1xkAYOeih0dg17UVGanaTStnrSzC8NCWxcLDwy" // Cost should match bcryptCost
  13. )
  14. // Auther-related queries
  15. const (
  16. createAuthTablesQueries = `
  17. BEGIN;
  18. CREATE TABLE IF NOT EXISTS user (
  19. user TEXT NOT NULL PRIMARY KEY,
  20. pass TEXT NOT NULL,
  21. role TEXT NOT NULL
  22. );
  23. CREATE TABLE IF NOT EXISTS access (
  24. user TEXT NOT NULL,
  25. topic TEXT NOT NULL,
  26. read INT NOT NULL,
  27. write INT NOT NULL,
  28. PRIMARY KEY (topic, user)
  29. );
  30. CREATE TABLE IF NOT EXISTS schemaVersion (
  31. id INT PRIMARY KEY,
  32. version INT NOT NULL
  33. );
  34. COMMIT;
  35. `
  36. selectUserQuery = `SELECT pass, role FROM user WHERE user = ?`
  37. selectTopicPermsQuery = `
  38. SELECT read, write
  39. FROM access
  40. WHERE user IN ('*', ?) AND ? LIKE topic
  41. ORDER BY user DESC
  42. `
  43. )
  44. // Manager-related queries
  45. const (
  46. insertUserQuery = `INSERT INTO user (user, pass, role) VALUES (?, ?, ?)`
  47. selectUsernamesQuery = `SELECT user FROM user ORDER BY role, user`
  48. updateUserPassQuery = `UPDATE user SET pass = ? WHERE user = ?`
  49. updateUserRoleQuery = `UPDATE user SET role = ? WHERE user = ?`
  50. deleteUserQuery = `DELETE FROM user WHERE user = ?`
  51. upsertUserAccessQuery = `
  52. INSERT INTO access (user, topic, read, write)
  53. VALUES (?, ?, ?, ?)
  54. ON CONFLICT (user, topic) DO UPDATE SET read=excluded.read, write=excluded.write
  55. `
  56. selectUserAccessQuery = `SELECT topic, read, write FROM access WHERE user = ?`
  57. deleteAllAccessQuery = `DELETE FROM access`
  58. deleteUserAccessQuery = `DELETE FROM access WHERE user = ?`
  59. deleteTopicAccessQuery = `DELETE FROM access WHERE user = ? AND topic = ?`
  60. )
  61. // Schema management queries
  62. const (
  63. currentSchemaVersion = 1
  64. insertSchemaVersion = `INSERT INTO schemaVersion VALUES (1, ?)`
  65. selectSchemaVersionQuery = `SELECT version FROM schemaVersion WHERE id = 1`
  66. )
  67. // SQLiteAuth is an implementation of Auther and Manager. It stores users and access control list
  68. // in a SQLite database.
  69. type SQLiteAuth struct {
  70. db *sql.DB
  71. defaultRead bool
  72. defaultWrite bool
  73. }
  74. var _ Auther = (*SQLiteAuth)(nil)
  75. var _ Manager = (*SQLiteAuth)(nil)
  76. // NewSQLiteAuth creates a new SQLiteAuth instance
  77. func NewSQLiteAuth(filename string, defaultRead, defaultWrite bool) (*SQLiteAuth, error) {
  78. db, err := sql.Open("sqlite3", filename)
  79. if err != nil {
  80. return nil, err
  81. }
  82. if err := setupAuthDB(db); err != nil {
  83. return nil, err
  84. }
  85. return &SQLiteAuth{
  86. db: db,
  87. defaultRead: defaultRead,
  88. defaultWrite: defaultWrite,
  89. }, nil
  90. }
  91. // Authenticate checks username and password and returns a user if correct. The method
  92. // returns in constant-ish time, regardless of whether the user exists or the password is
  93. // correct or incorrect.
  94. func (a *SQLiteAuth) Authenticate(username, password string) (*User, error) {
  95. if username == Everyone {
  96. return nil, ErrUnauthenticated
  97. }
  98. user, err := a.User(username)
  99. if err != nil {
  100. bcrypt.CompareHashAndPassword([]byte(intentionalSlowDownHash),
  101. []byte("intentional slow-down to avoid timing attacks"))
  102. return nil, ErrUnauthenticated
  103. }
  104. if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password)); err != nil {
  105. return nil, ErrUnauthenticated
  106. }
  107. return user, nil
  108. }
  109. // Authorize returns nil if the given user has access to the given topic using the desired
  110. // permission. The user param may be nil to signal an anonymous user.
  111. func (a *SQLiteAuth) Authorize(user *User, topic string, perm Permission) error {
  112. if user != nil && user.Role == RoleAdmin {
  113. return nil // Admin can do everything
  114. }
  115. username := Everyone
  116. if user != nil {
  117. username = user.Name
  118. }
  119. // Select the read/write permissions for this user/topic combo. The query may return two
  120. // rows (one for everyone, and one for the user), but prioritizes the user. The value for
  121. // user.Name may be empty (= everyone).
  122. rows, err := a.db.Query(selectTopicPermsQuery, username, topic)
  123. if err != nil {
  124. return err
  125. }
  126. defer rows.Close()
  127. if !rows.Next() {
  128. return a.resolvePerms(a.defaultRead, a.defaultWrite, perm)
  129. }
  130. var read, write bool
  131. if err := rows.Scan(&read, &write); err != nil {
  132. return err
  133. } else if err := rows.Err(); err != nil {
  134. return err
  135. }
  136. return a.resolvePerms(read, write, perm)
  137. }
  138. func (a *SQLiteAuth) resolvePerms(read, write bool, perm Permission) error {
  139. if perm == PermissionRead && read {
  140. return nil
  141. } else if perm == PermissionWrite && write {
  142. return nil
  143. }
  144. return ErrUnauthorized
  145. }
  146. // AddUser adds a user with the given username, password and role. The password should be hashed
  147. // before it is stored in a persistence layer.
  148. func (a *SQLiteAuth) AddUser(username, password string, role Role) error {
  149. if !AllowedUsername(username) || !AllowedRole(role) {
  150. return ErrInvalidArgument
  151. }
  152. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
  153. if err != nil {
  154. return err
  155. }
  156. if _, err = a.db.Exec(insertUserQuery, username, hash, role); err != nil {
  157. return err
  158. }
  159. return nil
  160. }
  161. // RemoveUser deletes the user with the given username. The function returns nil on success, even
  162. // if the user did not exist in the first place.
  163. func (a *SQLiteAuth) RemoveUser(username string) error {
  164. if !AllowedUsername(username) {
  165. return ErrInvalidArgument
  166. }
  167. if _, err := a.db.Exec(deleteUserQuery, username); err != nil {
  168. return err
  169. }
  170. if _, err := a.db.Exec(deleteUserAccessQuery, username); err != nil {
  171. return err
  172. }
  173. return nil
  174. }
  175. // Users returns a list of users. It always also returns the Everyone user ("*").
  176. func (a *SQLiteAuth) Users() ([]*User, error) {
  177. rows, err := a.db.Query(selectUsernamesQuery)
  178. if err != nil {
  179. return nil, err
  180. }
  181. defer rows.Close()
  182. usernames := make([]string, 0)
  183. for rows.Next() {
  184. var username string
  185. if err := rows.Scan(&username); err != nil {
  186. return nil, err
  187. } else if err := rows.Err(); err != nil {
  188. return nil, err
  189. }
  190. usernames = append(usernames, username)
  191. }
  192. rows.Close()
  193. users := make([]*User, 0)
  194. for _, username := range usernames {
  195. user, err := a.User(username)
  196. if err != nil {
  197. return nil, err
  198. }
  199. users = append(users, user)
  200. }
  201. everyone, err := a.everyoneUser()
  202. if err != nil {
  203. return nil, err
  204. }
  205. users = append(users, everyone)
  206. return users, nil
  207. }
  208. // User returns the user with the given username if it exists, or ErrNotFound otherwise.
  209. // You may also pass Everyone to retrieve the anonymous user and its Grant list.
  210. func (a *SQLiteAuth) User(username string) (*User, error) {
  211. if username == Everyone {
  212. return a.everyoneUser()
  213. }
  214. rows, err := a.db.Query(selectUserQuery, username)
  215. if err != nil {
  216. return nil, err
  217. }
  218. defer rows.Close()
  219. var hash, role string
  220. if !rows.Next() {
  221. return nil, ErrNotFound
  222. }
  223. if err := rows.Scan(&hash, &role); err != nil {
  224. return nil, err
  225. } else if err := rows.Err(); err != nil {
  226. return nil, err
  227. }
  228. grants, err := a.readGrants(username)
  229. if err != nil {
  230. return nil, err
  231. }
  232. return &User{
  233. Name: username,
  234. Hash: hash,
  235. Role: Role(role),
  236. Grants: grants,
  237. }, nil
  238. }
  239. func (a *SQLiteAuth) everyoneUser() (*User, error) {
  240. grants, err := a.readGrants(Everyone)
  241. if err != nil {
  242. return nil, err
  243. }
  244. return &User{
  245. Name: Everyone,
  246. Hash: "",
  247. Role: RoleAnonymous,
  248. Grants: grants,
  249. }, nil
  250. }
  251. func (a *SQLiteAuth) readGrants(username string) ([]Grant, error) {
  252. rows, err := a.db.Query(selectUserAccessQuery, username)
  253. if err != nil {
  254. return nil, err
  255. }
  256. defer rows.Close()
  257. grants := make([]Grant, 0)
  258. for rows.Next() {
  259. var topic string
  260. var read, write bool
  261. if err := rows.Scan(&topic, &read, &write); err != nil {
  262. return nil, err
  263. } else if err := rows.Err(); err != nil {
  264. return nil, err
  265. }
  266. grants = append(grants, Grant{
  267. TopicPattern: fromSQLWildcard(topic),
  268. AllowRead: read,
  269. AllowWrite: write,
  270. })
  271. }
  272. return grants, nil
  273. }
  274. // ChangePassword changes a user's password
  275. func (a *SQLiteAuth) ChangePassword(username, password string) error {
  276. hash, err := bcrypt.GenerateFromPassword([]byte(password), bcryptCost)
  277. if err != nil {
  278. return err
  279. }
  280. if _, err := a.db.Exec(updateUserPassQuery, hash, username); err != nil {
  281. return err
  282. }
  283. return nil
  284. }
  285. // ChangeRole changes a user's role. When a role is changed from RoleUser to RoleAdmin,
  286. // all existing access control entries (Grant) are removed, since they are no longer needed.
  287. func (a *SQLiteAuth) ChangeRole(username string, role Role) error {
  288. if !AllowedUsername(username) || !AllowedRole(role) {
  289. return ErrInvalidArgument
  290. }
  291. if _, err := a.db.Exec(updateUserRoleQuery, string(role), username); err != nil {
  292. return err
  293. }
  294. if role == RoleAdmin {
  295. if _, err := a.db.Exec(deleteUserAccessQuery, username); err != nil {
  296. return err
  297. }
  298. }
  299. return nil
  300. }
  301. // AllowAccess adds or updates an entry in th access control list for a specific user. It controls
  302. // read/write access to a topic. The parameter topicPattern may include wildcards (*).
  303. func (a *SQLiteAuth) AllowAccess(username string, topicPattern string, read bool, write bool) error {
  304. if (!AllowedUsername(username) && username != Everyone) || !AllowedTopicPattern(topicPattern) {
  305. return ErrInvalidArgument
  306. }
  307. if _, err := a.db.Exec(upsertUserAccessQuery, username, toSQLWildcard(topicPattern), read, write); err != nil {
  308. return err
  309. }
  310. return nil
  311. }
  312. // ResetAccess removes an access control list entry for a specific username/topic, or (if topic is
  313. // empty) for an entire user. The parameter topicPattern may include wildcards (*).
  314. func (a *SQLiteAuth) ResetAccess(username string, topicPattern string) error {
  315. if !AllowedUsername(username) && username != Everyone && username != "" {
  316. return ErrInvalidArgument
  317. } else if !AllowedTopicPattern(topicPattern) && topicPattern != "" {
  318. return ErrInvalidArgument
  319. }
  320. if username == "" && topicPattern == "" {
  321. _, err := a.db.Exec(deleteAllAccessQuery, username)
  322. return err
  323. } else if topicPattern == "" {
  324. _, err := a.db.Exec(deleteUserAccessQuery, username)
  325. return err
  326. }
  327. _, err := a.db.Exec(deleteTopicAccessQuery, username, toSQLWildcard(topicPattern))
  328. return err
  329. }
  330. // DefaultAccess returns the default read/write access if no access control entry matches
  331. func (a *SQLiteAuth) DefaultAccess() (read bool, write bool) {
  332. return a.defaultRead, a.defaultWrite
  333. }
  334. func toSQLWildcard(s string) string {
  335. return strings.ReplaceAll(s, "*", "%")
  336. }
  337. func fromSQLWildcard(s string) string {
  338. return strings.ReplaceAll(s, "%", "*")
  339. }
  340. func setupAuthDB(db *sql.DB) error {
  341. // If 'schemaVersion' table does not exist, this must be a new database
  342. rowsSV, err := db.Query(selectSchemaVersionQuery)
  343. if err != nil {
  344. return setupNewAuthDB(db)
  345. }
  346. defer rowsSV.Close()
  347. // If 'schemaVersion' table exists, read version and potentially upgrade
  348. schemaVersion := 0
  349. if !rowsSV.Next() {
  350. return errors.New("cannot determine schema version: database file may be corrupt")
  351. }
  352. if err := rowsSV.Scan(&schemaVersion); err != nil {
  353. return err
  354. }
  355. rowsSV.Close()
  356. // Do migrations
  357. if schemaVersion == currentSchemaVersion {
  358. return nil
  359. }
  360. return fmt.Errorf("unexpected schema version found: %d", schemaVersion)
  361. }
  362. func setupNewAuthDB(db *sql.DB) error {
  363. if _, err := db.Exec(createAuthTablesQueries); err != nil {
  364. return err
  365. }
  366. if _, err := db.Exec(insertSchemaVersion, currentSchemaVersion); err != nil {
  367. return err
  368. }
  369. return nil
  370. }