Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.cruise.activity.config;

import com.cruise.common.security.RemoteRbacConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration(proxyBeanMethods = false)
@Import(RemoteRbacConfiguration.class)
public class RbacConfig {
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public ApiResponse<OperationalNotificationEventDto> broadcastOperationalAlert(
@RequestHeader(value = "X-Caller-Role", required = false) String callerRole,
@Valid @RequestBody OperationalBroadcastRequest request
) {
if (callerRole == null || !java.util.Set.of("CREW", "STAFF", "OFFICER", "ADMIN", "SYSTEM")
if (callerRole == null || !java.util.Set.of("CREW", "STAFF", "OFFICER", "ADMIN", "SYSTEM", "SYSTEM_ADMIN", "OPERATIONS_MANAGER")
.contains(callerRole.trim().toUpperCase())) {
throw new AccessDeniedException("Chỉ nhân viên hoặc hệ thống mới có quyền phát thông báo vận hành");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public ApiResponse<PassengerServiceReviewResponse> triageReview(
}

private void verifyAdminAuthorization(String callerRole) {
if (callerRole == null || !java.util.Set.of("SYSTEM_ADMIN", "ADMIN", "STAFF")
if (callerRole == null || !java.util.Set.of("SYSTEM_ADMIN", "ADMIN", "STAFF", "OPERATIONS_MANAGER")
.contains(callerRole.trim().toUpperCase())) {
throw new AccessDeniedException("Yêu cầu quyền SYSTEM_ADMIN để truy cập quản trị đánh giá");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ public ApiResponse<Page<TourProviderResponse>> getTourProviders(
}

private void verifyProviderManagementAuthorization(String callerRole) {
if (callerRole == null || !"SHORE_EXCURSION_MANAGER".equalsIgnoreCase(callerRole.trim())) {
if (callerRole == null || !java.util.Set.of("SHORE_EXCURSION_MANAGER", "OPERATIONS_MANAGER", "SYSTEM_ADMIN")
.contains(callerRole.trim().toUpperCase(java.util.Locale.ROOT))) {
throw new AccessDeniedException("Yêu cầu quyền SHORE_EXCURSION_MANAGER");
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public boolean canReceive(OperationalNotificationEventDto event) {
|| callerRole.equalsIgnoreCase("STAFF")
|| callerRole.equalsIgnoreCase("OFFICER")
|| callerRole.equalsIgnoreCase("ADMIN")
|| isCanonicalCrew(callerRole)
);
}
if (event.getScope() == NotificationScope.PASSENGER_ONLY) {
Expand All @@ -45,6 +46,14 @@ public boolean canReceive(OperationalNotificationEventDto event) {
}
return true;
}

private static boolean isCanonicalCrew(String role) {
try {
return com.cruise.common.enums.Role.valueOf(role) != com.cruise.common.enums.Role.PASSENGER;
} catch (IllegalArgumentException ex) {
return false;
}
}
}

private final List<SubscriberContext> subscribers = new CopyOnWriteArrayList<>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@DisplayName("Cruise Activity Service Context Tests")
class CruiseActivityApplicationTest {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@DisplayName("Activity Check-in & Attendance Controller Integration Tests (KAN-223)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
* 6. PATCH /api/excursions/{id}/status & GET allowed-transitions - Quản lý trạng thái và danh sách trạng thái cho phép.
* 7. DELETE /api/excursions/{id} - Xóa mềm tour bờ (active=false, status=CANCELLED, 404).
*/
@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
* 2. POST /api/excursions/{id}/groups/auto-generate
* 3. GET /api/excursions/{id}/groups/export/csv
*/
@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
* 10. GET /api/excursions/{id}/groups/export/csv - Xuất danh sách đoàn dạng CSV
* 11. Edge cases, Validation và Business Rule Error Handling
*/
@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
* 1. POST /api/excursions/{id}/vehicles & GET & PATCH & DELETE
* 2. POST /api/excursions/{id}/guides & GET & PATCH & DELETE
*/
@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
* 4. PATCH /api/excursions/{id}/passengers/bulk-group - Gán đoàn & xe hàng loạt
* 5. DELETE /api/excursions/{id}/passengers/{passengerId} - Xóa hành khách khỏi tour bờ
*/
@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
* Integration Test suite kiểm thử tích hợp toàn diện cho các thao tác cập nhật trạng thái tour bờ (KAN-191).
* Kiểm thử thông qua MockMvc và verify trực tiếp trong database.
*/
@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@DisplayName("Excursion Status Updates Integration Tests (KAN-191)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
* 6. Escape dữ liệu đặc biệt trong file CSV (dấu phẩy, dấu nháy kép, ký tự xuống dòng).
* 7. Kiểm tra Content-Type, Content-Disposition header của response CSV.
*/
@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
/**
* Integration Test cho Passenger Catalog Browsing & Realtime Capacity (KAN-213)
*/
@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc(addFilters = false)
@ActiveProfiles("test")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@AutoConfigureMockMvc
@Transactional
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@

import static org.assertj.core.api.Assertions.assertThat;

@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@ActiveProfiles("test")
@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.cruise.activity.security;

import com.cruise.activity.repository.OnboardActivityRepository;
import com.cruise.common.enums.Role;
import com.cruise.common.security.*;
import java.util.Optional;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.EnumSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.transaction.annotation.Transactional;
import static org.assertj.core.api.Assertions.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

@SpringBootTest @AutoConfigureMockMvc @Transactional
class CrossRoleActivityApiTest {
@Autowired MockMvc mvc;
@Autowired OnboardActivityRepository activities;
@MockitoBean AccessTokenVerifier verifier;

@ParameterizedTest @EnumSource(Role.class)
void onlyActivityManagersOpsAndAdminCanCreateActivities(Role role) throws Exception {
when(verifier.verify("role-token")).thenReturn(Optional.of(new VerifiedCaller(5L, "actor", role)));
boolean allowed = Set.of(Role.SYSTEM_ADMIN, Role.OPERATIONS_MANAGER, Role.ACTIVITY_MANAGER).contains(role);
long before = activities.count();
mvc.perform(post("/api/activities").header("Authorization", "Bearer role-token")
.header("X-Caller-Role", "SYSTEM_ADMIN").contentType(MediaType.APPLICATION_JSON).content("""
{"tourId":777,"title":"RBAC Activity","location":"Deck 7","activityDate":"2027-01-01",
"startTime":"09:00:00","endTime":"10:00:00","maxCapacity":20,"price":0,"isIncluded":true}
"""))
.andExpect(status().is(allowed ? 201 : 403));
assertThat(activities.count()).isEqualTo(before + (allowed ? 1 : 0));
}

@Test void directServiceRequestsRejectAnonymousSpoofedHeadersAndAuthOutages() throws Exception {
mvc.perform(get("/api/activities/tour/777").header("X-Caller-Role", "SYSTEM_ADMIN"))
.andExpect(status().isUnauthorized());
when(verifier.verify("outage")).thenThrow(new AccessTokenVerifier.Unavailable(new RuntimeException()));
mvc.perform(get("/api/activities/tour/777").header("Authorization", "Bearer outage"))
.andExpect(status().isServiceUnavailable());
mvc.perform(get("/api/activities/health")).andExpect(status().isOk());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@

import static org.assertj.core.api.Assertions.assertThat;

@org.springframework.context.annotation.Import(com.cruise.activity.support.AuthenticatedApiTestConfig.class)
@SpringBootTest
@DisplayName("Activity Concurrency & Capacity Enforcement Integration Test (KAN-218)")
class ActivityConcurrencyIntegrationTest {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package com.cruise.activity.support;

import com.cruise.common.enums.Role;
import com.cruise.common.security.*;
import java.util.Optional;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.webmvc.test.autoconfigure.MockMvcBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;

/** Explicit authenticated fixture for pre-existing domain tests; production RBAC remains active. */
@TestConfiguration(proxyBeanMethods = false)
public class AuthenticatedApiTestConfig {
@Bean @Primary
public AccessTokenVerifier domainTestIdentityVerifier() {
return token -> "domain-test-admin".equals(token)
? Optional.of(new VerifiedCaller(1L, "domain.test", Role.SYSTEM_ADMIN)) : Optional.empty();
}
@Bean
public MockMvcBuilderCustomizer authenticatedDomainRequests() {
return builder -> builder.defaultRequest(get("/").header("Authorization", "Bearer domain-test-admin"));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.cruise.auth.config;

import com.cruise.common.security.RbacFilterConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

@Configuration(proxyBeanMethods = false)
@Import(RbacFilterConfiguration.class)
public class RbacConfig {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package com.cruise.auth.controller;

import com.cruise.auth.dto.VerifyTokenRequest;
import com.cruise.common.dto.ApiResponse;
import com.cruise.common.enums.Role;
import com.cruise.common.security.*;
import jakarta.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AccessControlController {
private final AccessTokenVerifier verifier;
public AccessControlController(AccessTokenVerifier verifier) { this.verifier = verifier; }

/** The token itself is proof. Invalid tokens return no identity and no detailed claims. */
@PostMapping("/access-context")
public ApiResponse<VerifiedCaller> accessContext(@RequestBody VerifyTokenRequest request) {
String token = request.getToken();
if (token == null || token.isBlank() || token.length() > 8192) return ApiResponse.ok(null);
return ApiResponse.ok(verifier.verify(token).orElse(null));
}

@GetMapping("/roles")
public ApiResponse<Map<Role, Set<Permission>>> roles() {
Map<Role, Set<Permission>> grants = new LinkedHashMap<>();
Arrays.stream(Role.values()).forEach(role -> grants.put(role, RolePermissions.permissions(role)));
return ApiResponse.ok(grants);
}

@GetMapping("/permissions")
public ApiResponse<Set<Permission>> permissions(HttpServletRequest request) {
var caller = (VerifiedCaller) request.getAttribute(VerifiedCaller.ATTRIBUTE);
return ApiResponse.ok(RolePermissions.permissions(caller.role()));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ public UserController(UserService userService) {
}

@PostMapping
public ResponseEntity<ApiResponse<com.cruise.auth.dto.UserResponseDto>> createUser(@RequestBody com.cruise.auth.dto.UserDto userDto) {
public ResponseEntity<ApiResponse<com.cruise.auth.dto.UserResponseDto>> createUser(@jakarta.validation.Valid @RequestBody com.cruise.auth.dto.UserDto userDto) {
try {
User user = new User();
user.setUsername(userDto.getUsername());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,18 @@
@AllArgsConstructor
@Builder
public class UserDto {
@jakarta.validation.constraints.NotBlank
@jakarta.validation.constraints.Size(min = 3, max = 50)
private String username;
private String password;
@jakarta.validation.constraints.NotBlank
@jakarta.validation.constraints.Size(max = 100)
private String fullName;
@jakarta.validation.constraints.NotBlank
@jakarta.validation.constraints.Email
@jakarta.validation.constraints.Size(max = 100)
private String email;
@jakarta.validation.constraints.NotNull
private Role role;
private String cabinNumber;
private String rfidTag;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package com.cruise.auth.entity;

import jakarta.persistence.*;
import java.time.Instant;
import lombok.Getter;
import lombok.NoArgsConstructor;

/** Append-only identity mutations; never contains passwords or bearer tokens. */
@Entity
@Table(name = "identity_audit_events", indexes = @Index(name = "idx_identity_audit_occurred", columnList = "occurred_at"))
@Getter
@NoArgsConstructor(access = lombok.AccessLevel.PROTECTED)
public class IdentityAuditEvent {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "occurred_at", nullable = false, updatable = false)
private Instant occurredAt;
@Column(nullable = false, updatable = false, length = 30)
private String action;
@Column(name = "actor_user_id", updatable = false)
private Long actorUserId;
@Column(name = "target_username", nullable = false, updatable = false, length = 50)
private String targetUsername;
@Column(name = "target_role", nullable = false, updatable = false, length = 30)
private String targetRole;

public IdentityAuditEvent(String action, Long actorUserId, String targetUsername, String targetRole) {
this.occurredAt = Instant.now();
this.action = action;
this.actorUserId = actorUserId;
this.targetUsername = targetUsername;
this.targetRole = targetRole;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package com.cruise.auth.repository;

import com.cruise.auth.entity.IdentityAuditEvent;
import org.springframework.data.jpa.repository.JpaRepository;

public interface IdentityAuditRepository extends JpaRepository<IdentityAuditEvent, Long> {}
Loading
Loading