-
Notifications
You must be signed in to change notification settings - Fork 57
Chore/record request ip #727
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
eb67231
Dev
fatemeh-i 918e931
Optimize financial action operations and implement two-factor authent…
AmirRajabii 0173997
Merge branch 'main' of https://github.com/opexdev/core into dev
fatemeh-i 3c4ac40
Merge branch 'dev' of https://github.com/opexdev/core into dev
fatemeh-i 3254ab8
Log API requests/response + additional user's data
fatemeh-i f0cbaf2
Potential fix for pull request finding
fatemeh-i bd4d432
Potential fix for pull request finding
fatemeh-i 8a6ea61
Revert method name extraction
fatemeh-i File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
125 changes: 125 additions & 0 deletions
125
api/api-app/src/main/kotlin/co/nilin/opex/api/app/interceptor/RequestAuditFilter.kt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,125 @@ | ||
| package co.nilin.opex.api.app.interceptor | ||
|
|
||
| import co.nilin.opex.common.security.JwtUtils | ||
| import com.fasterxml.jackson.databind.ObjectMapper | ||
| import org.reactivestreams.Publisher | ||
| import org.slf4j.LoggerFactory | ||
| import org.springframework.core.Ordered | ||
| import org.springframework.core.annotation.Order | ||
| import org.springframework.core.io.buffer.DataBufferUtils | ||
| import org.springframework.http.HttpHeaders | ||
| import org.springframework.http.server.reactive.ServerHttpRequestDecorator | ||
| import org.springframework.http.server.reactive.ServerHttpResponseDecorator | ||
| import org.springframework.stereotype.Component | ||
| import org.springframework.web.server.ServerWebExchange | ||
| import org.springframework.web.server.WebFilter | ||
| import org.springframework.web.server.WebFilterChain | ||
| import reactor.core.publisher.Flux | ||
| import reactor.core.publisher.Mono | ||
| import java.nio.charset.StandardCharsets | ||
| import java.time.OffsetDateTime | ||
| import java.time.ZoneOffset | ||
|
|
||
| @Component | ||
| @Order(Ordered.LOWEST_PRECEDENCE) | ||
| class RequestAuditFilter( | ||
| private val objectMapper: ObjectMapper | ||
| ) : WebFilter { | ||
|
|
||
| private val logger = LoggerFactory.getLogger(RequestAuditFilter::class.java) | ||
| private val maxPayloadSize = 10_000 | ||
|
|
||
| override fun filter(exchange: ServerWebExchange, chain: WebFilterChain): Mono<Void> { | ||
| val request = exchange.request | ||
| val sourceIp = resolveClientIp(exchange) | ||
| val token = extractBearerToken(request.headers) | ||
| val mobile = extractClaim(token, "mobile", "phone_number") | ||
| val email = extractClaim(token, "email") | ||
| val deviceUuid = extractClaim(token, "deviceUuid", "device_uuid") | ||
|
|
||
| return DataBufferUtils.join(request.body) | ||
| .defaultIfEmpty(exchange.response.bufferFactory().wrap(ByteArray(0))) | ||
| .flatMap { requestBuffer -> | ||
| val requestBytes = ByteArray(requestBuffer.readableByteCount()) | ||
| requestBuffer.read(requestBytes) | ||
| DataBufferUtils.release(requestBuffer) | ||
| val requestBody = truncateBody(String(requestBytes, StandardCharsets.UTF_8)) | ||
|
|
||
| val decoratedRequest = object : ServerHttpRequestDecorator(request) { | ||
| override fun getBody() = Flux.just(exchange.response.bufferFactory().wrap(requestBytes)) | ||
| } | ||
|
|
||
| val responseBody = StringBuilder() | ||
| val decoratedResponse = object : ServerHttpResponseDecorator(exchange.response) { | ||
| override fun writeWith(body: Publisher<out org.springframework.core.io.buffer.DataBuffer>): Mono<Void> { | ||
| val wrapped = Flux.from(body).map { dataBuffer -> | ||
| val bytes = ByteArray(dataBuffer.readableByteCount()) | ||
| dataBuffer.read(bytes) | ||
| DataBufferUtils.release(dataBuffer) | ||
| responseBody.append(String(bytes, StandardCharsets.UTF_8)) | ||
| bufferFactory().wrap(bytes) | ||
| } | ||
| return super.writeWith(wrapped) | ||
| } | ||
|
|
||
| override fun writeAndFlushWith(body: Publisher<out Publisher<out org.springframework.core.io.buffer.DataBuffer>>): Mono<Void> { | ||
| return writeWith(Flux.from(body).flatMapSequential { it }) | ||
| } | ||
| } | ||
|
|
||
| val updatedExchange = exchange.mutate() | ||
| .request(decoratedRequest) | ||
| .response(decoratedResponse) | ||
| .build() | ||
|
|
||
| return@flatMap chain.filter(updatedExchange) | ||
| .doFinally { | ||
| val payload = mapOf( | ||
| "date" to OffsetDateTime.now(ZoneOffset.UTC).toString(), | ||
| "ip" to sourceIp, | ||
| "mobile" to mobile, | ||
| "email" to email, | ||
| "deviceUuid" to deviceUuid, | ||
| "method" to request.method.name(), | ||
| "url" to request.uri.toString(), | ||
| "requestData" to requestBody, | ||
| "responseStatus" to (decoratedResponse.statusCode?.value() ?: updatedExchange.response.statusCode?.value()), | ||
| "responseBody" to truncateBody(responseBody.toString()) | ||
| ) | ||
| runCatching { | ||
| logger.info("API_REQUEST_AUDIT {}", objectMapper.writeValueAsString(payload)) | ||
| }.onFailure { | ||
| logger.warn("Failed to write request audit log", it) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| private fun extractBearerToken(headers: HttpHeaders): String? { | ||
| val header = headers.getFirst(HttpHeaders.AUTHORIZATION) ?: return null | ||
| if (!header.startsWith("Bearer ", true)) return null | ||
| return header.substringAfter("Bearer ").trim().takeIf { it.isNotBlank() } | ||
| } | ||
|
|
||
| private fun extractClaim(token: String?, vararg names: String): String? { | ||
| if (token.isNullOrBlank()) return null | ||
| val payload = runCatching { JwtUtils.decodePayload(token) }.getOrNull() ?: return null | ||
| return names.firstNotNullOfOrNull { name -> | ||
| payload[name]?.toString()?.takeIf { it.isNotBlank() } | ||
| } | ||
| } | ||
|
|
||
| private fun resolveClientIp(exchange: ServerWebExchange): String? { | ||
| val forwardedFor = exchange.request.headers.getFirst("X-Forwarded-For") | ||
| if (!forwardedFor.isNullOrBlank()) { | ||
| return forwardedFor.substringBefore(",").trim() | ||
| } | ||
| return exchange.request.headers.getFirst("X-Real-IP")?.takeIf { it.isNotBlank() } | ||
| ?: exchange.request.remoteAddress?.address?.hostAddress | ||
| } | ||
|
|
||
| private fun truncateBody(body: String): String { | ||
| if (body.length <= maxPayloadSize) return body | ||
| return body.take(maxPayloadSize) + "...(truncated)" | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
2 changes: 2 additions & 0 deletions
2
...ce-management-postgres/src/main/resources/db/migration/V5__add_ip_address_to_sessions.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| ALTER TABLE sessions | ||
| ADD COLUMN IF NOT EXISTS ip_address VARCHAR(64); |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.