-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathAccessControlServiceTest.java
More file actions
413 lines (347 loc) · 16.6 KB
/
Copy pathAccessControlServiceTest.java
File metadata and controls
413 lines (347 loc) · 16.6 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
package com.dbaagent.service.security;
import com.dbaagent.model.Chat;
import com.dbaagent.model.ChatFeedback;
import com.dbaagent.model.ConnectionOwnershipType;
import com.dbaagent.model.DatabaseConnection;
import com.dbaagent.model.EffectiveConnectionAccess;
import com.dbaagent.repository.AnalysisHistoryRepository;
import com.dbaagent.repository.ChatFeedbackRepository;
import com.dbaagent.repository.ChatRepository;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class AccessControlServiceTest {
@Mock
private ConnectionAccessService connectionAccessService;
@Mock
private ChatRepository chatRepository;
@Mock
private ChatFeedbackRepository chatFeedbackRepository;
@Mock
private AnalysisHistoryRepository analysisHistoryRepository;
@InjectMocks
private AccessControlService accessControlService;
@BeforeEach
void setUp() {
ReflectionTestUtils.setField(accessControlService, "authEnabled", true);
}
@AfterEach
void tearDown() {
SecurityContextHolder.clearContext();
com.dbaagent.security.ImpersonationContext.clear();
}
@Test
void ownerCanAccessOwnConnection() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("alice", null, List.of())
);
when(connectionAccessService.resolveAccess("conn-1", "alice", false))
.thenReturn(resolved("conn-1", EffectiveConnectionAccess.OWNER, ConnectionOwnershipType.OWNED));
assertDoesNotThrow(() -> accessControlService.assertCanAccessConnection("conn-1"));
}
@Test
void nonOwnerIsDenied() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("bob", null, List.of())
);
when(connectionAccessService.resolveAccess("conn-1", "bob", false))
.thenReturn(resolved("conn-1", EffectiveConnectionAccess.NONE, null));
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> accessControlService.assertCanAccessConnection("conn-1"));
assertEquals(403, ex.getStatusCode().value());
}
@Test
void adminCanAccessAnyConnection() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
"carol",
null,
List.of(new SimpleGrantedAuthority("ROLE_ADMIN"))
)
);
when(connectionAccessService.resolveAccess("conn-1", "carol", true))
.thenReturn(resolved("conn-1", EffectiveConnectionAccess.ADMIN, ConnectionOwnershipType.ADMIN));
assertDoesNotThrow(() -> accessControlService.assertCanAccessConnection("conn-1"));
}
/**
* Profile switch has to punch through the auth-disabled admin bypass.
* Otherwise an admin "viewing as" an editor still sees every connection.
*/
@Test
void impersonationDisablesAdminBypassWhileAuthIsOff() {
ReflectionTestUtils.setField(accessControlService, "authEnabled", false);
com.dbaagent.model.User impersonator = new com.dbaagent.model.User();
impersonator.setId(1L);
impersonator.setUsername("admin");
impersonator.setRole("ADMIN");
com.dbaagent.model.User target = new com.dbaagent.model.User();
target.setId(2L);
target.setUsername("marts-editor");
target.setRole("DEVELOPER");
com.dbaagent.security.ImpersonationContext.enter(
new com.dbaagent.security.ImpersonationContext.State(impersonator, target)
);
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("marts-editor", null, List.of())
);
when(connectionAccessService.resolveAccess("conn-1", "marts-editor", false))
.thenReturn(resolved("conn-1", EffectiveConnectionAccess.CHAT_EDITOR, ConnectionOwnershipType.ASSIGNED));
assertFalse(accessControlService.isCurrentUserAdmin());
assertEquals("marts-editor", accessControlService.requireCurrentUsername());
assertDoesNotThrow(() -> accessControlService.assertCanUseChatEditor("conn-1"));
verify(connectionAccessService).resolveAccess("conn-1", "marts-editor", false);
verify(connectionAccessService, never()).resolveAccess(eq("conn-1"), eq(null), eq(true));
}
/**
* The dev-mode bypass has to be coherent. Every other check here honours
* security.auth.enabled, so this one throwing 403 meant turning auth off turned chat
* off — the opposite of what the flag advertises.
*/
@Test
void withAuthDisabledTheCurrentUsernameFallsBackInsteadOfThrowing() {
ReflectionTestUtils.setField(accessControlService, "authEnabled", false);
SecurityContextHolder.clearContext();
assertEquals("admin", accessControlService.requireCurrentUsername());
}
/** With auth on — every real deployment — an anonymous caller is still refused. */
@Test
void withAuthEnabledAnAnonymousCallerIsStillRefused() {
SecurityContextHolder.clearContext();
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> accessControlService.requireCurrentUsername());
assertEquals(403, ex.getStatusCode().value());
}
/** A real principal always wins over the fallback, however the flag is set. */
@Test
void aRealPrincipalIsUsedEvenWithAuthDisabled() {
ReflectionTestUtils.setField(accessControlService, "authEnabled", false);
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("alice", null, List.of())
);
assertEquals("alice", accessControlService.requireCurrentUsername());
}
/**
* A client generates a chat id when the user opens a conversation and sends it with
* the first message. Rejecting that as "Chat not found" rejected the opening message
* of every new conversation.
*/
@Test
void aChatIdThatDoesNotExistYetIsAllowedThrough() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("alice", null, List.of())
);
when(chatRepository.existsById("brand-new-chat")).thenReturn(false);
assertDoesNotThrow(() ->
accessControlService.assertChatBelongsToConnectionIfPresent("brand-new-chat", "conn-1"));
}
/**
* The leniency above must not become a probe. {@code findAccessibleChatIfPresent}
* matches on id AND owner, so it returns empty for "someone else's chat" exactly as
* it does for "no such chat" — if the two were collapsed, passing another user's
* chat id would sail straight through.
*/
@Test
void anotherUsersChatIsStillRejectedByTheLenientCheck() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("alice", null, List.of())
);
when(chatRepository.existsById("chat-1")).thenReturn(true);
when(chatRepository.findByIdAndOwnerUsernameIgnoreCase("chat-1", "alice"))
.thenReturn(Optional.empty());
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> accessControlService.assertChatBelongsToConnectionIfPresent("chat-1", "conn-1"));
assertEquals(404, ex.getStatusCode().value());
}
/** An existing, owned chat still has to match the connection it is used with. */
@Test
void anExistingChatStillMustBelongToTheRequestedConnection() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("alice", null, List.of())
);
Chat chat = new Chat();
chat.setId("chat-1");
chat.setConnectionId("conn-2");
chat.setOwnerUsername("alice");
when(chatRepository.existsById("chat-1")).thenReturn(true);
when(chatRepository.findByIdAndOwnerUsernameIgnoreCase("chat-1", "alice"))
.thenReturn(Optional.of(chat));
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> accessControlService.assertChatBelongsToConnectionIfPresent("chat-1", "conn-1"));
assertEquals(403, ex.getStatusCode().value());
}
@Test
void chatMustBelongToRequestedConnection() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("alice", null, List.of())
);
Chat chat = new Chat();
chat.setId("chat-1");
chat.setConnectionId("conn-2");
chat.setOwnerUsername("alice");
when(chatRepository.findByIdAndOwnerUsernameIgnoreCase("chat-1", "alice")).thenReturn(Optional.of(chat));
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> accessControlService.assertChatBelongsToConnection("chat-1", "conn-1"));
assertEquals(403, ex.getStatusCode().value());
}
@Test
void userCannotAccessAnotherUsersChatEvenWithConnectionAccess() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("alice", null, List.of())
);
when(chatRepository.findByIdAndOwnerUsernameIgnoreCase("chat-1", "alice")).thenReturn(Optional.empty());
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> accessControlService.assertCanAccessChat("chat-1"));
assertEquals(404, ex.getStatusCode().value());
}
@Test
void feedbackAccessUsesUnderlyingConnectionOwnership() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("alice", null, List.of())
);
ChatFeedback feedback = new ChatFeedback();
feedback.setId("fb-1");
feedback.setConnectionId("conn-1");
when(chatFeedbackRepository.findById("fb-1")).thenReturn(Optional.of(feedback));
when(connectionAccessService.resolveAccess("conn-1", "alice", false))
.thenReturn(resolved("conn-1", EffectiveConnectionAccess.FULL_CONTENT, ConnectionOwnershipType.ASSIGNED));
assertDoesNotThrow(() -> accessControlService.assertCanAccessFeedback("fb-1"));
}
/**
* Guards the CHAT_EDITOR branch of {@link EffectiveConnectionAccess} itself.
*
* <p>Note this state is no longer reachable from a real grant: connection access
* levels collapsed to a single tier, so {@code ConnectionAccessService.resolveAccess}
* returns FULL_CONTENT for every grant (see
* {@code ConnectionAccessLevelCollapseTest}). This test stubs the resolver directly,
* so it exercises the enum's semantics, not the resolution path — keep it for the
* former, do not read it as evidence about the latter.
*/
@Test
void assignedChatEditorUserCanUseChatEditor() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("dave", null, List.of())
);
when(connectionAccessService.resolveAccess("conn-1", "dave", false))
.thenReturn(resolved("conn-1", EffectiveConnectionAccess.CHAT_EDITOR, ConnectionOwnershipType.ASSIGNED));
assertDoesNotThrow(() -> accessControlService.assertCanUseChatEditor("conn-1"));
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> accessControlService.assertCanManageConnectionContent("conn-1"));
assertEquals(403, ex.getStatusCode().value());
}
@Test
void dbaMayMutateSqlButIsNotAdmin() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
"dba-user",
null,
List.of(new SimpleGrantedAuthority("ROLE_DBA"))
)
);
assertTrue(accessControlService.currentUserMayMutateSql());
assertFalse(accessControlService.isCurrentUserAdmin());
}
@Test
void adminMayMutateSql() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
"admin",
null,
List.of(new SimpleGrantedAuthority("ROLE_ADMIN"))
)
);
assertTrue(accessControlService.currentUserMayMutateSql());
assertTrue(accessControlService.isCurrentUserAdmin());
}
@Test
void developerMayNotMutateSql() {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(
"dev",
null,
List.of(new SimpleGrantedAuthority("ROLE_DEVELOPER"))
)
);
assertFalse(accessControlService.currentUserMayMutateSql());
assertFalse(accessControlService.isCurrentUserAdmin());
}
@Test
void impersonatingDbaAllowsMutateSql() {
com.dbaagent.model.User impersonator = new com.dbaagent.model.User();
impersonator.setId(1L);
impersonator.setUsername("admin");
impersonator.setRole("ADMIN");
com.dbaagent.model.User target = new com.dbaagent.model.User();
target.setId(2L);
target.setUsername("dba-target");
target.setRole("DBA");
com.dbaagent.security.ImpersonationContext.enter(
new com.dbaagent.security.ImpersonationContext.State(impersonator, target)
);
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("dba-target", null, List.of())
);
assertTrue(accessControlService.currentUserMayMutateSql());
assertFalse(accessControlService.isCurrentUserAdmin());
}
/**
* An admin viewing as a user who lacks access to a connection sees access denied.
*
* <p>This is the backend counterpart to the frontend fix: when the admin selects a
* connection, then uses "View as" to switch to a user without access to that connection,
* the UI should not be able to make API calls against the connection. The UI fix clears
* the stale connectionId; this test ensures the backend also correctly denies access.
*/
@Test
void impersonatingUserWithoutAccessDeniesConnection() {
com.dbaagent.model.User impersonator = new com.dbaagent.model.User();
impersonator.setId(1L);
impersonator.setUsername("admin");
impersonator.setRole("ADMIN");
com.dbaagent.model.User target = new com.dbaagent.model.User();
target.setId(2L);
target.setUsername("mart-viewer");
target.setRole("DEVELOPER");
com.dbaagent.security.ImpersonationContext.enter(
new com.dbaagent.security.ImpersonationContext.State(impersonator, target)
);
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken("mart-viewer", null, List.of())
);
// The target user has no grant on conn-1
when(connectionAccessService.resolveAccess("conn-1", "mart-viewer", false))
.thenReturn(resolved("conn-1", EffectiveConnectionAccess.NONE, null));
// Verify: admin bypass is disabled during impersonation
assertFalse(accessControlService.isCurrentUserAdmin());
// Verify: attempting to access the connection should throw 403
ResponseStatusException ex = assertThrows(ResponseStatusException.class,
() -> accessControlService.assertCanUseChatEditor("conn-1"));
assertEquals(403, ex.getStatusCode().value());
}
private ConnectionAccessService.ResolvedConnectionAccess resolved(
String connectionId,
EffectiveConnectionAccess effectiveAccess,
ConnectionOwnershipType ownershipType
) {
DatabaseConnection connection = new DatabaseConnection();
connection.setId(connectionId);
return ConnectionAccessService.ResolvedConnectionAccess.builder()
.connection(connection)
.effectiveAccess(effectiveAccess)
.ownershipType(ownershipType)
.build();
}
}