You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

388 lines
11 KiB

Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
4 years ago
Restricted users (#6274) * Restricted users (#4334): initial implementation * Add User.IsRestricted & UI to edit it * Pass user object instead of user id to places where IsRestricted flag matters * Restricted users: maintain access rows for all referenced repos (incl public) * Take logged in user & IsRestricted flag into account in org/repo listings, searches and accesses * Add basic repo access tests for restricted users Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Mention restricted users in the faq Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert unnecessary change `.isUserPartOfOrg` -> `.IsUserPartOfOrg` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Remove unnecessary `org.IsOrganization()` call Signed-off-by: Manush Dodunekov <manush@stendahls.se> * Revert to an `int64` keyed `accessMap` * Add type `userAccess` * Add convenience func updateUserAccess() * Turn accessMap into a `map[int64]userAccess` Signed-off-by: Manush Dodunekov <manush@stendahls.se> * or even better: `map[int64]*userAccess` * updateUserAccess(): use tighter syntax as suggested by lafriks * even tighter * Avoid extra loop * Don't disclose limited orgs to unauthenticated users * Don't assume block only applies to orgs * Use an array of `VisibleType` for filtering * fix yet another thinko * Ok - no need for u * Revert "Ok - no need for u" This reverts commit 5c3e886aabd5acd997a3b35687d322439732c200. Co-authored-by: Antoine GIRARD <sapk@users.noreply.github.com> Co-authored-by: Lauris BH <lauris@nix.lv>
4 years ago
  1. // Copyright 2017 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "fmt"
  7. "math/rand"
  8. "strings"
  9. "testing"
  10. "code.gitea.io/gitea/modules/setting"
  11. "code.gitea.io/gitea/modules/util"
  12. "github.com/stretchr/testify/assert"
  13. )
  14. func TestUserIsPublicMember(t *testing.T) {
  15. assert.NoError(t, PrepareTestDatabase())
  16. tt := []struct {
  17. uid int64
  18. orgid int64
  19. expected bool
  20. }{
  21. {2, 3, true},
  22. {4, 3, false},
  23. {5, 6, true},
  24. {5, 7, false},
  25. }
  26. for _, v := range tt {
  27. t.Run(fmt.Sprintf("UserId%dIsPublicMemberOf%d", v.uid, v.orgid), func(t *testing.T) {
  28. testUserIsPublicMember(t, v.uid, v.orgid, v.expected)
  29. })
  30. }
  31. }
  32. func testUserIsPublicMember(t *testing.T, uid int64, orgID int64, expected bool) {
  33. user, err := GetUserByID(uid)
  34. assert.NoError(t, err)
  35. assert.Equal(t, expected, user.IsPublicMember(orgID))
  36. }
  37. func TestIsUserOrgOwner(t *testing.T) {
  38. assert.NoError(t, PrepareTestDatabase())
  39. tt := []struct {
  40. uid int64
  41. orgid int64
  42. expected bool
  43. }{
  44. {2, 3, true},
  45. {4, 3, false},
  46. {5, 6, true},
  47. {5, 7, true},
  48. }
  49. for _, v := range tt {
  50. t.Run(fmt.Sprintf("UserId%dIsOrgOwnerOf%d", v.uid, v.orgid), func(t *testing.T) {
  51. testIsUserOrgOwner(t, v.uid, v.orgid, v.expected)
  52. })
  53. }
  54. }
  55. func testIsUserOrgOwner(t *testing.T, uid int64, orgID int64, expected bool) {
  56. user, err := GetUserByID(uid)
  57. assert.NoError(t, err)
  58. assert.Equal(t, expected, user.IsUserOrgOwner(orgID))
  59. }
  60. func TestGetUserEmailsByNames(t *testing.T) {
  61. assert.NoError(t, PrepareTestDatabase())
  62. // ignore none active user email
  63. assert.Equal(t, []string{"user8@example.com"}, GetUserEmailsByNames([]string{"user8", "user9"}))
  64. assert.Equal(t, []string{"user8@example.com", "user5@example.com"}, GetUserEmailsByNames([]string{"user8", "user5"}))
  65. assert.Equal(t, []string{"user8@example.com"}, GetUserEmailsByNames([]string{"user8", "user7"}))
  66. }
  67. func TestUser_APIFormat(t *testing.T) {
  68. user, err := GetUserByID(1)
  69. assert.NoError(t, err)
  70. assert.True(t, user.IsAdmin)
  71. apiUser := user.APIFormat()
  72. assert.True(t, apiUser.IsAdmin)
  73. user, err = GetUserByID(2)
  74. assert.NoError(t, err)
  75. assert.False(t, user.IsAdmin)
  76. apiUser = user.APIFormat()
  77. assert.False(t, apiUser.IsAdmin)
  78. }
  79. func TestCanCreateOrganization(t *testing.T) {
  80. assert.NoError(t, PrepareTestDatabase())
  81. admin := AssertExistsAndLoadBean(t, &User{ID: 1}).(*User)
  82. assert.True(t, admin.CanCreateOrganization())
  83. user := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
  84. assert.True(t, user.CanCreateOrganization())
  85. // Disable user create organization permission.
  86. user.AllowCreateOrganization = false
  87. assert.False(t, user.CanCreateOrganization())
  88. setting.Admin.DisableRegularOrgCreation = true
  89. user.AllowCreateOrganization = true
  90. assert.True(t, admin.CanCreateOrganization())
  91. assert.False(t, user.CanCreateOrganization())
  92. }
  93. func TestSearchUsers(t *testing.T) {
  94. assert.NoError(t, PrepareTestDatabase())
  95. testSuccess := func(opts *SearchUserOptions, expectedUserOrOrgIDs []int64) {
  96. users, _, err := SearchUsers(opts)
  97. assert.NoError(t, err)
  98. if assert.Len(t, users, len(expectedUserOrOrgIDs)) {
  99. for i, expectedID := range expectedUserOrOrgIDs {
  100. assert.EqualValues(t, expectedID, users[i].ID)
  101. }
  102. }
  103. }
  104. // test orgs
  105. testOrgSuccess := func(opts *SearchUserOptions, expectedOrgIDs []int64) {
  106. opts.Type = UserTypeOrganization
  107. testSuccess(opts, expectedOrgIDs)
  108. }
  109. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 1, PageSize: 2},
  110. []int64{3, 6})
  111. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 2, PageSize: 2},
  112. []int64{7, 17})
  113. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 3, PageSize: 2},
  114. []int64{19, 25})
  115. testOrgSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 4, PageSize: 2},
  116. []int64{26})
  117. testOrgSuccess(&SearchUserOptions{Page: 5, PageSize: 2},
  118. []int64{})
  119. // test users
  120. testUserSuccess := func(opts *SearchUserOptions, expectedUserIDs []int64) {
  121. opts.Type = UserTypeIndividual
  122. testSuccess(opts, expectedUserIDs)
  123. }
  124. testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 1},
  125. []int64{1, 2, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24, 27, 28, 29})
  126. testUserSuccess(&SearchUserOptions{Page: 1, IsActive: util.OptionalBoolFalse},
  127. []int64{9})
  128. testUserSuccess(&SearchUserOptions{OrderBy: "id ASC", Page: 1, IsActive: util.OptionalBoolTrue},
  129. []int64{1, 2, 4, 5, 8, 10, 11, 12, 13, 14, 15, 16, 18, 20, 21, 24, 28, 29})
  130. testUserSuccess(&SearchUserOptions{Keyword: "user1", OrderBy: "id ASC", Page: 1, IsActive: util.OptionalBoolTrue},
  131. []int64{1, 10, 11, 12, 13, 14, 15, 16, 18})
  132. // order by name asc default
  133. testUserSuccess(&SearchUserOptions{Keyword: "user1", Page: 1, IsActive: util.OptionalBoolTrue},
  134. []int64{1, 10, 11, 12, 13, 14, 15, 16, 18})
  135. }
  136. func TestDeleteUser(t *testing.T) {
  137. test := func(userID int64) {
  138. assert.NoError(t, PrepareTestDatabase())
  139. user := AssertExistsAndLoadBean(t, &User{ID: userID}).(*User)
  140. ownedRepos := make([]*Repository, 0, 10)
  141. assert.NoError(t, x.Find(&ownedRepos, &Repository{OwnerID: userID}))
  142. if len(ownedRepos) > 0 {
  143. err := DeleteUser(user)
  144. assert.Error(t, err)
  145. assert.True(t, IsErrUserOwnRepos(err))
  146. return
  147. }
  148. orgUsers := make([]*OrgUser, 0, 10)
  149. assert.NoError(t, x.Find(&orgUsers, &OrgUser{UID: userID}))
  150. for _, orgUser := range orgUsers {
  151. if err := RemoveOrgUser(orgUser.OrgID, orgUser.UID); err != nil {
  152. assert.True(t, IsErrLastOrgOwner(err))
  153. return
  154. }
  155. }
  156. assert.NoError(t, DeleteUser(user))
  157. AssertNotExistsBean(t, &User{ID: userID})
  158. CheckConsistencyFor(t, &User{}, &Repository{})
  159. }
  160. test(2)
  161. test(4)
  162. test(8)
  163. test(11)
  164. }
  165. func TestEmailNotificationPreferences(t *testing.T) {
  166. assert.NoError(t, PrepareTestDatabase())
  167. for _, test := range []struct {
  168. expected string
  169. userID int64
  170. }{
  171. {EmailNotificationsEnabled, 1},
  172. {EmailNotificationsEnabled, 2},
  173. {EmailNotificationsOnMention, 3},
  174. {EmailNotificationsOnMention, 4},
  175. {EmailNotificationsEnabled, 5},
  176. {EmailNotificationsEnabled, 6},
  177. {EmailNotificationsDisabled, 7},
  178. {EmailNotificationsEnabled, 8},
  179. {EmailNotificationsOnMention, 9},
  180. } {
  181. user := AssertExistsAndLoadBean(t, &User{ID: test.userID}).(*User)
  182. assert.Equal(t, test.expected, user.EmailNotifications())
  183. // Try all possible settings
  184. assert.NoError(t, user.SetEmailNotifications(EmailNotificationsEnabled))
  185. assert.Equal(t, EmailNotificationsEnabled, user.EmailNotifications())
  186. assert.NoError(t, user.SetEmailNotifications(EmailNotificationsOnMention))
  187. assert.Equal(t, EmailNotificationsOnMention, user.EmailNotifications())
  188. assert.NoError(t, user.SetEmailNotifications(EmailNotificationsDisabled))
  189. assert.Equal(t, EmailNotificationsDisabled, user.EmailNotifications())
  190. }
  191. }
  192. func TestHashPasswordDeterministic(t *testing.T) {
  193. b := make([]byte, 16)
  194. rand.Read(b)
  195. u := &User{Salt: string(b)}
  196. algos := []string{"pbkdf2", "argon2", "scrypt", "bcrypt"}
  197. for j := 0; j < len(algos); j++ {
  198. u.PasswdHashAlgo = algos[j]
  199. for i := 0; i < 50; i++ {
  200. // generate a random password
  201. rand.Read(b)
  202. pass := string(b)
  203. // save the current password in the user - hash it and store the result
  204. u.HashPassword(pass)
  205. r1 := u.Passwd
  206. // run again
  207. u.HashPassword(pass)
  208. r2 := u.Passwd
  209. // assert equal (given the same salt+pass, the same result is produced) except bcrypt
  210. if u.PasswdHashAlgo == "bcrypt" {
  211. assert.NotEqual(t, r1, r2)
  212. } else {
  213. assert.Equal(t, r1, r2)
  214. }
  215. }
  216. }
  217. }
  218. func BenchmarkHashPassword(b *testing.B) {
  219. // BenchmarkHashPassword ensures that it takes a reasonable amount of time
  220. // to hash a password - in order to protect from brute-force attacks.
  221. pass := "password1337"
  222. bs := make([]byte, 16)
  223. rand.Read(bs)
  224. u := &User{Salt: string(bs), Passwd: pass}
  225. b.ResetTimer()
  226. for i := 0; i < b.N; i++ {
  227. u.HashPassword(pass)
  228. }
  229. }
  230. func TestGetOrgRepositoryIDs(t *testing.T) {
  231. assert.NoError(t, PrepareTestDatabase())
  232. user2 := AssertExistsAndLoadBean(t, &User{ID: 2}).(*User)
  233. user4 := AssertExistsAndLoadBean(t, &User{ID: 4}).(*User)
  234. user5 := AssertExistsAndLoadBean(t, &User{ID: 5}).(*User)
  235. accessibleRepos, err := user2.GetOrgRepositoryIDs()
  236. assert.NoError(t, err)
  237. // User 2's team has access to private repos 3, 5, repo 32 is a public repo of the organization
  238. assert.Equal(t, []int64{3, 5, 23, 24, 32}, accessibleRepos)
  239. accessibleRepos, err = user4.GetOrgRepositoryIDs()
  240. assert.NoError(t, err)
  241. // User 4's team has access to private repo 3, repo 32 is a public repo of the organization
  242. assert.Equal(t, []int64{3, 32}, accessibleRepos)
  243. accessibleRepos, err = user5.GetOrgRepositoryIDs()
  244. assert.NoError(t, err)
  245. // User 5's team has no access to any repo
  246. assert.Len(t, accessibleRepos, 0)
  247. }
  248. func TestNewGitSig(t *testing.T) {
  249. users := make([]*User, 0, 20)
  250. sess := x.NewSession()
  251. defer sess.Close()
  252. sess.Find(&users)
  253. for _, user := range users {
  254. sig := user.NewGitSig()
  255. assert.NotContains(t, sig.Name, "<")
  256. assert.NotContains(t, sig.Name, ">")
  257. assert.NotContains(t, sig.Name, "\n")
  258. assert.NotEqual(t, len(strings.TrimSpace(sig.Name)), 0)
  259. }
  260. }
  261. func TestDisplayName(t *testing.T) {
  262. users := make([]*User, 0, 20)
  263. sess := x.NewSession()
  264. defer sess.Close()
  265. sess.Find(&users)
  266. for _, user := range users {
  267. displayName := user.DisplayName()
  268. assert.Equal(t, strings.TrimSpace(displayName), displayName)
  269. if len(strings.TrimSpace(user.FullName)) == 0 {
  270. assert.Equal(t, user.Name, displayName)
  271. }
  272. assert.NotEqual(t, len(strings.TrimSpace(displayName)), 0)
  273. }
  274. }
  275. func TestCreateUser(t *testing.T) {
  276. user := &User{
  277. Name: "GiteaBot",
  278. Email: "GiteaBot@gitea.io",
  279. Passwd: ";p['////..-++']",
  280. IsAdmin: false,
  281. Theme: setting.UI.DefaultTheme,
  282. MustChangePassword: false,
  283. }
  284. assert.NoError(t, CreateUser(user))
  285. assert.NoError(t, DeleteUser(user))
  286. }
  287. func TestCreateUser_Issue5882(t *testing.T) {
  288. // Init settings
  289. _ = setting.Admin
  290. passwd := ".//.;1;;//.,-=_"
  291. tt := []struct {
  292. user *User
  293. disableOrgCreation bool
  294. }{
  295. {&User{Name: "GiteaBot", Email: "GiteaBot@gitea.io", Passwd: passwd, MustChangePassword: false}, false},
  296. {&User{Name: "GiteaBot2", Email: "GiteaBot2@gitea.io", Passwd: passwd, MustChangePassword: false}, true},
  297. }
  298. setting.Service.DefaultAllowCreateOrganization = true
  299. for _, v := range tt {
  300. setting.Admin.DisableRegularOrgCreation = v.disableOrgCreation
  301. assert.NoError(t, CreateUser(v.user))
  302. u, err := GetUserByEmail(v.user.Email)
  303. assert.NoError(t, err)
  304. assert.Equal(t, !u.AllowCreateOrganization, v.disableOrgCreation)
  305. assert.NoError(t, DeleteUser(v.user))
  306. }
  307. }
  308. func TestGetUserIDsByNames(t *testing.T) {
  309. //ignore non existing
  310. IDs, err := GetUserIDsByNames([]string{"user1", "user2", "none_existing_user"}, true)
  311. assert.NoError(t, err)
  312. assert.Equal(t, []int64{1, 2}, IDs)
  313. //ignore non existing
  314. IDs, err = GetUserIDsByNames([]string{"user1", "do_not_exist"}, false)
  315. assert.Error(t, err)
  316. assert.Equal(t, []int64(nil), IDs)
  317. }