|
| 1 | +package com.park.utmstack.loggin.api_key; |
| 2 | + |
| 3 | +import com.park.utmstack.domain.api_keys.ApiKey; |
| 4 | +import com.park.utmstack.domain.api_keys.ApiKeyUsageLog; |
| 5 | +import com.park.utmstack.domain.application_events.enums.ApplicationEventType; |
| 6 | +import com.park.utmstack.service.api_key.ApiKeyService; |
| 7 | +import com.park.utmstack.service.application_events.ApplicationEventService; |
| 8 | +import lombok.RequiredArgsConstructor; |
| 9 | +import lombok.extern.slf4j.Slf4j; |
| 10 | +import org.springframework.stereotype.Service; |
| 11 | +import org.springframework.util.StringUtils; |
| 12 | +import org.springframework.web.util.ContentCachingRequestWrapper; |
| 13 | +import org.springframework.web.util.ContentCachingResponseWrapper; |
| 14 | + |
| 15 | +import javax.servlet.http.HttpServletRequest; |
| 16 | +import javax.servlet.http.HttpServletResponse; |
| 17 | +import java.nio.charset.StandardCharsets; |
| 18 | +import java.time.Instant; |
| 19 | +import java.util.UUID; |
| 20 | + |
| 21 | +import static org.postgresql.PGProperty.APPLICATION_NAME; |
| 22 | + |
| 23 | +@Service |
| 24 | +@Slf4j |
| 25 | +@RequiredArgsConstructor |
| 26 | +public class ApiKeyUsageLoggingService { |
| 27 | + |
| 28 | + private final ApiKeyService apiKeyService; |
| 29 | + private final ApplicationEventService applicationEventService; |
| 30 | + private static final String LOG_USAGE_FLAG = "LOG_USAGE_DONE"; |
| 31 | + |
| 32 | + public void logUsage(ContentCachingRequestWrapper request, |
| 33 | + ContentCachingResponseWrapper response, |
| 34 | + ApiKey apiKey, |
| 35 | + String ipAddress, |
| 36 | + String message) { |
| 37 | + |
| 38 | + if (Boolean.TRUE.equals(request.getAttribute(LOG_USAGE_FLAG))) { |
| 39 | + return; |
| 40 | + } |
| 41 | + |
| 42 | + try { |
| 43 | + String payload = extractPayload(request); |
| 44 | + String errorText = extractErrorText(response); |
| 45 | + int status = safeStatus(response); |
| 46 | + |
| 47 | + ApiKeyUsageLog usage = buildUsageLog(apiKey, ipAddress, request, status, errorText, payload); |
| 48 | + |
| 49 | + apiKeyService.logUsage(usage); |
| 50 | + |
| 51 | + ApplicationEventType eventType = (status >= 400) |
| 52 | + ? ApplicationEventType.API_KEY_ACCESS_FAILURE |
| 53 | + : ApplicationEventType.API_KEY_ACCESS_SUCCESS; |
| 54 | + |
| 55 | + String eventMessage = (status >= 400) |
| 56 | + ? "API key access failure" |
| 57 | + : "API key access"; |
| 58 | + |
| 59 | + applicationEventService.createEvent(eventMessage, eventType, usage.toAuditMap()); |
| 60 | + |
| 61 | + } catch (Exception e) { |
| 62 | + log.error("Error while logging API key usage: {}", e.getMessage(), e); |
| 63 | + } finally { |
| 64 | + request.setAttribute(LOG_USAGE_FLAG, Boolean.TRUE); |
| 65 | + } |
| 66 | + } |
| 67 | + |
| 68 | + private int safeStatus(HttpServletResponse response) { |
| 69 | + try { |
| 70 | + return response.getStatus(); |
| 71 | + } catch (Exception e) { |
| 72 | + return 0; |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + private String extractPayload(ContentCachingRequestWrapper request) { |
| 77 | + try { |
| 78 | + if (!"GET".equalsIgnoreCase(request.getMethod()) && !"DELETE".equalsIgnoreCase(request.getMethod())) { |
| 79 | + byte[] content = request.getContentAsByteArray(); |
| 80 | + return content.length > 0 ? new String(content, StandardCharsets.UTF_8) : null; |
| 81 | + } |
| 82 | + } catch (Exception ex) { |
| 83 | + log.error("Error extracting payload: {}", ex.getMessage()); |
| 84 | + } |
| 85 | + return null; |
| 86 | + } |
| 87 | + |
| 88 | + private String extractErrorText(ContentCachingResponseWrapper response) { |
| 89 | + int statusCode = response.getStatus(); |
| 90 | + if (statusCode >= 400) { |
| 91 | + byte[] content = response.getContentAsByteArray(); |
| 92 | + String responseError = content.length > 0 ? new String(content, StandardCharsets.UTF_8) : null; |
| 93 | + String errorHeader = response.getHeader("X-" + APPLICATION_NAME + "-error"); |
| 94 | + return StringUtils.hasText(responseError) ? responseError : errorHeader; |
| 95 | + } |
| 96 | + return null; |
| 97 | + } |
| 98 | + |
| 99 | + private ApiKeyUsageLog buildUsageLog(ApiKey apiKey, |
| 100 | + String ipAddress, |
| 101 | + HttpServletRequest request, |
| 102 | + int status, |
| 103 | + String errorText, |
| 104 | + String payload) { |
| 105 | + |
| 106 | + String id = UUID.randomUUID().toString(); |
| 107 | + String apiKeyId = apiKey != null && apiKey.getId() != null ? apiKey.getId().toString() : null; |
| 108 | + String apiKeyName = apiKey != null ? apiKey.getName() : null; |
| 109 | + String userId = apiKey != null && apiKey.getUserId() != null ? apiKey.getUserId().toString() : null; |
| 110 | + String timestamp = Instant.now().toString(); |
| 111 | + String endpoint = request != null ? request.getRequestURI() : null; |
| 112 | + String queryParams = request != null ? request.getQueryString() : null; |
| 113 | + String userAgent = request != null ? request.getHeader("User-Agent") : null; |
| 114 | + String httpMethod = request != null ? request.getMethod() : null; |
| 115 | + String statusCode = String.valueOf(status); |
| 116 | + |
| 117 | + String safePayload = null; |
| 118 | + if (payload != null) { |
| 119 | + int PAYLOAD_MAX_LENGTH = 2000; |
| 120 | + safePayload = payload.length() > PAYLOAD_MAX_LENGTH ? payload.substring(0, PAYLOAD_MAX_LENGTH) : payload; |
| 121 | + } |
| 122 | + |
| 123 | + return ApiKeyUsageLog.builder() |
| 124 | + .id(id) |
| 125 | + .apiKeyId(apiKeyId) |
| 126 | + .apiKeyName(apiKeyName) |
| 127 | + .userId(userId) |
| 128 | + .timestamp(timestamp) |
| 129 | + .endpoint(endpoint) |
| 130 | + .address(ipAddress) |
| 131 | + .errorMessage(errorText) |
| 132 | + .queryParams(queryParams) |
| 133 | + .payload(safePayload) |
| 134 | + .userAgent(userAgent) |
| 135 | + .httpMethod(httpMethod) |
| 136 | + .statusCode(statusCode) |
| 137 | + .build(); |
| 138 | + } |
| 139 | +} |
0 commit comments