|
@@ -0,0 +1,469 @@
|
|
|
|
|
+package com.zksy.web.controller.cockpit;
|
|
|
|
|
+
|
|
|
|
|
+import com.alibaba.fastjson2.JSON;
|
|
|
|
|
+import com.alibaba.fastjson2.JSONObject;
|
|
|
|
|
+import com.zksy.base.domain.EquipmentBase;
|
|
|
|
|
+import com.zksy.base.mapper.EquipmentBaseMapper;
|
|
|
|
|
+import com.zksy.base.mapper.EquipmentVideoBindingMapper;
|
|
|
|
|
+import com.zksy.base.mapper.VideoSessionMapper;
|
|
|
|
|
+import com.zksy.base.service.EquipmentBaseService;
|
|
|
|
|
+import com.zksy.base.video.VideoCollectorClient;
|
|
|
|
|
+import com.zksy.base.video.VideoDeviceRecord;
|
|
|
|
|
+import com.zksy.base.video.VideoDeviceService;
|
|
|
|
|
+import com.zksy.base.video.VideoSession;
|
|
|
|
|
+import com.zksy.cockpit.video.CockpitVideoService;
|
|
|
|
|
+import com.zksy.common.core.redis.RedisCache;
|
|
|
|
|
+import com.zksy.framework.config.ResourcesConfig;
|
|
|
|
|
+import com.zksy.framework.config.SecurityConfig;
|
|
|
|
|
+import com.zksy.framework.config.properties.PermitAllUrlProperties;
|
|
|
|
|
+import com.zksy.framework.security.filter.JwtAuthenticationTokenFilter;
|
|
|
|
|
+import com.zksy.framework.security.handle.AuthenticationEntryPointImpl;
|
|
|
|
|
+import com.zksy.framework.security.handle.CockpitAuthenticationEntryPoint;
|
|
|
|
|
+import com.zksy.framework.security.handle.LogoutSuccessHandlerImpl;
|
|
|
|
|
+import com.zksy.framework.web.exception.GlobalExceptionHandler;
|
|
|
|
|
+import com.zksy.framework.web.service.PermissionService;
|
|
|
|
|
+import com.zksy.framework.web.service.TokenService;
|
|
|
|
|
+import com.zksy.web.controller.video.VideoDeviceController;
|
|
|
|
|
+import org.junit.jupiter.api.AfterEach;
|
|
|
|
|
+import org.junit.jupiter.api.BeforeEach;
|
|
|
|
|
+import org.junit.jupiter.api.Test;
|
|
|
|
|
+import org.junit.jupiter.params.ParameterizedTest;
|
|
|
|
|
+import org.junit.jupiter.params.provider.CsvSource;
|
|
|
|
|
+import org.junit.jupiter.params.provider.ValueSource;
|
|
|
|
|
+import com.zksy.common.exception.ServiceException;
|
|
|
|
|
+import org.springframework.beans.BeanUtils;
|
|
|
|
|
+import org.springframework.context.annotation.Bean;
|
|
|
|
|
+import org.springframework.context.annotation.Configuration;
|
|
|
|
|
+import org.springframework.context.annotation.Import;
|
|
|
|
|
+import org.springframework.core.env.MapPropertySource;
|
|
|
|
|
+import org.springframework.data.redis.core.RedisTemplate;
|
|
|
|
|
+import org.springframework.http.MediaType;
|
|
|
|
|
+import org.springframework.mock.web.MockServletContext;
|
|
|
|
|
+import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
|
|
|
|
+import org.springframework.security.core.context.SecurityContextHolder;
|
|
|
|
|
+import org.springframework.security.core.userdetails.UserDetailsService;
|
|
|
|
|
+import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
|
|
|
|
+import org.springframework.test.web.servlet.MockMvc;
|
|
|
|
|
+import org.springframework.test.web.servlet.ResultActions;
|
|
|
|
|
+import org.springframework.test.web.servlet.setup.MockMvcBuilders;
|
|
|
|
|
+import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
|
|
|
|
|
+import org.springframework.web.filter.CorsFilter;
|
|
|
|
|
+import org.springframework.web.servlet.config.annotation.EnableWebMvc;
|
|
|
|
|
+
|
|
|
|
|
+import javax.servlet.Filter;
|
|
|
|
|
+import java.nio.charset.StandardCharsets;
|
|
|
|
|
+import java.time.Clock;
|
|
|
|
|
+import java.time.Instant;
|
|
|
|
|
+import java.time.ZoneOffset;
|
|
|
|
|
+import java.util.List;
|
|
|
|
|
+import java.util.Map;
|
|
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
|
|
+
|
|
|
|
|
+import static org.mockito.ArgumentMatchers.any;
|
|
|
|
|
+import static org.mockito.ArgumentMatchers.anyString;
|
|
|
|
|
+import static org.mockito.Mockito.*;
|
|
|
|
|
+import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
|
|
|
|
|
+import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
|
|
|
|
+
|
|
|
|
|
+/** HTTP seam with the real security/JWT chain and both business services.
|
|
|
|
|
+ * Only DB, Redis storage and media transport are replaced. No server, scheduler,
|
|
|
|
|
+ * database connection or media/network request is started by this fixture.
|
|
|
|
|
+ */
|
|
|
|
|
+class CockpitVideoControllerTest {
|
|
|
|
|
+ private static final String ROOT = "/api/cockpit/v1/video";
|
|
|
|
|
+ private static final String CODE = " CN/摄像机+%2F 001 ";
|
|
|
|
|
+ private static final String ID = "internal-ledger-id";
|
|
|
|
|
+ private static final String GB = "34020000002000000001";
|
|
|
|
|
+ private static final String CHANNEL = "34020000001320000001";
|
|
|
|
|
+ private static final String START = "/api/play/start/" + GB + "/" + CHANNEL;
|
|
|
|
|
+ private static final String STOP = "/api/play/stop/" + GB + "/" + CHANNEL;
|
|
|
|
|
+ private static final String URL = "https://media.invalid/live.flv";
|
|
|
|
|
+ private AnnotationConfigWebApplicationContext context;
|
|
|
|
|
+ private MockMvc mvc;
|
|
|
|
|
+ private EquipmentBaseMapper devices;
|
|
|
|
|
+ private EquipmentVideoBindingMapper bindings;
|
|
|
|
|
+ private VideoSessionMapper sessions;
|
|
|
|
|
+ private VideoCollectorClient collector;
|
|
|
|
|
+ private EquipmentBase equipment;
|
|
|
|
|
+ private VideoDeviceRecord binding;
|
|
|
|
|
+
|
|
|
|
|
+ @BeforeEach
|
|
|
|
|
+ void setUp() {
|
|
|
|
|
+ SecurityContextHolder.clearContext();
|
|
|
|
|
+ context = new AnnotationConfigWebApplicationContext();
|
|
|
|
|
+ context.setServletContext(new MockServletContext());
|
|
|
|
|
+ context.getEnvironment().getPropertySources().addFirst(new MapPropertySource("video-test", Map.of(
|
|
|
|
|
+ "token.header", "Authorization", "token.secret", "offline-video-contract-only-secret-not-for-production", "token.expireTime", "60")));
|
|
|
|
|
+ context.register(HttpConfiguration.class);
|
|
|
|
|
+ context.refresh();
|
|
|
|
|
+ mvc = MockMvcBuilders.webAppContextSetup(context)
|
|
|
|
|
+ .addFilters(context.getBean("springSecurityFilterChain", Filter.class)).build();
|
|
|
|
|
+ devices = context.getBean(EquipmentBaseMapper.class);
|
|
|
|
|
+ bindings = context.getBean(EquipmentVideoBindingMapper.class);
|
|
|
|
|
+ sessions = context.getBean(VideoSessionMapper.class);
|
|
|
|
|
+ collector = context.getBean(VideoCollectorClient.class);
|
|
|
|
|
+ equipment = new EquipmentBase();
|
|
|
|
|
+ equipment.setEquipmentId(ID);
|
|
|
|
|
+ equipment.setEquipmentCode(CODE);
|
|
|
|
|
+ equipment.setEquipmentName("测试摄像机");
|
|
|
|
|
+ equipment.setEquipmentTypeId(20);
|
|
|
|
|
+ when(devices.selectList(any())).thenReturn(List.of(equipment));
|
|
|
|
|
+ binding = new VideoDeviceRecord();
|
|
|
|
|
+ BeanUtils.copyProperties(equipment, binding);
|
|
|
|
|
+ binding.setVideoId(ID);
|
|
|
|
|
+ binding.setDeviceCode(CODE);
|
|
|
|
|
+ binding.setDeviceName("测试摄像机");
|
|
|
|
|
+ binding.setSourceType("GB28181");
|
|
|
|
|
+ binding.setGbDeviceId(GB);
|
|
|
|
|
+ binding.setGbChannelId(CHANNEL);
|
|
|
|
|
+ when(bindings.find(ID)).thenReturn(binding);
|
|
|
|
|
+ when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", URL));
|
|
|
|
|
+ Map<String, VideoSession> rows = new ConcurrentHashMap<>();
|
|
|
|
|
+ when(sessions.insert(any(VideoSession.class))).thenAnswer(call -> {
|
|
|
|
|
+ VideoSession row = call.getArgument(0);
|
|
|
|
|
+ rows.put(row.getSessionId(), copy(row));
|
|
|
|
|
+ return 1;
|
|
|
|
|
+ });
|
|
|
|
|
+ when(sessions.selectById(anyString())).thenAnswer(call -> copy(rows.get(call.getArgument(0))));
|
|
|
|
|
+ when(sessions.updateById(any(VideoSession.class))).thenAnswer(call -> {
|
|
|
|
|
+ VideoSession row = call.getArgument(0);
|
|
|
|
|
+ return rows.replace(row.getSessionId(), copy(row)) == null ? 0 : 1;
|
|
|
|
|
+ });
|
|
|
|
|
+ // Literal single-viewer DB fixture; no copy of shared-count business logic.
|
|
|
|
|
+ when(sessions.selectCount(any())).thenReturn(0L);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @AfterEach
|
|
|
|
|
+ void tearDown() {
|
|
|
|
|
+ if (context != null) context.close();
|
|
|
|
|
+ SecurityContextHolder.clearContext();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void anonymousDeviceLookupKeepsExactBusinessCodeAndPublishesOnlyConfirmedLiveCapability() throws Exception {
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device").param("deviceCode", CODE).header("X-Request-Id", "video-lookup-1"))
|
|
|
|
|
+ .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(200))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.deviceCode").value(CODE))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.deviceName").value("测试摄像机"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.typeCode").value("20"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.bound").value(true))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.capabilities.live").value(true))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.capabilities.records").value(false))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.capabilities.playback").value(false))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.capabilities.playbackControl").value(false))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.capabilities.ptz").value(false))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.capabilities.ptzStopGuaranteed").value(false))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.requestId").value("video-lookup-1"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.serverTime").value("2026-11-10T16:00:00+08:00"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.equipmentId").doesNotExist())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.videoId").doesNotExist())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.gbChannelId").doesNotExist());
|
|
|
|
|
+ verifyNoInteractions(collector, sessions);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void anonymousViewerStartsMaintainsAndIdempotentlyReleasesOnlyItsOwnSession() throws Exception {
|
|
|
|
|
+ when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", URL,
|
|
|
|
|
+ "rtcs", "https://media.invalid/index/api/webrtc?app=rtp&stream=stream_01&type=play",
|
|
|
|
|
+ "native", true, "secret", "internal-secret", "proxyKey", "internal-key"));
|
|
|
|
|
+ JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.deviceCode").value(CODE))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.mode").value("LIVE"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.sessionToken").isNotEmpty())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.flv").value(URL))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.webrtc").value("https://media.invalid/index/api/webrtc?app=rtp&stream=stream_01&type=play"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.native").value(false))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.secret").doesNotExist())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.stream").doesNotExist())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.proxyKey").doesNotExist())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.secret").doesNotExist())
|
|
|
|
|
+ .andExpect(header().string("Cache-Control", "no-store"))
|
|
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8))
|
|
|
|
|
+ .getJSONObject("data");
|
|
|
|
|
+ clearInvocations(collector);
|
|
|
|
|
+ session(viewer, "stop", "A".repeat(43)).andExpect(status().isForbidden())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.category").value("SESSION_FORBIDDEN"));
|
|
|
|
|
+ verifyNoInteractions(collector);
|
|
|
|
|
+ session(viewer, "heartbeat", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("ACTIVE"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.sessionToken").doesNotExist());
|
|
|
|
|
+ session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.status").value("STOPPED"));
|
|
|
|
|
+ session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
|
|
|
|
|
+ verify(collector, times(1)).get(STOP, Map.of());
|
|
|
|
|
+ session(viewer, "heartbeat", viewer.getString("sessionToken")).andExpect(status().isGone())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.category").value("SESSION_EXPIRED"));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @ParameterizedTest
|
|
|
|
|
+ @CsvSource({"GET,/live", "GET,/sessions/example/stop", "GET,/sessions/example/heartbeat",
|
|
|
|
|
+ "GET,/devices/remove", "GET,/records", "POST,/device", "PUT,/live", "DELETE,/live",
|
|
|
|
|
+ "POST,/sessions/example/control", "POST,/ptz", "POST,/playback", "POST,/devices",
|
|
|
|
|
+ "POST,/sessions/example/nested/stop", "POST,/live/nested"})
|
|
|
|
|
+ void onlyTheFourPublishedMethodAndPathPairsAreAnonymous(String method, String path) throws Exception {
|
|
|
|
|
+ mvc.perform(request(org.springframework.http.HttpMethod.valueOf(method), ROOT + path))
|
|
|
|
|
+ .andExpect(status().isUnauthorized()).andExpect(jsonPath("$.code").value(401));
|
|
|
|
|
+ verifyNoInteractions(devices, bindings, sessions, collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @ParameterizedTest
|
|
|
|
|
+ @ValueSource(strings = {"/devices/internal/live", "/devices/internal/playback", "/devices",
|
|
|
|
|
+ "/sessions/another/heartbeat", "/sessions/another/stop", "/sessions/another/control"})
|
|
|
|
|
+ void legacyVideoEndpointsStillRequireBusinessAuthentication(String path) throws Exception {
|
|
|
|
|
+ mvc.perform(post("/api/video" + path)).andExpect(status().isOk()).andExpect(jsonPath("$.code").value(401));
|
|
|
|
|
+ verifyNoInteractions(devices, bindings, sessions, collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @ParameterizedTest
|
|
|
|
|
+ @ValueSource(strings = {"CN/摄像机+%2F 001", " CN/摄像机+%2f 001 ", " CN/摄像机+/ 001 ", "internal-ledger-id"})
|
|
|
|
|
+ void neverNormalizesOrDecodesBusinessCodeAgain(String differentCode) throws Exception {
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device").param("deviceCode", differentCode))
|
|
|
|
|
+ .andExpect(status().isNotFound()).andExpect(jsonPath("$.data.category").value("DEVICE_NOT_FOUND"));
|
|
|
|
|
+ verifyNoInteractions(bindings, sessions, collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void ordinaryDeviceCannotGainVideoFromItsNameOrALeftoverBinding() throws Exception {
|
|
|
|
|
+ equipment.setEquipmentTypeId(12);
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.typeCode").value("12"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.bound").value(false))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.capabilities.live").value(false));
|
|
|
|
|
+ live().andExpect(status().isConflict()).andExpect(jsonPath("$.data.category").value("VIDEO_UNAVAILABLE"));
|
|
|
|
|
+ verifyNoInteractions(bindings, sessions, collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void unboundCameraIsGreyWithoutConsultingMediaOrCollectionRecords() throws Exception {
|
|
|
|
|
+ when(bindings.find(ID)).thenReturn(null);
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.bound").value(false)).andExpect(jsonPath("$.data.capabilities.live").value(false));
|
|
|
|
|
+ live().andExpect(status().isConflict());
|
|
|
|
|
+ verifyNoInteractions(sessions, collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void unknownSourceAndIncompleteGbBindingRemainGrey() throws Exception {
|
|
|
|
|
+ binding.setSourceType("unknown");
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.bound").value(true)).andExpect(jsonPath("$.data.capabilities.live").value(false));
|
|
|
|
|
+ binding.setSourceType("GB28181");
|
|
|
|
|
+ binding.setGbChannelId(null);
|
|
|
|
|
+ live().andExpect(status().isConflict());
|
|
|
|
|
+ verifyNoInteractions(sessions, collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void ambiguousOrFailedLedgerQueriesDoNotGuessADeviceOrLeakDatabaseDetails() throws Exception {
|
|
|
|
|
+ when(devices.selectList(any())).thenReturn(List.of(equipment, equipment));
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isServiceUnavailable())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.category").value("VIDEO_READ_FAILED"));
|
|
|
|
|
+ when(devices.selectList(any())).thenThrow(new IllegalStateException("jdbc password=do-not-publish"));
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isServiceUnavailable())
|
|
|
|
|
+ .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("do-not-publish"))));
|
|
|
|
|
+ verifyNoInteractions(bindings, collector, sessions);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @ParameterizedTest
|
|
|
|
|
+ @ValueSource(strings = {"{}", "{bad-json", "{\"deviceCode\":123}", "{\"deviceCode\":\"\"}",
|
|
|
|
|
+ "{\"deviceCode\":\"x\",\"userId\":1}"})
|
|
|
|
|
+ void malformedLiveRequestsUseThePublicInvalidRequestEnvelope(String body) throws Exception {
|
|
|
|
|
+ mvc.perform(post(ROOT + "/live").contentType(MediaType.APPLICATION_JSON).content(body))
|
|
|
|
|
+ .andExpect(status().isBadRequest()).andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
|
|
|
|
|
+ verifyNoInteractions(devices, bindings, collector, sessions);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void missingDeviceQueryIsBadRequestRatherThanAnInternalError() throws Exception {
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device")).andExpect(status().isBadRequest())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.category").value("INVALID_REQUEST"));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void manualNativeVideoIsExplicitAndNeverLeaksItsLedgerFields() throws Exception {
|
|
|
|
|
+ binding.setSourceType("MANUAL");
|
|
|
|
|
+ binding.setVideoUrl("https://media.invalid/live.mp4");
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.capabilities.live").value(true));
|
|
|
|
|
+ JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.url").value("https://media.invalid/live.mp4"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.native").value(true))
|
|
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
|
|
+ session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
|
|
|
|
|
+ verifyNoInteractions(collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @ParameterizedTest
|
|
|
|
|
+ @ValueSource(strings = {"https://user:password@media.invalid/live.mp4", "https://media.invalid/live.mp4?secret=hidden",
|
|
|
|
|
+ "https://media.invalid/live.flv", "https://media.invalid/error.html", "ws://media.invalid/live.flv"})
|
|
|
|
|
+ void manualSourcesThatCannotBePublicNativeMediaAreGrey(String url) throws Exception {
|
|
|
|
|
+ binding.setSourceType("MANUAL");
|
|
|
|
|
+ binding.setVideoUrl(url);
|
|
|
|
|
+ mvc.perform(get(ROOT + "/device").param("deviceCode", CODE)).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.capabilities.live").value(false));
|
|
|
|
|
+ live().andExpect(status().isConflict());
|
|
|
|
|
+ verifyNoInteractions(collector, sessions);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @ParameterizedTest
|
|
|
|
|
+ @ValueSource(strings = {"https://user:password@media.invalid/live.flv", "https://media.invalid/live.flv?secret=hidden",
|
|
|
|
|
+ "https://media.invalid/live.flv?%73ecret=hidden", "https://media.invalid/live.flv?internal-token=hidden",
|
|
|
|
|
+ "https://media.invalid/live.flv?proxyKey=hidden", "https://media.invalid/live.flv?password=hidden"})
|
|
|
|
|
+ void unsafeMediaAddressTriggersOwnSessionCleanupInsteadOfPublishingCredentials(String url) throws Exception {
|
|
|
|
|
+ when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", url));
|
|
|
|
|
+ live().andExpect(status().isBadGateway()).andExpect(jsonPath("$.data.category").value("VIDEO_START_FAILED"))
|
|
|
|
|
+ .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("hidden"))));
|
|
|
|
|
+ verify(collector).get(STOP, Map.of());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void failedStopIsUnconfirmedAndTheSameOwnerCanRetry() throws Exception {
|
|
|
|
|
+ JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk()).andReturn()
|
|
|
|
|
+ .getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
|
|
+ when(collector.get(STOP, Map.of())).thenThrow(new ServiceException("secret=hidden transport detail"));
|
|
|
|
|
+ session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isServiceUnavailable())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.category").value("CLEANUP_UNCONFIRMED"))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.message").value("清理未确认,请等待回收"));
|
|
|
|
|
+ session(viewer, "heartbeat", viewer.getString("sessionToken")).andExpect(status().isOk());
|
|
|
|
|
+ doReturn(Map.of()).when(collector).get(STOP, Map.of());
|
|
|
|
|
+ session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void unsafeMediaAndFailedCompensationDoNotClaimThatResourcesWereStopped() throws Exception {
|
|
|
|
|
+ when(collector.get(START, Map.of())).thenReturn(Map.of("stream", "stream_01", "flv", URL + "?token=hidden"));
|
|
|
|
|
+ when(collector.get(STOP, Map.of())).thenThrow(new ServiceException("password=hidden"));
|
|
|
|
|
+ live().andExpect(status().isServiceUnavailable()).andExpect(jsonPath("$.data.category").value("CLEANUP_UNCONFIRMED"))
|
|
|
|
|
+ .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("hidden"))));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void twoAnonymousViewersDoNotShareOwnershipOrStopEachOthersLiveStream() throws Exception {
|
|
|
|
|
+ when(sessions.selectCount(any())).thenReturn(0L, 1L, 1L, 0L);
|
|
|
|
|
+ JSONObject first = JSON.parseObject(live().andExpect(status().isOk()).andReturn()
|
|
|
|
|
+ .getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
|
|
+ JSONObject second = JSON.parseObject(live().andExpect(status().isOk()).andReturn()
|
|
|
|
|
+ .getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
|
|
+ org.junit.jupiter.api.Assertions.assertNotEquals(first.getString("sessionToken"), second.getString("sessionToken"));
|
|
|
|
|
+ session(first, "stop", second.getString("sessionToken")).andExpect(status().isForbidden());
|
|
|
|
|
+ clearInvocations(collector);
|
|
|
|
|
+ session(first, "stop", first.getString("sessionToken")).andExpect(status().isOk());
|
|
|
|
|
+ verifyNoInteractions(collector);
|
|
|
|
|
+ session(second, "heartbeat", second.getString("sessionToken")).andExpect(status().isOk());
|
|
|
|
|
+ session(second, "stop", second.getString("sessionToken")).andExpect(status().isOk());
|
|
|
|
|
+ verify(collector).get(STOP, Map.of());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void upstreamFailureIsSanitizedAndNeverReportedAsAnEmptyOrSuccessfulStream() throws Exception {
|
|
|
|
|
+ when(collector.get(START, Map.of())).thenThrow(new ServiceException("password=hidden upstream failure"));
|
|
|
|
|
+ live().andExpect(status().isBadGateway()).andExpect(jsonPath("$.data.category").value("VIDEO_START_FAILED"))
|
|
|
|
|
+ .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("hidden"))));
|
|
|
|
|
+ verify(collector).get(STOP, Map.of());
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void manualRtspCredentialsStayInsideProxyAndOnlyPublicWebRtcIsReturned() throws Exception {
|
|
|
|
|
+ binding.setSourceType("MANUAL");
|
|
|
|
|
+ binding.setVideoUrl("rtsp://user:private-password@camera.invalid/live");
|
|
|
|
|
+ when(collector.post("/internal/video/manual/start", Map.of("id", ID, "url", binding.getVideoUrl())))
|
|
|
|
|
+ .thenReturn(Map.of("stream", "proxy_stream", "proxyKey", "private-proxy-key", "flv", URL,
|
|
|
|
|
+ "webrtc", "https://media.invalid/index/api/webrtc?app=proxy&stream=proxy_stream&type=play"));
|
|
|
|
|
+ JSONObject viewer = JSON.parseObject(live().andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.native").value(false))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.media.webrtc").isNotEmpty())
|
|
|
|
|
+ .andExpect(content().string(org.hamcrest.Matchers.not(org.hamcrest.Matchers.containsString("private-"))))
|
|
|
|
|
+ .andReturn().getResponse().getContentAsString(StandardCharsets.UTF_8)).getJSONObject("data");
|
|
|
|
|
+ session(viewer, "stop", viewer.getString("sessionToken")).andExpect(status().isOk());
|
|
|
|
|
+ verify(collector).post("/internal/video/manual/stop", Map.of("key", "private-proxy-key"));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @ParameterizedTest
|
|
|
|
|
+ @ValueSource(strings = {"/api/cockpit/v1/security-contract-probe", "/api/cockpit/v1/security-contract-probe/nested"})
|
|
|
|
|
+ void existingCockpitReadPolicyAllowsAnonymousGetButNotPost(String path) throws Exception {
|
|
|
|
|
+ mvc.perform(get(path)).andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.reached").value("security-policy-probe"))
|
|
|
|
|
+ .andExpect(jsonPath("$.method").value("GET"));
|
|
|
|
|
+ mvc.perform(post(path)).andExpect(status().isUnauthorized())
|
|
|
|
|
+ .andExpect(jsonPath("$.code").value(401))
|
|
|
|
|
+ .andExpect(jsonPath("$.data.category").value("UNAUTHORIZED"))
|
|
|
|
|
+ .andExpect(jsonPath("$.reached").doesNotExist());
|
|
|
|
|
+ verifyNoInteractions(devices, bindings, sessions, collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @ParameterizedTest
|
|
|
|
|
+ @CsvSource({"GET,/api/security-contract-probe", "POST,/api/security-contract-probe",
|
|
|
|
|
+ "GET,/ws/deviceStatus/nested", "POST,/ws/deviceStatus/nested"})
|
|
|
|
|
+ void theDefaultRuleStillRejectsAnonymousRequestsOutsideExplicitExceptions(String method, String path)
|
|
|
|
|
+ throws Exception {
|
|
|
|
|
+ mvc.perform(request(org.springframework.http.HttpMethod.valueOf(method), path))
|
|
|
|
|
+ .andExpect(status().isOk()).andExpect(jsonPath("$.code").value(401))
|
|
|
|
|
+ .andExpect(jsonPath("$.reached").doesNotExist());
|
|
|
|
|
+ verifyNoInteractions(devices, bindings, sessions, collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Test
|
|
|
|
|
+ void existingWebSocketHandshakePathStillPassesTheRealAuthenticationChain() throws Exception {
|
|
|
|
|
+ // This observes authorization before an Upgrade endpoint, not a real socket handshake.
|
|
|
|
|
+ mvc.perform(get("/ws/deviceStatus").header("Connection", "Upgrade").header("Upgrade", "websocket")
|
|
|
|
|
+ .header("Sec-WebSocket-Version", "13").header("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="))
|
|
|
|
|
+ .andExpect(status().isOk())
|
|
|
|
|
+ .andExpect(jsonPath("$.reached").value("security-policy-probe"))
|
|
|
|
|
+ .andExpect(jsonPath("$.method").value("GET"));
|
|
|
|
|
+ verifyNoInteractions(devices, bindings, sessions, collector);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private ResultActions live() throws Exception {
|
|
|
|
|
+ return mvc.perform(post(ROOT + "/live").contentType(MediaType.APPLICATION_JSON)
|
|
|
|
|
+ .content(JSON.toJSONString(Map.of("deviceCode", CODE))));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private ResultActions session(JSONObject viewer, String action, String token) throws Exception {
|
|
|
|
|
+ return mvc.perform(post(ROOT + "/sessions/{id}/" + action, viewer.getString("sessionId"))
|
|
|
|
|
+ .contentType(MediaType.APPLICATION_JSON).content(JSON.toJSONString(Map.of("sessionToken", token))));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private static VideoSession copy(VideoSession source) {
|
|
|
|
|
+ if (source == null) return null;
|
|
|
|
|
+ VideoSession copy = new VideoSession();
|
|
|
|
|
+ BeanUtils.copyProperties(source, copy);
|
|
|
|
|
+ return copy;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** Replaces the old source-text matcher/count assertions with actual filter-chain outcomes.
|
|
|
|
|
+ * The same endpoint accepts GET and POST, so denied requests cannot pass by falling through to 404.
|
|
|
|
|
+ * Only the downstream HTTP handler is a fixture; SecurityConfig and all authentication filters are real.
|
|
|
|
|
+ */
|
|
|
|
|
+ @org.springframework.web.bind.annotation.RestController
|
|
|
|
|
+ static class SecurityPolicyProbe {
|
|
|
|
|
+ @org.springframework.web.bind.annotation.RequestMapping({"/api/cockpit/v1/security-contract-probe",
|
|
|
|
|
+ "/api/cockpit/v1/security-contract-probe/nested", "/api/security-contract-probe",
|
|
|
|
|
+ "/ws/deviceStatus", "/ws/deviceStatus/nested"})
|
|
|
|
|
+ Map<String, String> reached(javax.servlet.http.HttpServletRequest request) {
|
|
|
|
|
+ return Map.of("reached", "security-policy-probe", "method", request.getMethod());
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ @Configuration
|
|
|
|
|
+ @EnableWebMvc
|
|
|
|
|
+ @EnableWebSecurity
|
|
|
|
|
+ @Import({SecurityConfig.class, PermitAllUrlProperties.class, PermissionService.class,
|
|
|
|
|
+ JwtAuthenticationTokenFilter.class, TokenService.class, RedisCache.class,
|
|
|
|
|
+ AuthenticationEntryPointImpl.class, CockpitAuthenticationEntryPoint.class,
|
|
|
|
|
+ LogoutSuccessHandlerImpl.class, GlobalExceptionHandler.class,
|
|
|
|
|
+ CockpitVideoController.class, CockpitVideoService.class, VideoDeviceController.class, SecurityPolicyProbe.class})
|
|
|
|
|
+ static class HttpConfiguration {
|
|
|
|
|
+ @Bean Clock clock() { return Clock.fixed(Instant.parse("2026-11-10T08:00:00Z"), ZoneOffset.UTC); }
|
|
|
|
|
+ @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(); }
|
|
|
|
|
+ @Bean CorsFilter corsFilter() { return new ResourcesConfig().corsFilter(); }
|
|
|
|
|
+ @Bean EquipmentBaseMapper devices() { return mock(EquipmentBaseMapper.class); }
|
|
|
|
|
+ @Bean EquipmentVideoBindingMapper bindings() { return mock(EquipmentVideoBindingMapper.class); }
|
|
|
|
|
+ @Bean VideoSessionMapper sessions() { return mock(VideoSessionMapper.class); }
|
|
|
|
|
+ @Bean VideoCollectorClient collector() { return mock(VideoCollectorClient.class); }
|
|
|
|
|
+ @Bean RedisTemplate<String, Object> redisTemplate() { return mock(RedisTemplate.class); }
|
|
|
|
|
+ @Bean VideoDeviceService videoDeviceService(EquipmentBaseMapper devices, VideoCollectorClient collector,
|
|
|
|
|
+ VideoSessionMapper sessions, EquipmentVideoBindingMapper bindings, Clock clock) {
|
|
|
|
|
+ return new VideoDeviceService(devices, collector, sessions, mock(EquipmentBaseService.class), bindings, clock);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+}
|