user.go 13 KB

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