summaryrefslogtreecommitdiff
path: root/src/test/kotlin/dev/dnpm/etl/processor/security/UserRoleServiceTest.kt
blob: 2a5a481f1cf8397249d1ed8272249d0ab2296d6e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*
 * This file is part of ETL-Processor
 *
 * Copyright (c) 2023       Comprehensive Cancer Center Mainfranken
 * Copyright (c) 2024-2026  Paul-Christian Volkmer, Datenintegrationszentrum Philipps-Universität Marburg and Contributors
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

package dev.dnpm.etl.processor.security

import java.time.Instant
import java.util.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.Mock
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.*
import org.springframework.security.core.session.SessionInformation
import org.springframework.security.core.session.SessionRegistry
import org.springframework.security.oauth2.core.oidc.OidcIdToken
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser
import org.springframework.security.oauth2.core.oidc.user.OidcUser

@ExtendWith(MockitoExtension::class)
class UserRoleServiceTest {

  private lateinit var userRoleRepository: UserRoleRepository
  private lateinit var sessionRegistry: SessionRegistry

  private lateinit var userRoleService: UserRoleService

  @BeforeEach
  fun setup(@Mock userRoleRepository: UserRoleRepository, @Mock sessionRegistry: SessionRegistry) {
    this.userRoleRepository = userRoleRepository
    this.sessionRegistry = sessionRegistry

    this.userRoleService = UserRoleService(userRoleRepository, sessionRegistry)
  }

  @Test
  fun shouldDelegateFindAllToRepository() {
    userRoleService.findAll()

    verify(userRoleRepository, times(1)).findAll()
  }

  @Nested
  inner class WithExistingUserRole {

    @BeforeEach
    fun setup() {
      doAnswer { invocation ->
            Optional.of(UserRole(invocation.getArgument(0), "patrick.tester", Role.USER))
          }
          .whenever(userRoleRepository)
          .findById(any<Long>())

      doAnswer { _ -> listOf(dummyPrincipal()) }.whenever(sessionRegistry).allPrincipals
    }

    @Test
    fun shouldUpdateUserRole() {
      userRoleService.updateUserRole(1, Role.ADMIN)

      val userRoleCaptor = argumentCaptor<UserRole>()
      verify(userRoleRepository, times(1)).save(userRoleCaptor.capture())

      assertThat(userRoleCaptor.firstValue.id).isEqualTo(1L)
      assertThat(userRoleCaptor.firstValue.role).isEqualTo(Role.ADMIN)
    }

    @Test
    fun shouldExpireSessionOnUpdate() {
      val dummySessions = dummySessions()
      whenever(sessionRegistry.getAllSessions(any(), any<Boolean>())).thenReturn(dummySessions)

      assertThat(dummySessions.filter { it.isExpired }).hasSize(0)

      userRoleService.updateUserRole(1, Role.ADMIN)

      verify(sessionRegistry, times(1)).getAllSessions(any<OidcUser>(), any<Boolean>())

      assertThat(dummySessions.filter { it.isExpired }).hasSize(2)
    }

    @Test
    fun shouldDeleteUserRole() {
      userRoleService.deleteUserRole(1)

      val userRoleCaptor = argumentCaptor<UserRole>()
      verify(userRoleRepository, times(1)).delete(userRoleCaptor.capture())

      assertThat(userRoleCaptor.firstValue.id).isEqualTo(1L)
      assertThat(userRoleCaptor.firstValue.role).isEqualTo(Role.USER)
    }

    @Test
    fun shouldExpireSessionOnDelete() {
      val dummySessions = dummySessions()
      whenever(sessionRegistry.getAllSessions(any(), any<Boolean>())).thenReturn(dummySessions)

      assertThat(dummySessions.filter { it.isExpired }).hasSize(0)

      userRoleService.deleteUserRole(1)

      verify(sessionRegistry, times(1)).getAllSessions(any<OidcUser>(), any<Boolean>())

      assertThat(dummySessions.filter { it.isExpired }).hasSize(2)
    }
  }

  @Nested
  inner class WithoutExistingUserRole {

    @BeforeEach
    fun setup() {
      doAnswer { _ -> Optional.empty<UserRole>() }
          .whenever(userRoleRepository)
          .findById(any<Long>())
    }

    @Test
    fun shouldNotUpdateUserRole() {
      userRoleService.updateUserRole(1, Role.ADMIN)

      verify(userRoleRepository, never()).save(any<UserRole>())
    }

    @Test
    fun shouldNotExpireSessionOnUpdate() {
      userRoleService.updateUserRole(1, Role.ADMIN)

      verify(sessionRegistry, never()).getAllSessions(any<OidcUser>(), any<Boolean>())
    }

    @Test
    fun shouldNotDeleteUserRole() {
      userRoleService.deleteUserRole(1)

      verify(userRoleRepository, never()).delete(any<UserRole>())
    }

    @Test
    fun shouldNotExpireSessionOnDelete() {
      userRoleService.deleteUserRole(1)

      verify(sessionRegistry, never()).getAllSessions(any<OidcUser>(), any<Boolean>())
    }
  }

  companion object {
    private fun dummyPrincipal() =
        DefaultOidcUser(
            listOf(),
            OidcIdToken(
                "anytokenvalue",
                Instant.now(),
                Instant.now().plusSeconds(10),
                mapOf("sub" to "testsub", "preferred_username" to "patrick.tester"),
            ),
        )

    private fun dummySessions() =
        listOf(
            SessionInformation(
                dummyPrincipal(),
                "SESSIONID1",
                Date.from(Instant.now()),
            ),
            SessionInformation(
                dummyPrincipal(),
                "SESSIONID2",
                Date.from(Instant.now()),
            ),
        )
  }
}