user.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. //go:build !noserver
  2. package cmd
  3. import (
  4. "crypto/subtle"
  5. "errors"
  6. "fmt"
  7. "heckel.io/ntfy/v2/server"
  8. "heckel.io/ntfy/v2/user"
  9. "os"
  10. "strings"
  11. "github.com/urfave/cli/v2"
  12. "github.com/urfave/cli/v2/altsrc"
  13. "heckel.io/ntfy/v2/util"
  14. )
  15. const (
  16. tierReset = "-"
  17. )
  18. func init() {
  19. commands = append(commands, cmdUser)
  20. }
  21. var flagsUser = append(
  22. append([]cli.Flag{}, flagsDefault...),
  23. &cli.StringFlag{Name: "config", Aliases: []string{"c"}, EnvVars: []string{"NTFY_CONFIG_FILE"}, Value: server.DefaultConfigFile, DefaultText: server.DefaultConfigFile, Usage: "config file"},
  24. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-file", Aliases: []string{"auth_file", "H"}, EnvVars: []string{"NTFY_AUTH_FILE"}, Usage: "auth database file used for access control"}),
  25. altsrc.NewStringFlag(&cli.StringFlag{Name: "auth-default-access", Aliases: []string{"auth_default_access", "p"}, EnvVars: []string{"NTFY_AUTH_DEFAULT_ACCESS"}, Value: "read-write", Usage: "default permissions if no matching entries in the auth database are found"}),
  26. )
  27. var cmdUser = &cli.Command{
  28. Name: "user",
  29. Usage: "Manage/show users",
  30. UsageText: "ntfy user [list|add|remove|change-pass|change-role] ...",
  31. Flags: flagsUser,
  32. Before: initConfigFileInputSourceFunc("config", flagsUser, initLogFunc),
  33. Category: categoryServer,
  34. Subcommands: []*cli.Command{
  35. {
  36. Name: "add",
  37. Aliases: []string{"a"},
  38. Usage: "Adds a new user",
  39. UsageText: "ntfy user add [--role=admin|user] USERNAME\nNTFY_PASSWORD=... ntfy user add [--role=admin|user] USERNAME\nNTFY_PASSWORD_HASH=... ntfy user add [--role=admin|user] USERNAME",
  40. Action: execUserAdd,
  41. Flags: []cli.Flag{
  42. &cli.StringFlag{Name: "role", Aliases: []string{"r"}, Value: string(user.RoleUser), Usage: "user role"},
  43. &cli.BoolFlag{Name: "ignore-exists", Usage: "if the user already exists, perform no action and exit"},
  44. },
  45. Description: `Add a new user to the ntfy user database.
  46. A user can be either a regular user, or an admin. A regular user has no read or write access (unless
  47. granted otherwise by the auth-default-access setting). An admin user has read and write access to all
  48. topics.
  49. Examples:
  50. ntfy user add phil # Add regular user phil
  51. ntfy user add --role=admin phil # Add admin user phil
  52. NTFY_PASSWORD=... ntfy user add phil # Add user, using env variable to set password (for scripts)
  53. NTFY_PASSWORD_HASH=... ntfy user add phil # Add user, using env variable to set password hash (for scripts)
  54. You may set the NTFY_PASSWORD environment variable to pass the password, or NTFY_PASSWORD_HASH to pass
  55. directly the bcrypt hash. This is useful if you are creating users via scripts.
  56. `,
  57. },
  58. {
  59. Name: "remove",
  60. Aliases: []string{"del", "rm"},
  61. Usage: "Removes a user",
  62. UsageText: "ntfy user remove USERNAME",
  63. Action: execUserDel,
  64. Description: `Remove a user from the ntfy user database.
  65. Example:
  66. ntfy user del phil
  67. `,
  68. },
  69. {
  70. Name: "change-pass",
  71. Aliases: []string{"chp"},
  72. Usage: "Changes a user's password",
  73. UsageText: "ntfy user change-pass USERNAME\nNTFY_PASSWORD=... ntfy user change-pass USERNAME\nNTFY_PASSWORD_HASH=... ntfy user change-pass USERNAME",
  74. Action: execUserChangePass,
  75. Description: `Change the password for the given user.
  76. The new password will be read from STDIN, and it'll be confirmed by typing
  77. it twice.
  78. Example:
  79. ntfy user change-pass phil
  80. NTFY_PASSWORD=.. ntfy user change-pass phil
  81. NTFY_PASSWORD_HASH=.. ntfy user change-pass phil
  82. You may set the NTFY_PASSWORD environment variable to pass the new password or NTFY_PASSWORD_HASH to pass
  83. directly the bcrypt hash. This is useful if you are updating users via scripts.
  84. `,
  85. },
  86. {
  87. Name: "change-role",
  88. Aliases: []string{"chr"},
  89. Usage: "Changes the role of a user",
  90. UsageText: "ntfy user change-role USERNAME ROLE",
  91. Action: execUserChangeRole,
  92. Description: `Change the role for the given user to admin or user.
  93. This command can be used to change the role of a user either from a regular user
  94. to an admin user, or the other way around:
  95. - admin: an admin has read/write access to all topics
  96. - user: a regular user only has access to what was explicitly granted via 'ntfy access'
  97. When changing the role of a user to "admin", all access control entries for that
  98. user are removed, since they are no longer necessary.
  99. Example:
  100. ntfy user change-role phil admin # Make user phil an admin
  101. ntfy user change-role phil user # Remove admin role from user phil
  102. `,
  103. },
  104. {
  105. Name: "change-tier",
  106. Aliases: []string{"cht"},
  107. Usage: "Changes the tier of a user",
  108. UsageText: "ntfy user change-tier USERNAME (TIER|-)",
  109. Action: execUserChangeTier,
  110. Description: `Change the tier for the given user.
  111. This command can be used to change the tier of a user. Tiers define usage limits, such
  112. as messages per day, attachment file sizes, etc.
  113. Example:
  114. ntfy user change-tier phil pro # Change tier to "pro" for user "phil"
  115. ntfy user change-tier phil - # Remove tier from user "phil" entirely
  116. `,
  117. },
  118. {
  119. Name: "hash",
  120. Usage: "Create password hash for a predefined user",
  121. UsageText: "ntfy user hash",
  122. Action: execUserHash,
  123. Description: `Asks for a password and creates a bcrypt password hash.
  124. This command is useful to create a password hash for a user, which can then be used
  125. for predefined users in the server config file, in auth-users.
  126. Example:
  127. $ ntfy user hash
  128. (asks for password and confirmation)
  129. $2a$10$YLiO8U21sX1uhZamTLJXHuxgVC0Z/GKISibrKCLohPgtG7yIxSk4C
  130. `,
  131. },
  132. {
  133. Name: "list",
  134. Aliases: []string{"l"},
  135. Usage: "Shows a list of users",
  136. Action: execUserList,
  137. Description: `Shows a list of all configured users, including the everyone ('*') user.
  138. This command is an alias to calling 'ntfy access' (display access control list).
  139. This is a server-only command. It directly reads from user.db as defined in the server config
  140. file server.yml. The command only works if 'auth-file' is properly defined.
  141. `,
  142. },
  143. },
  144. Description: `Manage users of the ntfy server.
  145. The command allows you to add/remove/change users in the ntfy user database, as well as change
  146. passwords or roles.
  147. This is a server-only command. It directly manages the user.db as defined in the server config
  148. file server.yml. The command only works if 'auth-file' is properly defined. Please also refer
  149. to the related command 'ntfy access'.
  150. Examples:
  151. ntfy user list # Shows list of users (alias: 'ntfy access')
  152. ntfy user add phil # Add regular user phil
  153. NTFY_PASSWORD=... ntfy user add phil # As above, using env variable to set password (for scripts)
  154. ntfy user add --role=admin phil # Add admin user phil
  155. ntfy user del phil # Delete user phil
  156. ntfy user change-pass phil # Change password for user phil
  157. NTFY_PASSWORD=.. ntfy user change-pass phil # As above, using env variable to set password (for scripts)
  158. ntfy user change-role phil admin # Make user phil an admin
  159. For the 'ntfy user add' and 'ntfy user change-pass' commands, you may set the NTFY_PASSWORD environment
  160. variable to pass the new password. This is useful if you are creating/updating users via scripts.
  161. `,
  162. }
  163. func execUserAdd(c *cli.Context) error {
  164. username := c.Args().Get(0)
  165. role := user.Role(c.String("role"))
  166. password, hashed := os.LookupEnv("NTFY_PASSWORD_HASH")
  167. if !hashed {
  168. password = os.Getenv("NTFY_PASSWORD")
  169. }
  170. if username == "" {
  171. return errors.New("username expected, type 'ntfy user add --help' for help")
  172. } else if username == userEveryone || username == user.Everyone {
  173. return errors.New("username not allowed")
  174. } else if !user.AllowedRole(role) {
  175. return errors.New("role must be either 'user' or 'admin'")
  176. }
  177. manager, err := createUserManager(c)
  178. if err != nil {
  179. return err
  180. }
  181. if user, _ := manager.User(username); user != nil {
  182. if c.Bool("ignore-exists") {
  183. fmt.Fprintf(c.App.Writer, "user %s already exists (exited successfully)\n", username)
  184. return nil
  185. }
  186. return fmt.Errorf("user %s already exists", username)
  187. }
  188. if password == "" {
  189. p, err := readPasswordAndConfirm(c)
  190. if err != nil {
  191. return err
  192. }
  193. password = p
  194. }
  195. if err := manager.AddUser(username, password, role, hashed); err != nil {
  196. return err
  197. }
  198. fmt.Fprintf(c.App.Writer, "user %s added with role %s\n", username, role)
  199. return nil
  200. }
  201. func execUserDel(c *cli.Context) error {
  202. username := c.Args().Get(0)
  203. if username == "" {
  204. return errors.New("username expected, type 'ntfy user del --help' for help")
  205. } else if username == userEveryone || username == user.Everyone {
  206. return errors.New("username not allowed")
  207. }
  208. manager, err := createUserManager(c)
  209. if err != nil {
  210. return err
  211. }
  212. if _, err := manager.User(username); errors.Is(err, user.ErrUserNotFound) {
  213. return fmt.Errorf("user %s does not exist", username)
  214. }
  215. if err := manager.RemoveUser(username); err != nil {
  216. return err
  217. }
  218. fmt.Fprintf(c.App.Writer, "user %s removed\n", username)
  219. return nil
  220. }
  221. func execUserChangePass(c *cli.Context) error {
  222. username := c.Args().Get(0)
  223. password, hashed := os.LookupEnv("NTFY_PASSWORD_HASH")
  224. if !hashed {
  225. password = os.Getenv("NTFY_PASSWORD")
  226. }
  227. if username == "" {
  228. return errors.New("username expected, type 'ntfy user change-pass --help' for help")
  229. } else if username == userEveryone || username == user.Everyone {
  230. return errors.New("username not allowed")
  231. }
  232. manager, err := createUserManager(c)
  233. if err != nil {
  234. return err
  235. }
  236. if _, err := manager.User(username); errors.Is(err, user.ErrUserNotFound) {
  237. return fmt.Errorf("user %s does not exist", username)
  238. }
  239. if password == "" {
  240. password, err = readPasswordAndConfirm(c)
  241. if err != nil {
  242. return err
  243. }
  244. }
  245. if err := manager.ChangePassword(username, password, hashed); err != nil {
  246. return err
  247. }
  248. fmt.Fprintf(c.App.Writer, "changed password for user %s\n", username)
  249. return nil
  250. }
  251. func execUserChangeRole(c *cli.Context) error {
  252. username := c.Args().Get(0)
  253. role := user.Role(c.Args().Get(1))
  254. if username == "" || !user.AllowedRole(role) {
  255. return errors.New("username and new role expected, type 'ntfy user change-role --help' for help")
  256. } else if username == userEveryone || username == user.Everyone {
  257. return errors.New("username not allowed")
  258. }
  259. manager, err := createUserManager(c)
  260. if err != nil {
  261. return err
  262. }
  263. if _, err := manager.User(username); errors.Is(err, user.ErrUserNotFound) {
  264. return fmt.Errorf("user %s does not exist", username)
  265. }
  266. if err := manager.ChangeRole(username, role); err != nil {
  267. return err
  268. }
  269. fmt.Fprintf(c.App.Writer, "changed role for user %s to %s\n", username, role)
  270. return nil
  271. }
  272. func execUserHash(c *cli.Context) error {
  273. password, err := readPasswordAndConfirm(c)
  274. if err != nil {
  275. return err
  276. }
  277. hash, err := user.HashPassword(password)
  278. if err != nil {
  279. return fmt.Errorf("failed to hash password: %w", err)
  280. }
  281. fmt.Fprintln(c.App.Writer, hash)
  282. return nil
  283. }
  284. func execUserChangeTier(c *cli.Context) error {
  285. username := c.Args().Get(0)
  286. tier := c.Args().Get(1)
  287. if username == "" {
  288. return errors.New("username and new tier expected, type 'ntfy user change-tier --help' for help")
  289. } else if !user.AllowedTier(tier) && tier != tierReset {
  290. return errors.New("invalid tier, must be tier code, or - to reset")
  291. } else if username == userEveryone || username == user.Everyone {
  292. return errors.New("username not allowed")
  293. }
  294. manager, err := createUserManager(c)
  295. if err != nil {
  296. return err
  297. }
  298. if _, err := manager.User(username); errors.Is(err, user.ErrUserNotFound) {
  299. return fmt.Errorf("user %s does not exist", username)
  300. }
  301. if tier == tierReset {
  302. if err := manager.ResetTier(username); err != nil {
  303. return err
  304. }
  305. fmt.Fprintf(c.App.Writer, "removed tier from user %s\n", username)
  306. } else {
  307. if err := manager.ChangeTier(username, tier); err != nil {
  308. return err
  309. }
  310. fmt.Fprintf(c.App.Writer, "changed tier for user %s to %s\n", username, tier)
  311. }
  312. return nil
  313. }
  314. func execUserList(c *cli.Context) error {
  315. manager, err := createUserManager(c)
  316. if err != nil {
  317. return err
  318. }
  319. users, err := manager.Users()
  320. if err != nil {
  321. return err
  322. }
  323. return showUsers(c, manager, users)
  324. }
  325. func createUserManager(c *cli.Context) (*user.Manager, error) {
  326. authFile := c.String("auth-file")
  327. authStartupQueries := c.String("auth-startup-queries")
  328. authDefaultAccess := c.String("auth-default-access")
  329. if authFile == "" {
  330. return nil, errors.New("option auth-file not set; auth is unconfigured for this server")
  331. } else if !util.FileExists(authFile) {
  332. return nil, errors.New("auth-file does not exist; please start the server at least once to create it")
  333. }
  334. authDefault, err := user.ParsePermission(authDefaultAccess)
  335. if err != nil {
  336. return nil, errors.New("if set, auth-default-access must start set to 'read-write', 'read-only', 'write-only' or 'deny-all'")
  337. }
  338. authConfig := &user.Config{
  339. Filename: authFile,
  340. StartupQueries: authStartupQueries,
  341. DefaultAccess: authDefault,
  342. ProvisionEnabled: false, // Hack: Do not re-provision users on manager initialization
  343. BcryptCost: user.DefaultUserPasswordBcryptCost,
  344. QueueWriterInterval: user.DefaultUserStatsQueueWriterInterval,
  345. }
  346. return user.NewManager(authConfig)
  347. }
  348. func readPasswordAndConfirm(c *cli.Context) (string, error) {
  349. fmt.Fprint(c.App.ErrWriter, "password: ")
  350. password, err := util.ReadPassword(c.App.Reader)
  351. if err != nil {
  352. return "", err
  353. } else if len(password) == 0 {
  354. return "", errors.New("password cannot be empty")
  355. }
  356. fmt.Fprintf(c.App.ErrWriter, "\r%s\rconfirm: ", strings.Repeat(" ", 25))
  357. confirm, err := util.ReadPassword(c.App.Reader)
  358. if err != nil {
  359. return "", err
  360. }
  361. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 25))
  362. if subtle.ConstantTimeCompare(confirm, password) != 1 {
  363. return "", errors.New("passwords do not match: try it again, but this time type slooowwwlly")
  364. }
  365. return string(password), nil
  366. }