manager.go 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510
  1. // Package user deals with authentication and authorization against topics
  2. package user
  3. import (
  4. "database/sql"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. _ "github.com/mattn/go-sqlite3" // SQLite driver
  9. "github.com/stripe/stripe-go/v74"
  10. "golang.org/x/crypto/bcrypt"
  11. "heckel.io/ntfy/log"
  12. "heckel.io/ntfy/util"
  13. "net/netip"
  14. "strings"
  15. "sync"
  16. "time"
  17. )
  18. const (
  19. tierIDPrefix = "ti_"
  20. tierIDLength = 8
  21. syncTopicPrefix = "st_"
  22. syncTopicLength = 16
  23. userIDPrefix = "u_"
  24. userIDLength = 12
  25. userAuthIntentionalSlowDownHash = "$2a$10$YFCQvqQDwIIwnJM1xkAYOeih0dg17UVGanaTStnrSzC8NCWxcLDwy" // Cost should match DefaultUserPasswordBcryptCost
  26. userHardDeleteAfterDuration = 7 * 24 * time.Hour
  27. tokenPrefix = "tk_"
  28. tokenLength = 32
  29. tokenMaxCount = 20 // Only keep this many tokens in the table per user
  30. tag = "user_manager"
  31. )
  32. // Default constants that may be overridden by configs
  33. const (
  34. DefaultUserStatsQueueWriterInterval = 33 * time.Second
  35. DefaultUserPasswordBcryptCost = 10
  36. )
  37. var (
  38. errNoTokenProvided = errors.New("no token provided")
  39. errTopicOwnedByOthers = errors.New("topic owned by others")
  40. errNoRows = errors.New("no rows found")
  41. )
  42. // Manager-related queries
  43. const (
  44. createTablesQueries = `
  45. BEGIN;
  46. CREATE TABLE IF NOT EXISTS tier (
  47. id TEXT PRIMARY KEY,
  48. code TEXT NOT NULL,
  49. name TEXT NOT NULL,
  50. messages_limit INT NOT NULL,
  51. messages_expiry_duration INT NOT NULL,
  52. emails_limit INT NOT NULL,
  53. reservations_limit INT NOT NULL,
  54. attachment_file_size_limit INT NOT NULL,
  55. attachment_total_size_limit INT NOT NULL,
  56. attachment_expiry_duration INT NOT NULL,
  57. attachment_bandwidth_limit INT NOT NULL,
  58. stripe_monthly_price_id TEXT,
  59. stripe_yearly_price_id TEXT
  60. );
  61. CREATE UNIQUE INDEX idx_tier_code ON tier (code);
  62. CREATE UNIQUE INDEX idx_tier_stripe_monthly_price_id ON tier (stripe_monthly_price_id);
  63. CREATE UNIQUE INDEX idx_tier_stripe_yearly_price_id ON tier (stripe_yearly_price_id);
  64. CREATE TABLE IF NOT EXISTS user (
  65. id TEXT PRIMARY KEY,
  66. tier_id TEXT,
  67. user TEXT NOT NULL,
  68. pass TEXT NOT NULL,
  69. role TEXT CHECK (role IN ('anonymous', 'admin', 'user')) NOT NULL,
  70. prefs JSON NOT NULL DEFAULT '{}',
  71. sync_topic TEXT NOT NULL,
  72. stats_messages INT NOT NULL DEFAULT (0),
  73. stats_emails INT NOT NULL DEFAULT (0),
  74. stripe_customer_id TEXT,
  75. stripe_subscription_id TEXT,
  76. stripe_subscription_status TEXT,
  77. stripe_subscription_interval TEXT,
  78. stripe_subscription_paid_until INT,
  79. stripe_subscription_cancel_at INT,
  80. created INT NOT NULL,
  81. deleted INT,
  82. FOREIGN KEY (tier_id) REFERENCES tier (id)
  83. );
  84. CREATE UNIQUE INDEX idx_user ON user (user);
  85. CREATE UNIQUE INDEX idx_user_stripe_customer_id ON user (stripe_customer_id);
  86. CREATE UNIQUE INDEX idx_user_stripe_subscription_id ON user (stripe_subscription_id);
  87. CREATE TABLE IF NOT EXISTS user_access (
  88. user_id TEXT NOT NULL,
  89. topic TEXT NOT NULL,
  90. read INT NOT NULL,
  91. write INT NOT NULL,
  92. owner_user_id INT,
  93. PRIMARY KEY (user_id, topic),
  94. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE,
  95. FOREIGN KEY (owner_user_id) REFERENCES user (id) ON DELETE CASCADE
  96. );
  97. CREATE TABLE IF NOT EXISTS user_token (
  98. user_id TEXT NOT NULL,
  99. token TEXT NOT NULL,
  100. label TEXT NOT NULL,
  101. last_access INT NOT NULL,
  102. last_origin TEXT NOT NULL,
  103. expires INT NOT NULL,
  104. PRIMARY KEY (user_id, token),
  105. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
  106. );
  107. CREATE TABLE IF NOT EXISTS schemaVersion (
  108. id INT PRIMARY KEY,
  109. version INT NOT NULL
  110. );
  111. INSERT INTO user (id, user, pass, role, sync_topic, created)
  112. VALUES ('` + everyoneID + `', '*', '', 'anonymous', '', UNIXEPOCH())
  113. ON CONFLICT (id) DO NOTHING;
  114. COMMIT;
  115. `
  116. builtinStartupQueries = `
  117. PRAGMA foreign_keys = ON;
  118. `
  119. selectUserByIDQuery = `
  120. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_interval, u.stripe_subscription_paid_until, u.stripe_subscription_cancel_at, deleted, t.id, t.code, t.name, t.messages_limit, t.messages_expiry_duration, t.emails_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_monthly_price_id, t.stripe_yearly_price_id
  121. FROM user u
  122. LEFT JOIN tier t on t.id = u.tier_id
  123. WHERE u.id = ?
  124. `
  125. selectUserByNameQuery = `
  126. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_interval, u.stripe_subscription_paid_until, u.stripe_subscription_cancel_at, deleted, t.id, t.code, t.name, t.messages_limit, t.messages_expiry_duration, t.emails_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_monthly_price_id, t.stripe_yearly_price_id
  127. FROM user u
  128. LEFT JOIN tier t on t.id = u.tier_id
  129. WHERE user = ?
  130. `
  131. selectUserByTokenQuery = `
  132. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_interval, u.stripe_subscription_paid_until, u.stripe_subscription_cancel_at, deleted, t.id, t.code, t.name, t.messages_limit, t.messages_expiry_duration, t.emails_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_monthly_price_id, t.stripe_yearly_price_id
  133. FROM user u
  134. JOIN user_token tk on u.id = tk.user_id
  135. LEFT JOIN tier t on t.id = u.tier_id
  136. WHERE tk.token = ? AND (tk.expires = 0 OR tk.expires >= ?)
  137. `
  138. selectUserByStripeCustomerIDQuery = `
  139. SELECT u.id, u.user, u.pass, u.role, u.prefs, u.sync_topic, u.stats_messages, u.stats_emails, u.stripe_customer_id, u.stripe_subscription_id, u.stripe_subscription_status, u.stripe_subscription_interval, u.stripe_subscription_paid_until, u.stripe_subscription_cancel_at, deleted, t.id, t.code, t.name, t.messages_limit, t.messages_expiry_duration, t.emails_limit, t.reservations_limit, t.attachment_file_size_limit, t.attachment_total_size_limit, t.attachment_expiry_duration, t.attachment_bandwidth_limit, t.stripe_monthly_price_id, t.stripe_yearly_price_id
  140. FROM user u
  141. LEFT JOIN tier t on t.id = u.tier_id
  142. WHERE u.stripe_customer_id = ?
  143. `
  144. selectTopicPermsQuery = `
  145. SELECT read, write
  146. FROM user_access a
  147. JOIN user u ON u.id = a.user_id
  148. WHERE (u.user = ? OR u.user = ?) AND ? LIKE a.topic
  149. ORDER BY u.user DESC
  150. `
  151. insertUserQuery = `
  152. INSERT INTO user (id, user, pass, role, sync_topic, created)
  153. VALUES (?, ?, ?, ?, ?, ?)
  154. `
  155. selectUsernamesQuery = `
  156. SELECT user
  157. FROM user
  158. ORDER BY
  159. CASE role
  160. WHEN 'admin' THEN 1
  161. WHEN 'anonymous' THEN 3
  162. ELSE 2
  163. END, user
  164. `
  165. selectUserCountQuery = `SELECT COUNT(*) FROM user`
  166. updateUserPassQuery = `UPDATE user SET pass = ? WHERE user = ?`
  167. updateUserRoleQuery = `UPDATE user SET role = ? WHERE user = ?`
  168. updateUserPrefsQuery = `UPDATE user SET prefs = ? WHERE id = ?`
  169. updateUserStatsQuery = `UPDATE user SET stats_messages = ?, stats_emails = ? WHERE id = ?`
  170. updateUserStatsResetAllQuery = `UPDATE user SET stats_messages = 0, stats_emails = 0`
  171. updateUserDeletedQuery = `UPDATE user SET deleted = ? WHERE id = ?`
  172. deleteUsersMarkedQuery = `DELETE FROM user WHERE deleted < ?`
  173. deleteUserQuery = `DELETE FROM user WHERE user = ?`
  174. upsertUserAccessQuery = `
  175. INSERT INTO user_access (user_id, topic, read, write, owner_user_id)
  176. VALUES ((SELECT id FROM user WHERE user = ?), ?, ?, ?, (SELECT IIF(?='',NULL,(SELECT id FROM user WHERE user=?))))
  177. ON CONFLICT (user_id, topic)
  178. DO UPDATE SET read=excluded.read, write=excluded.write, owner_user_id=excluded.owner_user_id
  179. `
  180. selectUserAccessQuery = `
  181. SELECT topic, read, write
  182. FROM user_access
  183. WHERE user_id = (SELECT id FROM user WHERE user = ?)
  184. ORDER BY write DESC, read DESC, topic
  185. `
  186. selectUserReservationsQuery = `
  187. SELECT a_user.topic, a_user.read, a_user.write, a_everyone.read AS everyone_read, a_everyone.write AS everyone_write
  188. FROM user_access a_user
  189. LEFT JOIN user_access a_everyone ON a_user.topic = a_everyone.topic AND a_everyone.user_id = (SELECT id FROM user WHERE user = ?)
  190. WHERE a_user.user_id = a_user.owner_user_id
  191. AND a_user.owner_user_id = (SELECT id FROM user WHERE user = ?)
  192. ORDER BY a_user.topic
  193. `
  194. selectUserReservationsCountQuery = `
  195. SELECT COUNT(*)
  196. FROM user_access
  197. WHERE user_id = owner_user_id
  198. AND owner_user_id = (SELECT id FROM user WHERE user = ?)
  199. `
  200. selectUserReservationsOwnerQuery = `
  201. SELECT owner_user_id
  202. FROM user_access
  203. WHERE topic = ?
  204. AND user_id = owner_user_id
  205. `
  206. selectUserHasReservationQuery = `
  207. SELECT COUNT(*)
  208. FROM user_access
  209. WHERE user_id = owner_user_id
  210. AND owner_user_id = (SELECT id FROM user WHERE user = ?)
  211. AND topic = ?
  212. `
  213. selectOtherAccessCountQuery = `
  214. SELECT COUNT(*)
  215. FROM user_access
  216. WHERE (topic = ? OR ? LIKE topic)
  217. AND (owner_user_id IS NULL OR owner_user_id != (SELECT id FROM user WHERE user = ?))
  218. `
  219. deleteAllAccessQuery = `DELETE FROM user_access`
  220. deleteUserAccessQuery = `
  221. DELETE FROM user_access
  222. WHERE user_id = (SELECT id FROM user WHERE user = ?)
  223. OR owner_user_id = (SELECT id FROM user WHERE user = ?)
  224. `
  225. deleteTopicAccessQuery = `
  226. DELETE FROM user_access
  227. WHERE (user_id = (SELECT id FROM user WHERE user = ?) OR owner_user_id = (SELECT id FROM user WHERE user = ?))
  228. AND topic = ?
  229. `
  230. selectTokenCountQuery = `SELECT COUNT(*) FROM user_token WHERE user_id = ?`
  231. selectTokensQuery = `SELECT token, label, last_access, last_origin, expires FROM user_token WHERE user_id = ?`
  232. selectTokenQuery = `SELECT token, label, last_access, last_origin, expires FROM user_token WHERE user_id = ? AND token = ?`
  233. insertTokenQuery = `INSERT INTO user_token (user_id, token, label, last_access, last_origin, expires) VALUES (?, ?, ?, ?, ?, ?)`
  234. updateTokenExpiryQuery = `UPDATE user_token SET expires = ? WHERE user_id = ? AND token = ?`
  235. updateTokenLabelQuery = `UPDATE user_token SET label = ? WHERE user_id = ? AND token = ?`
  236. updateTokenLastAccessQuery = `UPDATE user_token SET last_access = ?, last_origin = ? WHERE token = ?`
  237. deleteTokenQuery = `DELETE FROM user_token WHERE user_id = ? AND token = ?`
  238. deleteAllTokenQuery = `DELETE FROM user_token WHERE user_id = ?`
  239. deleteExpiredTokensQuery = `DELETE FROM user_token WHERE expires > 0 AND expires < ?`
  240. deleteExcessTokensQuery = `
  241. DELETE FROM user_token
  242. WHERE (user_id, token) NOT IN (
  243. SELECT user_id, token
  244. FROM user_token
  245. WHERE user_id = ?
  246. ORDER BY expires DESC
  247. LIMIT ?
  248. )
  249. `
  250. insertTierQuery = `
  251. INSERT INTO tier (id, code, name, messages_limit, messages_expiry_duration, emails_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id)
  252. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  253. `
  254. updateTierQuery = `
  255. UPDATE tier
  256. SET name = ?, messages_limit = ?, messages_expiry_duration = ?, emails_limit = ?, reservations_limit = ?, attachment_file_size_limit = ?, attachment_total_size_limit = ?, attachment_expiry_duration = ?, attachment_bandwidth_limit = ?, stripe_monthly_price_id = ?, stripe_yearly_price_id = ?
  257. WHERE code = ?
  258. `
  259. selectTiersQuery = `
  260. SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id
  261. FROM tier
  262. `
  263. selectTierByCodeQuery = `
  264. SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id
  265. FROM tier
  266. WHERE code = ?
  267. `
  268. selectTierByPriceIDQuery = `
  269. SELECT id, code, name, messages_limit, messages_expiry_duration, emails_limit, reservations_limit, attachment_file_size_limit, attachment_total_size_limit, attachment_expiry_duration, attachment_bandwidth_limit, stripe_monthly_price_id, stripe_yearly_price_id
  270. FROM tier
  271. WHERE (stripe_monthly_price_id = ? OR stripe_yearly_price_id = ?)
  272. `
  273. updateUserTierQuery = `UPDATE user SET tier_id = (SELECT id FROM tier WHERE code = ?) WHERE user = ?`
  274. deleteUserTierQuery = `UPDATE user SET tier_id = null WHERE user = ?`
  275. deleteTierQuery = `DELETE FROM tier WHERE code = ?`
  276. updateBillingQuery = `
  277. UPDATE user
  278. SET stripe_customer_id = ?, stripe_subscription_id = ?, stripe_subscription_status = ?, stripe_subscription_interval = ?, stripe_subscription_paid_until = ?, stripe_subscription_cancel_at = ?
  279. WHERE user = ?
  280. `
  281. )
  282. // Schema management queries
  283. const (
  284. currentSchemaVersion = 3
  285. insertSchemaVersion = `INSERT INTO schemaVersion VALUES (1, ?)`
  286. updateSchemaVersion = `UPDATE schemaVersion SET version = ? WHERE id = 1`
  287. selectSchemaVersionQuery = `SELECT version FROM schemaVersion WHERE id = 1`
  288. // 1 -> 2 (complex migration!)
  289. migrate1To2CreateTablesQueries = `
  290. ALTER TABLE user RENAME TO user_old;
  291. CREATE TABLE IF NOT EXISTS tier (
  292. id TEXT PRIMARY KEY,
  293. code TEXT NOT NULL,
  294. name TEXT NOT NULL,
  295. messages_limit INT NOT NULL,
  296. messages_expiry_duration INT NOT NULL,
  297. emails_limit INT NOT NULL,
  298. reservations_limit INT NOT NULL,
  299. attachment_file_size_limit INT NOT NULL,
  300. attachment_total_size_limit INT NOT NULL,
  301. attachment_expiry_duration INT NOT NULL,
  302. attachment_bandwidth_limit INT NOT NULL,
  303. stripe_price_id TEXT
  304. );
  305. CREATE UNIQUE INDEX idx_tier_code ON tier (code);
  306. CREATE UNIQUE INDEX idx_tier_price_id ON tier (stripe_price_id);
  307. CREATE TABLE IF NOT EXISTS user (
  308. id TEXT PRIMARY KEY,
  309. tier_id TEXT,
  310. user TEXT NOT NULL,
  311. pass TEXT NOT NULL,
  312. role TEXT CHECK (role IN ('anonymous', 'admin', 'user')) NOT NULL,
  313. prefs JSON NOT NULL DEFAULT '{}',
  314. sync_topic TEXT NOT NULL,
  315. stats_messages INT NOT NULL DEFAULT (0),
  316. stats_emails INT NOT NULL DEFAULT (0),
  317. stripe_customer_id TEXT,
  318. stripe_subscription_id TEXT,
  319. stripe_subscription_status TEXT,
  320. stripe_subscription_paid_until INT,
  321. stripe_subscription_cancel_at INT,
  322. created INT NOT NULL,
  323. deleted INT,
  324. FOREIGN KEY (tier_id) REFERENCES tier (id)
  325. );
  326. CREATE UNIQUE INDEX idx_user ON user (user);
  327. CREATE UNIQUE INDEX idx_user_stripe_customer_id ON user (stripe_customer_id);
  328. CREATE UNIQUE INDEX idx_user_stripe_subscription_id ON user (stripe_subscription_id);
  329. CREATE TABLE IF NOT EXISTS user_access (
  330. user_id TEXT NOT NULL,
  331. topic TEXT NOT NULL,
  332. read INT NOT NULL,
  333. write INT NOT NULL,
  334. owner_user_id INT,
  335. PRIMARY KEY (user_id, topic),
  336. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE,
  337. FOREIGN KEY (owner_user_id) REFERENCES user (id) ON DELETE CASCADE
  338. );
  339. CREATE TABLE IF NOT EXISTS user_token (
  340. user_id TEXT NOT NULL,
  341. token TEXT NOT NULL,
  342. label TEXT NOT NULL,
  343. last_access INT NOT NULL,
  344. last_origin TEXT NOT NULL,
  345. expires INT NOT NULL,
  346. PRIMARY KEY (user_id, token),
  347. FOREIGN KEY (user_id) REFERENCES user (id) ON DELETE CASCADE
  348. );
  349. CREATE TABLE IF NOT EXISTS schemaVersion (
  350. id INT PRIMARY KEY,
  351. version INT NOT NULL
  352. );
  353. INSERT INTO user (id, user, pass, role, sync_topic, created)
  354. VALUES ('u_everyone', '*', '', 'anonymous', '', UNIXEPOCH())
  355. ON CONFLICT (id) DO NOTHING;
  356. `
  357. migrate1To2SelectAllOldUsernamesNoTx = `SELECT user FROM user_old`
  358. migrate1To2InsertUserNoTx = `
  359. INSERT INTO user (id, user, pass, role, sync_topic, created)
  360. SELECT ?, user, pass, role, ?, UNIXEPOCH() FROM user_old WHERE user = ?
  361. `
  362. migrate1To2InsertFromOldTablesAndDropNoTx = `
  363. INSERT INTO user_access (user_id, topic, read, write)
  364. SELECT u.id, a.topic, a.read, a.write
  365. FROM user u
  366. JOIN access a ON u.user = a.user;
  367. DROP TABLE access;
  368. DROP TABLE user_old;
  369. `
  370. // 2 -> 3
  371. migrate2To3UpdateQueries = `
  372. ALTER TABLE user ADD COLUMN stripe_subscription_interval TEXT;
  373. ALTER TABLE tier RENAME COLUMN stripe_price_id TO stripe_monthly_price_id;
  374. ALTER TABLE tier ADD COLUMN stripe_yearly_price_id TEXT;
  375. DROP INDEX IF EXISTS idx_tier_price_id;
  376. CREATE UNIQUE INDEX idx_tier_stripe_monthly_price_id ON tier (stripe_monthly_price_id);
  377. CREATE UNIQUE INDEX idx_tier_stripe_yearly_price_id ON tier (stripe_yearly_price_id);
  378. `
  379. )
  380. var (
  381. migrations = map[int]func(db *sql.DB) error{
  382. 1: migrateFrom1,
  383. 2: migrateFrom2,
  384. }
  385. )
  386. // Manager is an implementation of Manager. It stores users and access control list
  387. // in a SQLite database.
  388. type Manager struct {
  389. db *sql.DB
  390. defaultAccess Permission // Default permission if no ACL matches
  391. statsQueue map[string]*Stats // "Queue" to asynchronously write user stats to the database (UserID -> Stats)
  392. tokenQueue map[string]*TokenUpdate // "Queue" to asynchronously write token access stats to the database (Token ID -> TokenUpdate)
  393. bcryptCost int // Makes testing easier
  394. mu sync.Mutex
  395. }
  396. var _ Auther = (*Manager)(nil)
  397. // NewManager creates a new Manager instance
  398. func NewManager(filename, startupQueries string, defaultAccess Permission, bcryptCost int, queueWriterInterval time.Duration) (*Manager, error) {
  399. db, err := sql.Open("sqlite3", filename)
  400. if err != nil {
  401. return nil, err
  402. }
  403. if err := setupDB(db); err != nil {
  404. return nil, err
  405. }
  406. if err := runStartupQueries(db, startupQueries); err != nil {
  407. return nil, err
  408. }
  409. manager := &Manager{
  410. db: db,
  411. defaultAccess: defaultAccess,
  412. statsQueue: make(map[string]*Stats),
  413. tokenQueue: make(map[string]*TokenUpdate),
  414. bcryptCost: bcryptCost,
  415. }
  416. go manager.asyncQueueWriter(queueWriterInterval)
  417. return manager, nil
  418. }
  419. // Authenticate checks username and password and returns a User if correct, and the user has not been
  420. // marked as deleted. The method returns in constant-ish time, regardless of whether the user exists or
  421. // the password is correct or incorrect.
  422. func (a *Manager) Authenticate(username, password string) (*User, error) {
  423. if username == Everyone {
  424. return nil, ErrUnauthenticated
  425. }
  426. user, err := a.User(username)
  427. if err != nil {
  428. log.Tag(tag).Field("user_name", username).Err(err).Trace("Authentication of user failed (1)")
  429. bcrypt.CompareHashAndPassword([]byte(userAuthIntentionalSlowDownHash), []byte("intentional slow-down to avoid timing attacks"))
  430. return nil, ErrUnauthenticated
  431. } else if user.Deleted {
  432. log.Tag(tag).Field("user_name", username).Trace("Authentication of user failed (2): user marked deleted")
  433. bcrypt.CompareHashAndPassword([]byte(userAuthIntentionalSlowDownHash), []byte("intentional slow-down to avoid timing attacks"))
  434. return nil, ErrUnauthenticated
  435. } else if err := bcrypt.CompareHashAndPassword([]byte(user.Hash), []byte(password)); err != nil {
  436. log.Tag(tag).Field("user_name", username).Err(err).Trace("Authentication of user failed (3)")
  437. return nil, ErrUnauthenticated
  438. }
  439. return user, nil
  440. }
  441. // AuthenticateToken checks if the token exists and returns the associated User if it does.
  442. // The method sets the User.Token value to the token that was used for authentication.
  443. func (a *Manager) AuthenticateToken(token string) (*User, error) {
  444. if len(token) != tokenLength {
  445. return nil, ErrUnauthenticated
  446. }
  447. user, err := a.userByToken(token)
  448. if err != nil {
  449. log.Tag(tag).Field("token", token).Err(err).Trace("Authentication of token failed")
  450. return nil, ErrUnauthenticated
  451. }
  452. user.Token = token
  453. return user, nil
  454. }
  455. // CreateToken generates a random token for the given user and returns it. The token expires
  456. // after a fixed duration unless ChangeToken is called. This function also prunes tokens for the
  457. // given user, if there are too many of them.
  458. func (a *Manager) CreateToken(userID, label string, expires time.Time, origin netip.Addr) (*Token, error) {
  459. token := util.RandomStringPrefix(tokenPrefix, tokenLength)
  460. tx, err := a.db.Begin()
  461. if err != nil {
  462. return nil, err
  463. }
  464. defer tx.Rollback()
  465. access := time.Now()
  466. if _, err := tx.Exec(insertTokenQuery, userID, token, label, access.Unix(), origin.String(), expires.Unix()); err != nil {
  467. return nil, err
  468. }
  469. rows, err := tx.Query(selectTokenCountQuery, userID)
  470. if err != nil {
  471. return nil, err
  472. }
  473. defer rows.Close()
  474. if !rows.Next() {
  475. return nil, errNoRows
  476. }
  477. var tokenCount int
  478. if err := rows.Scan(&tokenCount); err != nil {
  479. return nil, err
  480. }
  481. if tokenCount >= tokenMaxCount {
  482. // This pruning logic is done in two queries for efficiency. The SELECT above is a lookup
  483. // on two indices, whereas the query below is a full table scan.
  484. if _, err := tx.Exec(deleteExcessTokensQuery, userID, tokenMaxCount); err != nil {
  485. return nil, err
  486. }
  487. }
  488. if err := tx.Commit(); err != nil {
  489. return nil, err
  490. }
  491. return &Token{
  492. Value: token,
  493. Label: label,
  494. LastAccess: access,
  495. LastOrigin: origin,
  496. Expires: expires,
  497. }, nil
  498. }
  499. // Tokens returns all existing tokens for the user with the given user ID
  500. func (a *Manager) Tokens(userID string) ([]*Token, error) {
  501. rows, err := a.db.Query(selectTokensQuery, userID)
  502. if err != nil {
  503. return nil, err
  504. }
  505. defer rows.Close()
  506. tokens := make([]*Token, 0)
  507. for {
  508. token, err := a.readToken(rows)
  509. if err == ErrTokenNotFound {
  510. break
  511. } else if err != nil {
  512. return nil, err
  513. }
  514. tokens = append(tokens, token)
  515. }
  516. return tokens, nil
  517. }
  518. // Token returns a specific token for a user
  519. func (a *Manager) Token(userID, token string) (*Token, error) {
  520. rows, err := a.db.Query(selectTokenQuery, userID, token)
  521. if err != nil {
  522. return nil, err
  523. }
  524. defer rows.Close()
  525. return a.readToken(rows)
  526. }
  527. func (a *Manager) readToken(rows *sql.Rows) (*Token, error) {
  528. var token, label, lastOrigin string
  529. var lastAccess, expires int64
  530. if !rows.Next() {
  531. return nil, ErrTokenNotFound
  532. }
  533. if err := rows.Scan(&token, &label, &lastAccess, &lastOrigin, &expires); err != nil {
  534. return nil, err
  535. } else if err := rows.Err(); err != nil {
  536. return nil, err
  537. }
  538. lastOriginIP, err := netip.ParseAddr(lastOrigin)
  539. if err != nil {
  540. lastOriginIP = netip.IPv4Unspecified()
  541. }
  542. return &Token{
  543. Value: token,
  544. Label: label,
  545. LastAccess: time.Unix(lastAccess, 0),
  546. LastOrigin: lastOriginIP,
  547. Expires: time.Unix(expires, 0),
  548. }, nil
  549. }
  550. // ChangeToken updates a token's label and/or expiry date
  551. func (a *Manager) ChangeToken(userID, token string, label *string, expires *time.Time) (*Token, error) {
  552. if token == "" {
  553. return nil, errNoTokenProvided
  554. }
  555. tx, err := a.db.Begin()
  556. if err != nil {
  557. return nil, err
  558. }
  559. defer tx.Rollback()
  560. if label != nil {
  561. if _, err := tx.Exec(updateTokenLabelQuery, *label, userID, token); err != nil {
  562. return nil, err
  563. }
  564. }
  565. if expires != nil {
  566. if _, err := tx.Exec(updateTokenExpiryQuery, expires.Unix(), userID, token); err != nil {
  567. return nil, err
  568. }
  569. }
  570. if err := tx.Commit(); err != nil {
  571. return nil, err
  572. }
  573. return a.Token(userID, token)
  574. }
  575. // RemoveToken deletes the token defined in User.Token
  576. func (a *Manager) RemoveToken(userID, token string) error {
  577. if token == "" {
  578. return errNoTokenProvided
  579. }
  580. if _, err := a.db.Exec(deleteTokenQuery, userID, token); err != nil {
  581. return err
  582. }
  583. return nil
  584. }
  585. // RemoveExpiredTokens deletes all expired tokens from the database
  586. func (a *Manager) RemoveExpiredTokens() error {
  587. if _, err := a.db.Exec(deleteExpiredTokensQuery, time.Now().Unix()); err != nil {
  588. return err
  589. }
  590. return nil
  591. }
  592. // RemoveDeletedUsers deletes all users that have been marked deleted for
  593. func (a *Manager) RemoveDeletedUsers() error {
  594. if _, err := a.db.Exec(deleteUsersMarkedQuery, time.Now().Unix()); err != nil {
  595. return err
  596. }
  597. return nil
  598. }
  599. // ChangeSettings persists the user settings
  600. func (a *Manager) ChangeSettings(userID string, prefs *Prefs) error {
  601. b, err := json.Marshal(prefs)
  602. if err != nil {
  603. return err
  604. }
  605. if _, err := a.db.Exec(updateUserPrefsQuery, string(b), userID); err != nil {
  606. return err
  607. }
  608. return nil
  609. }
  610. // ResetStats resets all user stats in the user database. This touches all users.
  611. func (a *Manager) ResetStats() error {
  612. a.mu.Lock() // Includes database query to avoid races!
  613. defer a.mu.Unlock()
  614. if _, err := a.db.Exec(updateUserStatsResetAllQuery); err != nil {
  615. return err
  616. }
  617. a.statsQueue = make(map[string]*Stats)
  618. return nil
  619. }
  620. // EnqueueUserStats adds the user to a queue which writes out user stats (messages, emails, ..) in
  621. // batches at a regular interval
  622. func (a *Manager) EnqueueUserStats(userID string, stats *Stats) {
  623. a.mu.Lock()
  624. defer a.mu.Unlock()
  625. a.statsQueue[userID] = stats
  626. }
  627. // EnqueueTokenUpdate adds the token update to a queue which writes out token access times
  628. // in batches at a regular interval
  629. func (a *Manager) EnqueueTokenUpdate(tokenID string, update *TokenUpdate) {
  630. a.mu.Lock()
  631. defer a.mu.Unlock()
  632. a.tokenQueue[tokenID] = update
  633. }
  634. func (a *Manager) asyncQueueWriter(interval time.Duration) {
  635. ticker := time.NewTicker(interval)
  636. for range ticker.C {
  637. if err := a.writeUserStatsQueue(); err != nil {
  638. log.Tag(tag).Err(err).Warn("Writing user stats queue failed")
  639. }
  640. if err := a.writeTokenUpdateQueue(); err != nil {
  641. log.Tag(tag).Err(err).Warn("Writing token update queue failed")
  642. }
  643. }
  644. }
  645. func (a *Manager) writeUserStatsQueue() error {
  646. a.mu.Lock()
  647. if len(a.statsQueue) == 0 {
  648. a.mu.Unlock()
  649. log.Tag(tag).Trace("No user stats updates to commit")
  650. return nil
  651. }
  652. statsQueue := a.statsQueue
  653. a.statsQueue = make(map[string]*Stats)
  654. a.mu.Unlock()
  655. tx, err := a.db.Begin()
  656. if err != nil {
  657. return err
  658. }
  659. defer tx.Rollback()
  660. log.Tag(tag).Debug("Writing user stats queue for %d user(s)", len(statsQueue))
  661. for userID, update := range statsQueue {
  662. log.
  663. Tag(tag).
  664. Fields(log.Context{
  665. "user_id": userID,
  666. "messages_count": update.Messages,
  667. "emails_count": update.Emails,
  668. }).
  669. Trace("Updating stats for user %s", userID)
  670. if _, err := tx.Exec(updateUserStatsQuery, update.Messages, update.Emails, userID); err != nil {
  671. return err
  672. }
  673. }
  674. return tx.Commit()
  675. }
  676. func (a *Manager) writeTokenUpdateQueue() error {
  677. a.mu.Lock()
  678. if len(a.tokenQueue) == 0 {
  679. a.mu.Unlock()
  680. log.Tag(tag).Trace("No token updates to commit")
  681. return nil
  682. }
  683. tokenQueue := a.tokenQueue
  684. a.tokenQueue = make(map[string]*TokenUpdate)
  685. a.mu.Unlock()
  686. tx, err := a.db.Begin()
  687. if err != nil {
  688. return err
  689. }
  690. defer tx.Rollback()
  691. log.Tag(tag).Debug("Writing token update queue for %d token(s)", len(tokenQueue))
  692. for tokenID, update := range tokenQueue {
  693. log.Tag(tag).Trace("Updating token %s with last access time %v", tokenID, update.LastAccess.Unix())
  694. if _, err := tx.Exec(updateTokenLastAccessQuery, update.LastAccess.Unix(), update.LastOrigin.String(), tokenID); err != nil {
  695. return err
  696. }
  697. }
  698. return tx.Commit()
  699. }
  700. // Authorize returns nil if the given user has access to the given topic using the desired
  701. // permission. The user param may be nil to signal an anonymous user.
  702. func (a *Manager) Authorize(user *User, topic string, perm Permission) error {
  703. if user != nil && user.Role == RoleAdmin {
  704. return nil // Admin can do everything
  705. }
  706. username := Everyone
  707. if user != nil {
  708. username = user.Name
  709. }
  710. // Select the read/write permissions for this user/topic combo. The query may return two
  711. // rows (one for everyone, and one for the user), but prioritizes the user.
  712. rows, err := a.db.Query(selectTopicPermsQuery, Everyone, username, topic)
  713. if err != nil {
  714. return err
  715. }
  716. defer rows.Close()
  717. if !rows.Next() {
  718. return a.resolvePerms(a.defaultAccess, perm)
  719. }
  720. var read, write bool
  721. if err := rows.Scan(&read, &write); err != nil {
  722. return err
  723. } else if err := rows.Err(); err != nil {
  724. return err
  725. }
  726. return a.resolvePerms(NewPermission(read, write), perm)
  727. }
  728. func (a *Manager) resolvePerms(base, perm Permission) error {
  729. if perm == PermissionRead && base.IsRead() {
  730. return nil
  731. } else if perm == PermissionWrite && base.IsWrite() {
  732. return nil
  733. }
  734. return ErrUnauthorized
  735. }
  736. // AddUser adds a user with the given username, password and role
  737. func (a *Manager) AddUser(username, password string, role Role) error {
  738. if !AllowedUsername(username) || !AllowedRole(role) {
  739. return ErrInvalidArgument
  740. }
  741. hash, err := bcrypt.GenerateFromPassword([]byte(password), a.bcryptCost)
  742. if err != nil {
  743. return err
  744. }
  745. userID := util.RandomStringPrefix(userIDPrefix, userIDLength)
  746. syncTopic, now := util.RandomStringPrefix(syncTopicPrefix, syncTopicLength), time.Now().Unix()
  747. if _, err = a.db.Exec(insertUserQuery, userID, username, hash, role, syncTopic, now); err != nil {
  748. return err
  749. }
  750. return nil
  751. }
  752. // RemoveUser deletes the user with the given username. The function returns nil on success, even
  753. // if the user did not exist in the first place.
  754. func (a *Manager) RemoveUser(username string) error {
  755. if !AllowedUsername(username) {
  756. return ErrInvalidArgument
  757. }
  758. // Rows in user_access, user_token, etc. are deleted via foreign keys
  759. if _, err := a.db.Exec(deleteUserQuery, username); err != nil {
  760. return err
  761. }
  762. return nil
  763. }
  764. // MarkUserRemoved sets the deleted flag on the user, and deletes all access tokens. This prevents
  765. // successful auth via Authenticate. A background process will delete the user at a later date.
  766. func (a *Manager) MarkUserRemoved(user *User) error {
  767. if !AllowedUsername(user.Name) {
  768. return ErrInvalidArgument
  769. }
  770. tx, err := a.db.Begin()
  771. if err != nil {
  772. return err
  773. }
  774. defer tx.Rollback()
  775. if _, err := tx.Exec(deleteUserAccessQuery, user.Name, user.Name); err != nil {
  776. return err
  777. }
  778. if _, err := tx.Exec(deleteAllTokenQuery, user.ID); err != nil {
  779. return err
  780. }
  781. if _, err := tx.Exec(updateUserDeletedQuery, time.Now().Add(userHardDeleteAfterDuration).Unix(), user.ID); err != nil {
  782. return err
  783. }
  784. return tx.Commit()
  785. }
  786. // Users returns a list of users. It always also returns the Everyone user ("*").
  787. func (a *Manager) Users() ([]*User, error) {
  788. rows, err := a.db.Query(selectUsernamesQuery)
  789. if err != nil {
  790. return nil, err
  791. }
  792. defer rows.Close()
  793. usernames := make([]string, 0)
  794. for rows.Next() {
  795. var username string
  796. if err := rows.Scan(&username); err != nil {
  797. return nil, err
  798. } else if err := rows.Err(); err != nil {
  799. return nil, err
  800. }
  801. usernames = append(usernames, username)
  802. }
  803. rows.Close()
  804. users := make([]*User, 0)
  805. for _, username := range usernames {
  806. user, err := a.User(username)
  807. if err != nil {
  808. return nil, err
  809. }
  810. users = append(users, user)
  811. }
  812. return users, nil
  813. }
  814. // UsersCount returns the number of users in the databsae
  815. func (a *Manager) UsersCount() (int64, error) {
  816. rows, err := a.db.Query(selectUserCountQuery)
  817. if err != nil {
  818. return 0, err
  819. }
  820. defer rows.Close()
  821. if !rows.Next() {
  822. return 0, errNoRows
  823. }
  824. var count int64
  825. if err := rows.Scan(&count); err != nil {
  826. return 0, err
  827. }
  828. return count, nil
  829. }
  830. // User returns the user with the given username if it exists, or ErrUserNotFound otherwise.
  831. // You may also pass Everyone to retrieve the anonymous user and its Grant list.
  832. func (a *Manager) User(username string) (*User, error) {
  833. rows, err := a.db.Query(selectUserByNameQuery, username)
  834. if err != nil {
  835. return nil, err
  836. }
  837. return a.readUser(rows)
  838. }
  839. // UserByID returns the user with the given ID if it exists, or ErrUserNotFound otherwise
  840. func (a *Manager) UserByID(id string) (*User, error) {
  841. rows, err := a.db.Query(selectUserByIDQuery, id)
  842. if err != nil {
  843. return nil, err
  844. }
  845. return a.readUser(rows)
  846. }
  847. // UserByStripeCustomer returns the user with the given Stripe customer ID if it exists, or ErrUserNotFound otherwise.
  848. func (a *Manager) UserByStripeCustomer(stripeCustomerID string) (*User, error) {
  849. rows, err := a.db.Query(selectUserByStripeCustomerIDQuery, stripeCustomerID)
  850. if err != nil {
  851. return nil, err
  852. }
  853. return a.readUser(rows)
  854. }
  855. func (a *Manager) userByToken(token string) (*User, error) {
  856. rows, err := a.db.Query(selectUserByTokenQuery, token, time.Now().Unix())
  857. if err != nil {
  858. return nil, err
  859. }
  860. return a.readUser(rows)
  861. }
  862. func (a *Manager) readUser(rows *sql.Rows) (*User, error) {
  863. defer rows.Close()
  864. var id, username, hash, role, prefs, syncTopic string
  865. var stripeCustomerID, stripeSubscriptionID, stripeSubscriptionStatus, stripeSubscriptionInterval, stripeMonthlyPriceID, stripeYearlyPriceID, tierID, tierCode, tierName sql.NullString
  866. var messages, emails int64
  867. var messagesLimit, messagesExpiryDuration, emailsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit, stripeSubscriptionPaidUntil, stripeSubscriptionCancelAt, deleted sql.NullInt64
  868. if !rows.Next() {
  869. return nil, ErrUserNotFound
  870. }
  871. if err := rows.Scan(&id, &username, &hash, &role, &prefs, &syncTopic, &messages, &emails, &stripeCustomerID, &stripeSubscriptionID, &stripeSubscriptionStatus, &stripeSubscriptionInterval, &stripeSubscriptionPaidUntil, &stripeSubscriptionCancelAt, &deleted, &tierID, &tierCode, &tierName, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripeMonthlyPriceID, &stripeYearlyPriceID); err != nil {
  872. return nil, err
  873. } else if err := rows.Err(); err != nil {
  874. return nil, err
  875. }
  876. user := &User{
  877. ID: id,
  878. Name: username,
  879. Hash: hash,
  880. Role: Role(role),
  881. Prefs: &Prefs{},
  882. SyncTopic: syncTopic,
  883. Stats: &Stats{
  884. Messages: messages,
  885. Emails: emails,
  886. },
  887. Billing: &Billing{
  888. StripeCustomerID: stripeCustomerID.String, // May be empty
  889. StripeSubscriptionID: stripeSubscriptionID.String, // May be empty
  890. StripeSubscriptionStatus: stripe.SubscriptionStatus(stripeSubscriptionStatus.String), // May be empty
  891. StripeSubscriptionInterval: stripe.PriceRecurringInterval(stripeSubscriptionInterval.String), // May be empty
  892. StripeSubscriptionPaidUntil: time.Unix(stripeSubscriptionPaidUntil.Int64, 0), // May be zero
  893. StripeSubscriptionCancelAt: time.Unix(stripeSubscriptionCancelAt.Int64, 0), // May be zero
  894. },
  895. Deleted: deleted.Valid,
  896. }
  897. if err := json.Unmarshal([]byte(prefs), user.Prefs); err != nil {
  898. return nil, err
  899. }
  900. if tierCode.Valid {
  901. // See readTier() when this is changed!
  902. user.Tier = &Tier{
  903. ID: tierID.String,
  904. Code: tierCode.String,
  905. Name: tierName.String,
  906. MessageLimit: messagesLimit.Int64,
  907. MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
  908. EmailLimit: emailsLimit.Int64,
  909. ReservationLimit: reservationsLimit.Int64,
  910. AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
  911. AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
  912. AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
  913. AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
  914. StripeMonthlyPriceID: stripeMonthlyPriceID.String, // May be empty
  915. StripeYearlyPriceID: stripeYearlyPriceID.String, // May be empty
  916. }
  917. }
  918. return user, nil
  919. }
  920. // Grants returns all user-specific access control entries
  921. func (a *Manager) Grants(username string) ([]Grant, error) {
  922. rows, err := a.db.Query(selectUserAccessQuery, username)
  923. if err != nil {
  924. return nil, err
  925. }
  926. defer rows.Close()
  927. grants := make([]Grant, 0)
  928. for rows.Next() {
  929. var topic string
  930. var read, write bool
  931. if err := rows.Scan(&topic, &read, &write); err != nil {
  932. return nil, err
  933. } else if err := rows.Err(); err != nil {
  934. return nil, err
  935. }
  936. grants = append(grants, Grant{
  937. TopicPattern: fromSQLWildcard(topic),
  938. Allow: NewPermission(read, write),
  939. })
  940. }
  941. return grants, nil
  942. }
  943. // Reservations returns all user-owned topics, and the associated everyone-access
  944. func (a *Manager) Reservations(username string) ([]Reservation, error) {
  945. rows, err := a.db.Query(selectUserReservationsQuery, Everyone, username)
  946. if err != nil {
  947. return nil, err
  948. }
  949. defer rows.Close()
  950. reservations := make([]Reservation, 0)
  951. for rows.Next() {
  952. var topic string
  953. var ownerRead, ownerWrite bool
  954. var everyoneRead, everyoneWrite sql.NullBool
  955. if err := rows.Scan(&topic, &ownerRead, &ownerWrite, &everyoneRead, &everyoneWrite); err != nil {
  956. return nil, err
  957. } else if err := rows.Err(); err != nil {
  958. return nil, err
  959. }
  960. reservations = append(reservations, Reservation{
  961. Topic: topic,
  962. Owner: NewPermission(ownerRead, ownerWrite),
  963. Everyone: NewPermission(everyoneRead.Bool, everyoneWrite.Bool), // false if null
  964. })
  965. }
  966. return reservations, nil
  967. }
  968. // HasReservation returns true if the given topic access is owned by the user
  969. func (a *Manager) HasReservation(username, topic string) (bool, error) {
  970. rows, err := a.db.Query(selectUserHasReservationQuery, username, topic)
  971. if err != nil {
  972. return false, err
  973. }
  974. defer rows.Close()
  975. if !rows.Next() {
  976. return false, errNoRows
  977. }
  978. var count int64
  979. if err := rows.Scan(&count); err != nil {
  980. return false, err
  981. }
  982. return count > 0, nil
  983. }
  984. // ReservationsCount returns the number of reservations owned by this user
  985. func (a *Manager) ReservationsCount(username string) (int64, error) {
  986. rows, err := a.db.Query(selectUserReservationsCountQuery, username)
  987. if err != nil {
  988. return 0, err
  989. }
  990. defer rows.Close()
  991. if !rows.Next() {
  992. return 0, errNoRows
  993. }
  994. var count int64
  995. if err := rows.Scan(&count); err != nil {
  996. return 0, err
  997. }
  998. return count, nil
  999. }
  1000. // ReservationOwner returns user ID of the user that owns this topic, or an
  1001. // empty string if it's not owned by anyone
  1002. func (a *Manager) ReservationOwner(topic string) (string, error) {
  1003. rows, err := a.db.Query(selectUserReservationsOwnerQuery, topic)
  1004. if err != nil {
  1005. return "", err
  1006. }
  1007. defer rows.Close()
  1008. if !rows.Next() {
  1009. return "", nil
  1010. }
  1011. var ownerUserID string
  1012. if err := rows.Scan(&ownerUserID); err != nil {
  1013. return "", err
  1014. }
  1015. return ownerUserID, nil
  1016. }
  1017. // ChangePassword changes a user's password
  1018. func (a *Manager) ChangePassword(username, password string) error {
  1019. hash, err := bcrypt.GenerateFromPassword([]byte(password), a.bcryptCost)
  1020. if err != nil {
  1021. return err
  1022. }
  1023. if _, err := a.db.Exec(updateUserPassQuery, hash, username); err != nil {
  1024. return err
  1025. }
  1026. return nil
  1027. }
  1028. // ChangeRole changes a user's role. When a role is changed from RoleUser to RoleAdmin,
  1029. // all existing access control entries (Grant) are removed, since they are no longer needed.
  1030. func (a *Manager) ChangeRole(username string, role Role) error {
  1031. if !AllowedUsername(username) || !AllowedRole(role) {
  1032. return ErrInvalidArgument
  1033. }
  1034. if _, err := a.db.Exec(updateUserRoleQuery, string(role), username); err != nil {
  1035. return err
  1036. }
  1037. if role == RoleAdmin {
  1038. if _, err := a.db.Exec(deleteUserAccessQuery, username, username); err != nil {
  1039. return err
  1040. }
  1041. }
  1042. return nil
  1043. }
  1044. // ChangeTier changes a user's tier using the tier code. This function does not delete reservations, messages,
  1045. // or attachments, even if the new tier has lower limits in this regard. That has to be done elsewhere.
  1046. func (a *Manager) ChangeTier(username, tier string) error {
  1047. if !AllowedUsername(username) {
  1048. return ErrInvalidArgument
  1049. }
  1050. t, err := a.Tier(tier)
  1051. if err != nil {
  1052. return err
  1053. } else if err := a.checkReservationsLimit(username, t.ReservationLimit); err != nil {
  1054. return err
  1055. }
  1056. if _, err := a.db.Exec(updateUserTierQuery, tier, username); err != nil {
  1057. return err
  1058. }
  1059. return nil
  1060. }
  1061. // ResetTier removes the tier from the given user
  1062. func (a *Manager) ResetTier(username string) error {
  1063. if !AllowedUsername(username) && username != Everyone && username != "" {
  1064. return ErrInvalidArgument
  1065. } else if err := a.checkReservationsLimit(username, 0); err != nil {
  1066. return err
  1067. }
  1068. _, err := a.db.Exec(deleteUserTierQuery, username)
  1069. return err
  1070. }
  1071. func (a *Manager) checkReservationsLimit(username string, reservationsLimit int64) error {
  1072. u, err := a.User(username)
  1073. if err != nil {
  1074. return err
  1075. }
  1076. if u.Tier != nil && reservationsLimit < u.Tier.ReservationLimit {
  1077. reservations, err := a.Reservations(username)
  1078. if err != nil {
  1079. return err
  1080. } else if int64(len(reservations)) > reservationsLimit {
  1081. return ErrTooManyReservations
  1082. }
  1083. }
  1084. return nil
  1085. }
  1086. // AllowReservation tests if a user may create an access control entry for the given topic.
  1087. // If there are any ACL entries that are not owned by the user, an error is returned.
  1088. func (a *Manager) AllowReservation(username string, topic string) error {
  1089. if (!AllowedUsername(username) && username != Everyone) || !AllowedTopic(topic) {
  1090. return ErrInvalidArgument
  1091. }
  1092. rows, err := a.db.Query(selectOtherAccessCountQuery, topic, topic, username)
  1093. if err != nil {
  1094. return err
  1095. }
  1096. defer rows.Close()
  1097. if !rows.Next() {
  1098. return errNoRows
  1099. }
  1100. var otherCount int
  1101. if err := rows.Scan(&otherCount); err != nil {
  1102. return err
  1103. }
  1104. if otherCount > 0 {
  1105. return errTopicOwnedByOthers
  1106. }
  1107. return nil
  1108. }
  1109. // AllowAccess adds or updates an entry in th access control list for a specific user. It controls
  1110. // read/write access to a topic. The parameter topicPattern may include wildcards (*). The ACL entry
  1111. // owner may either be a user (username), or the system (empty).
  1112. func (a *Manager) AllowAccess(username string, topicPattern string, permission Permission) error {
  1113. if !AllowedUsername(username) && username != Everyone {
  1114. return ErrInvalidArgument
  1115. } else if !AllowedTopicPattern(topicPattern) {
  1116. return ErrInvalidArgument
  1117. }
  1118. owner := ""
  1119. if _, err := a.db.Exec(upsertUserAccessQuery, username, toSQLWildcard(topicPattern), permission.IsRead(), permission.IsWrite(), owner, owner); err != nil {
  1120. return err
  1121. }
  1122. return nil
  1123. }
  1124. // ResetAccess removes an access control list entry for a specific username/topic, or (if topic is
  1125. // empty) for an entire user. The parameter topicPattern may include wildcards (*).
  1126. func (a *Manager) ResetAccess(username string, topicPattern string) error {
  1127. if !AllowedUsername(username) && username != Everyone && username != "" {
  1128. return ErrInvalidArgument
  1129. } else if !AllowedTopicPattern(topicPattern) && topicPattern != "" {
  1130. return ErrInvalidArgument
  1131. }
  1132. if username == "" && topicPattern == "" {
  1133. _, err := a.db.Exec(deleteAllAccessQuery, username)
  1134. return err
  1135. } else if topicPattern == "" {
  1136. _, err := a.db.Exec(deleteUserAccessQuery, username, username)
  1137. return err
  1138. }
  1139. _, err := a.db.Exec(deleteTopicAccessQuery, username, username, toSQLWildcard(topicPattern))
  1140. return err
  1141. }
  1142. // AddReservation creates two access control entries for the given topic: one with full read/write access for the
  1143. // given user, and one for Everyone with the permission passed as everyone. The user also owns the entries, and
  1144. // can modify or delete them.
  1145. func (a *Manager) AddReservation(username string, topic string, everyone Permission) error {
  1146. if !AllowedUsername(username) || username == Everyone || !AllowedTopic(topic) {
  1147. return ErrInvalidArgument
  1148. }
  1149. tx, err := a.db.Begin()
  1150. if err != nil {
  1151. return err
  1152. }
  1153. defer tx.Rollback()
  1154. if _, err := tx.Exec(upsertUserAccessQuery, username, topic, true, true, username, username); err != nil {
  1155. return err
  1156. }
  1157. if _, err := tx.Exec(upsertUserAccessQuery, Everyone, topic, everyone.IsRead(), everyone.IsWrite(), username, username); err != nil {
  1158. return err
  1159. }
  1160. return tx.Commit()
  1161. }
  1162. // RemoveReservations deletes the access control entries associated with the given username/topic, as
  1163. // well as all entries with Everyone/topic. This is the counterpart for AddReservation.
  1164. func (a *Manager) RemoveReservations(username string, topics ...string) error {
  1165. if !AllowedUsername(username) || username == Everyone || len(topics) == 0 {
  1166. return ErrInvalidArgument
  1167. }
  1168. for _, topic := range topics {
  1169. if !AllowedTopic(topic) {
  1170. return ErrInvalidArgument
  1171. }
  1172. }
  1173. tx, err := a.db.Begin()
  1174. if err != nil {
  1175. return err
  1176. }
  1177. defer tx.Rollback()
  1178. for _, topic := range topics {
  1179. if _, err := tx.Exec(deleteTopicAccessQuery, username, username, topic); err != nil {
  1180. return err
  1181. }
  1182. if _, err := tx.Exec(deleteTopicAccessQuery, Everyone, Everyone, topic); err != nil {
  1183. return err
  1184. }
  1185. }
  1186. return tx.Commit()
  1187. }
  1188. // DefaultAccess returns the default read/write access if no access control entry matches
  1189. func (a *Manager) DefaultAccess() Permission {
  1190. return a.defaultAccess
  1191. }
  1192. // AddTier creates a new tier in the database
  1193. func (a *Manager) AddTier(tier *Tier) error {
  1194. if tier.ID == "" {
  1195. tier.ID = util.RandomStringPrefix(tierIDPrefix, tierIDLength)
  1196. }
  1197. if _, err := a.db.Exec(insertTierQuery, tier.ID, tier.Code, tier.Name, tier.MessageLimit, int64(tier.MessageExpiryDuration.Seconds()), tier.EmailLimit, tier.ReservationLimit, tier.AttachmentFileSizeLimit, tier.AttachmentTotalSizeLimit, int64(tier.AttachmentExpiryDuration.Seconds()), tier.AttachmentBandwidthLimit, nullString(tier.StripeMonthlyPriceID), nullString(tier.StripeYearlyPriceID)); err != nil {
  1198. return err
  1199. }
  1200. return nil
  1201. }
  1202. // UpdateTier updates a tier's properties in the database
  1203. func (a *Manager) UpdateTier(tier *Tier) error {
  1204. if _, err := a.db.Exec(updateTierQuery, tier.Name, tier.MessageLimit, int64(tier.MessageExpiryDuration.Seconds()), tier.EmailLimit, tier.ReservationLimit, tier.AttachmentFileSizeLimit, tier.AttachmentTotalSizeLimit, int64(tier.AttachmentExpiryDuration.Seconds()), tier.AttachmentBandwidthLimit, nullString(tier.StripeMonthlyPriceID), nullString(tier.StripeYearlyPriceID), tier.Code); err != nil {
  1205. return err
  1206. }
  1207. return nil
  1208. }
  1209. // RemoveTier deletes the tier with the given code
  1210. func (a *Manager) RemoveTier(code string) error {
  1211. if !AllowedTier(code) {
  1212. return ErrInvalidArgument
  1213. }
  1214. // This fails if any user has this tier
  1215. if _, err := a.db.Exec(deleteTierQuery, code); err != nil {
  1216. return err
  1217. }
  1218. return nil
  1219. }
  1220. // ChangeBilling updates a user's billing fields, namely the Stripe customer ID, and subscription information
  1221. func (a *Manager) ChangeBilling(username string, billing *Billing) error {
  1222. if _, err := a.db.Exec(updateBillingQuery, nullString(billing.StripeCustomerID), nullString(billing.StripeSubscriptionID), nullString(string(billing.StripeSubscriptionStatus)), nullString(string(billing.StripeSubscriptionInterval)), nullInt64(billing.StripeSubscriptionPaidUntil.Unix()), nullInt64(billing.StripeSubscriptionCancelAt.Unix()), username); err != nil {
  1223. return err
  1224. }
  1225. return nil
  1226. }
  1227. // Tiers returns a list of all Tier structs
  1228. func (a *Manager) Tiers() ([]*Tier, error) {
  1229. rows, err := a.db.Query(selectTiersQuery)
  1230. if err != nil {
  1231. return nil, err
  1232. }
  1233. defer rows.Close()
  1234. tiers := make([]*Tier, 0)
  1235. for {
  1236. tier, err := a.readTier(rows)
  1237. if err == ErrTierNotFound {
  1238. break
  1239. } else if err != nil {
  1240. return nil, err
  1241. }
  1242. tiers = append(tiers, tier)
  1243. }
  1244. return tiers, nil
  1245. }
  1246. // Tier returns a Tier based on the code, or ErrTierNotFound if it does not exist
  1247. func (a *Manager) Tier(code string) (*Tier, error) {
  1248. rows, err := a.db.Query(selectTierByCodeQuery, code)
  1249. if err != nil {
  1250. return nil, err
  1251. }
  1252. defer rows.Close()
  1253. return a.readTier(rows)
  1254. }
  1255. // TierByStripePrice returns a Tier based on the Stripe price ID, or ErrTierNotFound if it does not exist
  1256. func (a *Manager) TierByStripePrice(priceID string) (*Tier, error) {
  1257. rows, err := a.db.Query(selectTierByPriceIDQuery, priceID, priceID)
  1258. if err != nil {
  1259. return nil, err
  1260. }
  1261. defer rows.Close()
  1262. return a.readTier(rows)
  1263. }
  1264. func (a *Manager) readTier(rows *sql.Rows) (*Tier, error) {
  1265. var id, code, name string
  1266. var stripeMonthlyPriceID, stripeYearlyPriceID sql.NullString
  1267. var messagesLimit, messagesExpiryDuration, emailsLimit, reservationsLimit, attachmentFileSizeLimit, attachmentTotalSizeLimit, attachmentExpiryDuration, attachmentBandwidthLimit sql.NullInt64
  1268. if !rows.Next() {
  1269. return nil, ErrTierNotFound
  1270. }
  1271. if err := rows.Scan(&id, &code, &name, &messagesLimit, &messagesExpiryDuration, &emailsLimit, &reservationsLimit, &attachmentFileSizeLimit, &attachmentTotalSizeLimit, &attachmentExpiryDuration, &attachmentBandwidthLimit, &stripeMonthlyPriceID, &stripeYearlyPriceID); err != nil {
  1272. return nil, err
  1273. } else if err := rows.Err(); err != nil {
  1274. return nil, err
  1275. }
  1276. // When changed, note readUser() as well
  1277. return &Tier{
  1278. ID: id,
  1279. Code: code,
  1280. Name: name,
  1281. MessageLimit: messagesLimit.Int64,
  1282. MessageExpiryDuration: time.Duration(messagesExpiryDuration.Int64) * time.Second,
  1283. EmailLimit: emailsLimit.Int64,
  1284. ReservationLimit: reservationsLimit.Int64,
  1285. AttachmentFileSizeLimit: attachmentFileSizeLimit.Int64,
  1286. AttachmentTotalSizeLimit: attachmentTotalSizeLimit.Int64,
  1287. AttachmentExpiryDuration: time.Duration(attachmentExpiryDuration.Int64) * time.Second,
  1288. AttachmentBandwidthLimit: attachmentBandwidthLimit.Int64,
  1289. StripeMonthlyPriceID: stripeMonthlyPriceID.String, // May be empty
  1290. StripeYearlyPriceID: stripeYearlyPriceID.String, // May be empty
  1291. }, nil
  1292. }
  1293. // Close closes the underlying database
  1294. func (a *Manager) Close() error {
  1295. return a.db.Close()
  1296. }
  1297. func toSQLWildcard(s string) string {
  1298. return strings.ReplaceAll(s, "*", "%")
  1299. }
  1300. func fromSQLWildcard(s string) string {
  1301. return strings.ReplaceAll(s, "%", "*")
  1302. }
  1303. func runStartupQueries(db *sql.DB, startupQueries string) error {
  1304. if _, err := db.Exec(startupQueries); err != nil {
  1305. return err
  1306. }
  1307. if _, err := db.Exec(builtinStartupQueries); err != nil {
  1308. return err
  1309. }
  1310. return nil
  1311. }
  1312. func setupDB(db *sql.DB) error {
  1313. // If 'schemaVersion' table does not exist, this must be a new database
  1314. rowsSV, err := db.Query(selectSchemaVersionQuery)
  1315. if err != nil {
  1316. return setupNewDB(db)
  1317. }
  1318. defer rowsSV.Close()
  1319. // If 'schemaVersion' table exists, read version and potentially upgrade
  1320. schemaVersion := 0
  1321. if !rowsSV.Next() {
  1322. return errors.New("cannot determine schema version: database file may be corrupt")
  1323. }
  1324. if err := rowsSV.Scan(&schemaVersion); err != nil {
  1325. return err
  1326. }
  1327. rowsSV.Close()
  1328. // Do migrations
  1329. if schemaVersion == currentSchemaVersion {
  1330. return nil
  1331. } else if schemaVersion > currentSchemaVersion {
  1332. return fmt.Errorf("unexpected schema version: version %d is higher than current version %d", schemaVersion, currentSchemaVersion)
  1333. }
  1334. for i := schemaVersion; i < currentSchemaVersion; i++ {
  1335. fn, ok := migrations[i]
  1336. if !ok {
  1337. return fmt.Errorf("cannot find migration step from schema version %d to %d", i, i+1)
  1338. } else if err := fn(db); err != nil {
  1339. return err
  1340. }
  1341. }
  1342. return nil
  1343. }
  1344. func setupNewDB(db *sql.DB) error {
  1345. if _, err := db.Exec(createTablesQueries); err != nil {
  1346. return err
  1347. }
  1348. if _, err := db.Exec(insertSchemaVersion, currentSchemaVersion); err != nil {
  1349. return err
  1350. }
  1351. return nil
  1352. }
  1353. func migrateFrom1(db *sql.DB) error {
  1354. log.Tag(tag).Info("Migrating user database schema: from 1 to 2")
  1355. tx, err := db.Begin()
  1356. if err != nil {
  1357. return err
  1358. }
  1359. defer tx.Rollback()
  1360. // Rename user -> user_old, and create new tables
  1361. if _, err := tx.Exec(migrate1To2CreateTablesQueries); err != nil {
  1362. return err
  1363. }
  1364. // Insert users from user_old into new user table, with ID and sync_topic
  1365. rows, err := tx.Query(migrate1To2SelectAllOldUsernamesNoTx)
  1366. if err != nil {
  1367. return err
  1368. }
  1369. defer rows.Close()
  1370. usernames := make([]string, 0)
  1371. for rows.Next() {
  1372. var username string
  1373. if err := rows.Scan(&username); err != nil {
  1374. return err
  1375. }
  1376. usernames = append(usernames, username)
  1377. }
  1378. if err := rows.Close(); err != nil {
  1379. return err
  1380. }
  1381. for _, username := range usernames {
  1382. userID := util.RandomStringPrefix(userIDPrefix, userIDLength)
  1383. syncTopic := util.RandomStringPrefix(syncTopicPrefix, syncTopicLength)
  1384. if _, err := tx.Exec(migrate1To2InsertUserNoTx, userID, syncTopic, username); err != nil {
  1385. return err
  1386. }
  1387. }
  1388. // Migrate old "access" table to "user_access" and drop "access" and "user_old"
  1389. if _, err := tx.Exec(migrate1To2InsertFromOldTablesAndDropNoTx); err != nil {
  1390. return err
  1391. }
  1392. if _, err := tx.Exec(updateSchemaVersion, 2); err != nil {
  1393. return err
  1394. }
  1395. if err := tx.Commit(); err != nil {
  1396. return err
  1397. }
  1398. return nil
  1399. }
  1400. func migrateFrom2(db *sql.DB) error {
  1401. log.Tag(tag).Info("Migrating user database schema: from 2 to 3")
  1402. tx, err := db.Begin()
  1403. if err != nil {
  1404. return err
  1405. }
  1406. defer tx.Rollback()
  1407. if _, err := tx.Exec(migrate2To3UpdateQueries); err != nil {
  1408. return err
  1409. }
  1410. if _, err := tx.Exec(updateSchemaVersion, 3); err != nil {
  1411. return err
  1412. }
  1413. return tx.Commit()
  1414. }
  1415. func nullString(s string) sql.NullString {
  1416. if s == "" {
  1417. return sql.NullString{}
  1418. }
  1419. return sql.NullString{String: s, Valid: true}
  1420. }
  1421. func nullInt64(v int64) sql.NullInt64 {
  1422. if v == 0 {
  1423. return sql.NullInt64{}
  1424. }
  1425. return sql.NullInt64{Int64: v, Valid: true}
  1426. }