user.go 9.5 KB

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