1
0

user.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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: "list",
  120. Aliases: []string{"l"},
  121. Usage: "Shows a list of users",
  122. Action: execUserList,
  123. Description: `Shows a list of all configured users, including the everyone ('*') user.
  124. This command is an alias to calling 'ntfy access' (display access control list).
  125. This is a server-only command. It directly reads from user.db as defined in the server config
  126. file server.yml. The command only works if 'auth-file' is properly defined.
  127. `,
  128. },
  129. },
  130. Description: `Manage users of the ntfy server.
  131. The command allows you to add/remove/change users in the ntfy user database, as well as change
  132. passwords or roles.
  133. This is a server-only command. It directly manages the user.db as defined in the server config
  134. file server.yml. The command only works if 'auth-file' is properly defined. Please also refer
  135. to the related command 'ntfy access'.
  136. Examples:
  137. ntfy user list # Shows list of users (alias: 'ntfy access')
  138. ntfy user add phil # Add regular user phil
  139. NTFY_PASSWORD=... ntfy user add phil # As above, using env variable to set password (for scripts)
  140. ntfy user add --role=admin phil # Add admin user phil
  141. ntfy user del phil # Delete user phil
  142. ntfy user change-pass phil # Change password for user phil
  143. NTFY_PASSWORD=.. ntfy user change-pass phil # As above, using env variable to set password (for scripts)
  144. ntfy user change-role phil admin # Make user phil an admin
  145. For the 'ntfy user add' and 'ntfy user change-pass' commands, you may set the NTFY_PASSWORD environment
  146. variable to pass the new password. This is useful if you are creating/updating users via scripts.
  147. `,
  148. }
  149. func execUserAdd(c *cli.Context) error {
  150. username := c.Args().Get(0)
  151. role := user.Role(c.String("role"))
  152. password, hashed := os.LookupEnv("NTFY_PASSWORD_HASH")
  153. if !hashed {
  154. password = os.Getenv("NTFY_PASSWORD")
  155. }
  156. if username == "" {
  157. return errors.New("username expected, type 'ntfy user add --help' for help")
  158. } else if username == userEveryone || username == user.Everyone {
  159. return errors.New("username not allowed")
  160. } else if !user.AllowedRole(role) {
  161. return errors.New("role must be either 'user' or 'admin'")
  162. }
  163. manager, err := createUserManager(c)
  164. if err != nil {
  165. return err
  166. }
  167. if user, _ := manager.User(username); user != nil {
  168. if c.Bool("ignore-exists") {
  169. fmt.Fprintf(c.App.ErrWriter, "user %s already exists (exited successfully)\n", username)
  170. return nil
  171. }
  172. return fmt.Errorf("user %s already exists", username)
  173. }
  174. if password == "" {
  175. p, err := readPasswordAndConfirm(c)
  176. if err != nil {
  177. return err
  178. }
  179. password = p
  180. }
  181. if err := manager.AddUser(username, password, role, hashed); err != nil {
  182. return err
  183. }
  184. fmt.Fprintf(c.App.ErrWriter, "user %s added with role %s\n", username, role)
  185. return nil
  186. }
  187. func execUserDel(c *cli.Context) error {
  188. username := c.Args().Get(0)
  189. if username == "" {
  190. return errors.New("username expected, type 'ntfy user del --help' for help")
  191. } else if username == userEveryone || username == user.Everyone {
  192. return errors.New("username not allowed")
  193. }
  194. manager, err := createUserManager(c)
  195. if err != nil {
  196. return err
  197. }
  198. if _, err := manager.User(username); errors.Is(err, user.ErrUserNotFound) {
  199. return fmt.Errorf("user %s does not exist", username)
  200. }
  201. if err := manager.RemoveUser(username); err != nil {
  202. return err
  203. }
  204. fmt.Fprintf(c.App.ErrWriter, "user %s removed\n", username)
  205. return nil
  206. }
  207. func execUserChangePass(c *cli.Context) error {
  208. username := c.Args().Get(0)
  209. password, hashed := os.LookupEnv("NTFY_PASSWORD_HASH")
  210. if !hashed {
  211. password = os.Getenv("NTFY_PASSWORD")
  212. }
  213. if username == "" {
  214. return errors.New("username expected, type 'ntfy user change-pass --help' for help")
  215. } else if username == userEveryone || username == user.Everyone {
  216. return errors.New("username not allowed")
  217. }
  218. manager, err := createUserManager(c)
  219. if err != nil {
  220. return err
  221. }
  222. if _, err := manager.User(username); errors.Is(err, user.ErrUserNotFound) {
  223. return fmt.Errorf("user %s does not exist", username)
  224. }
  225. if password == "" {
  226. password, err = readPasswordAndConfirm(c)
  227. if err != nil {
  228. return err
  229. }
  230. }
  231. if err := manager.ChangePassword(username, password, hashed); err != nil {
  232. return err
  233. }
  234. fmt.Fprintf(c.App.ErrWriter, "changed password for user %s\n", username)
  235. return nil
  236. }
  237. func execUserChangeRole(c *cli.Context) error {
  238. username := c.Args().Get(0)
  239. role := user.Role(c.Args().Get(1))
  240. if username == "" || !user.AllowedRole(role) {
  241. return errors.New("username and new role expected, type 'ntfy user change-role --help' for help")
  242. } else if username == userEveryone || username == user.Everyone {
  243. return errors.New("username not allowed")
  244. }
  245. manager, err := createUserManager(c)
  246. if err != nil {
  247. return err
  248. }
  249. if _, err := manager.User(username); errors.Is(err, user.ErrUserNotFound) {
  250. return fmt.Errorf("user %s does not exist", username)
  251. }
  252. if err := manager.ChangeRole(username, role); err != nil {
  253. return err
  254. }
  255. fmt.Fprintf(c.App.ErrWriter, "changed role for user %s to %s\n", username, role)
  256. return nil
  257. }
  258. func execUserChangeTier(c *cli.Context) error {
  259. username := c.Args().Get(0)
  260. tier := c.Args().Get(1)
  261. if username == "" {
  262. return errors.New("username and new tier expected, type 'ntfy user change-tier --help' for help")
  263. } else if !user.AllowedTier(tier) && tier != tierReset {
  264. return errors.New("invalid tier, must be tier code, or - to reset")
  265. } else if username == userEveryone || username == user.Everyone {
  266. return errors.New("username not allowed")
  267. }
  268. manager, err := createUserManager(c)
  269. if err != nil {
  270. return err
  271. }
  272. if _, err := manager.User(username); errors.Is(err, user.ErrUserNotFound) {
  273. return fmt.Errorf("user %s does not exist", username)
  274. }
  275. if tier == tierReset {
  276. if err := manager.ResetTier(username); err != nil {
  277. return err
  278. }
  279. fmt.Fprintf(c.App.ErrWriter, "removed tier from user %s\n", username)
  280. } else {
  281. if err := manager.ChangeTier(username, tier); err != nil {
  282. return err
  283. }
  284. fmt.Fprintf(c.App.ErrWriter, "changed tier for user %s to %s\n", username, tier)
  285. }
  286. return nil
  287. }
  288. func execUserList(c *cli.Context) error {
  289. manager, err := createUserManager(c)
  290. if err != nil {
  291. return err
  292. }
  293. users, err := manager.Users()
  294. if err != nil {
  295. return err
  296. }
  297. return showUsers(c, manager, users)
  298. }
  299. func createUserManager(c *cli.Context) (*user.Manager, error) {
  300. authFile := c.String("auth-file")
  301. authStartupQueries := c.String("auth-startup-queries")
  302. authDefaultAccess := c.String("auth-default-access")
  303. if authFile == "" {
  304. return nil, errors.New("option auth-file not set; auth is unconfigured for this server")
  305. } else if !util.FileExists(authFile) {
  306. return nil, errors.New("auth-file does not exist; please start the server at least once to create it")
  307. }
  308. authDefault, err := user.ParsePermission(authDefaultAccess)
  309. if err != nil {
  310. return nil, errors.New("if set, auth-default-access must start set to 'read-write', 'read-only', 'write-only' or 'deny-all'")
  311. }
  312. authConfig := &user.Config{
  313. Filename: authFile,
  314. StartupQueries: authStartupQueries,
  315. DefaultAccess: authDefault,
  316. ProvisionEnabled: false, // Do not re-provision users on manager initialization
  317. BcryptCost: user.DefaultUserPasswordBcryptCost,
  318. QueueWriterInterval: user.DefaultUserStatsQueueWriterInterval,
  319. }
  320. return user.NewManager(authConfig)
  321. }
  322. func readPasswordAndConfirm(c *cli.Context) (string, error) {
  323. fmt.Fprint(c.App.ErrWriter, "password: ")
  324. password, err := util.ReadPassword(c.App.Reader)
  325. if err != nil {
  326. return "", err
  327. } else if len(password) == 0 {
  328. return "", errors.New("password cannot be empty")
  329. }
  330. fmt.Fprintf(c.App.ErrWriter, "\r%s\rconfirm: ", strings.Repeat(" ", 25))
  331. confirm, err := util.ReadPassword(c.App.Reader)
  332. if err != nil {
  333. return "", err
  334. }
  335. fmt.Fprintf(c.App.ErrWriter, "\r%s\r", strings.Repeat(" ", 25))
  336. if subtle.ConstantTimeCompare(confirm, password) != 1 {
  337. return "", errors.New("passwords do not match: try it again, but this time type slooowwwlly")
  338. }
  339. return string(password), nil
  340. }