user.go 10 KB

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