-
Notifications
You must be signed in to change notification settings - Fork 8
accesslog - porting accesslogs capabilities from DT's gateway #113
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
Closed
+433
−6
Closed
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
11e993a
Add AccessLog and X-Request-Id filters to provide additional informat…
pmauduit c47f744
AccessLog: log the effective role names as auth-roles
groldan 54c34e2
AccessLogFilter: clear MDC after logging
groldan d49e001
adding missing dependencies on log4j2
pmauduit 8c77adf
fix: docker-compose - reverting back to latest tag
pmauduit 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
There are no files selected for viewing
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
126 changes: 126 additions & 0 deletions
126
gateway/src/main/java/org/georchestra/gateway/filter/global/AccessLogFilter.java
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,126 @@ | ||
/* | ||
* Copyright (C) 2022 by the geOrchestra PSC | ||
* | ||
* This file is part of geOrchestra. | ||
* | ||
* geOrchestra is free software: you can redistribute it and/or modify it under | ||
* the terms of the GNU General Public License as published by the Free | ||
* Software Foundation, either version 3 of the License, or (at your option) | ||
* any later version. | ||
* | ||
* geOrchestra is distributed in the hope that it will be useful, but WITHOUT | ||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | ||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for | ||
* more details. | ||
* | ||
* You should have received a copy of the GNU General Public License along with | ||
* geOrchestra. If not, see <http://www.gnu.org/licenses/>. | ||
*/ | ||
|
||
package org.georchestra.gateway.filter.global; | ||
|
||
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; | ||
import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR; | ||
|
||
import java.net.InetSocketAddress; | ||
import java.net.URI; | ||
import java.security.Principal; | ||
import java.util.List; | ||
import java.util.Optional; | ||
import java.util.stream.Collectors; | ||
|
||
import org.georchestra.gateway.model.GeorchestraUsers; | ||
import org.georchestra.security.model.GeorchestraUser; | ||
import org.slf4j.MDC; | ||
import org.springframework.cloud.gateway.filter.GatewayFilterChain; | ||
import org.springframework.cloud.gateway.filter.GlobalFilter; | ||
import org.springframework.cloud.gateway.route.Route; | ||
import org.springframework.http.server.reactive.ServerHttpRequest; | ||
import org.springframework.http.server.reactive.ServerHttpResponse; | ||
import org.springframework.security.authentication.AnonymousAuthenticationToken; | ||
import org.springframework.security.core.Authentication; | ||
import org.springframework.security.core.GrantedAuthority; | ||
import org.springframework.security.core.authority.SimpleGrantedAuthority; | ||
import org.springframework.web.server.ServerWebExchange; | ||
|
||
import lombok.NonNull; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import reactor.core.publisher.Mono; | ||
|
||
@RequiredArgsConstructor | ||
@Slf4j(topic = "org.georchestra.gateway.accesslog") | ||
public class AccessLogFilter implements GlobalFilter { | ||
|
||
private final @NonNull AccessLogFilterConfig config; | ||
|
||
@Override | ||
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { | ||
if (config.matches(exchange.getRequest().getURI())) { | ||
exchange.getResponse().beforeCommit(() -> { | ||
return log(exchange); | ||
}); | ||
} | ||
|
||
return chain.filter(exchange); | ||
} | ||
|
||
private static final AnonymousAuthenticationToken ANNON = new AnonymousAuthenticationToken("anonymous", "anonymous", | ||
List.of(new SimpleGrantedAuthority("ROLE_ANONYMOUS"))); | ||
|
||
/** | ||
* @param exchange | ||
*/ | ||
private Mono<Void> log(ServerWebExchange exchange) { | ||
if (!log.isInfoEnabled()) | ||
return Mono.empty(); | ||
|
||
return exchange.getPrincipal().switchIfEmpty(Mono.just(ANNON)).doOnNext(p -> { | ||
doLog(p, exchange); | ||
}).then(); | ||
} | ||
|
||
private void doLog(Principal principal, ServerWebExchange exchange) { | ||
ServerHttpRequest request = exchange.getRequest(); | ||
ServerHttpResponse response = exchange.getResponse(); | ||
URI uri = request.getURI(); | ||
|
||
Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR); | ||
URI routeUri = exchange.getAttribute(GATEWAY_REQUEST_URL_ATTR); | ||
|
||
String requestId = request.getHeaders().getFirst(RequestIdGlobalFilter.REQUEST_ID_HEADER); | ||
|
||
InetSocketAddress addr = request.getRemoteAddress(); | ||
String remoteAddress = addr == null ? "unknown" : addr.toString(); | ||
|
||
mdcPut("route-id", route.getId()); | ||
mdcPut("route-uri", String.valueOf(routeUri)); | ||
mdcPut(RequestIdGlobalFilter.REQUEST_ID_HEADER, requestId); | ||
mdcPut("remoteAddress", remoteAddress); | ||
|
||
Optional<GeorchestraUser> user = GeorchestraUsers.resolve(exchange); | ||
user.ifPresentOrElse(gsu -> { | ||
mdcPut("auth-user", gsu.getUsername()); | ||
mdcPut("auth-roles", gsu.getRoles().stream().collect(Collectors.joining(", "))); | ||
}, () -> MDC.put("auth-user", "anonymous")); | ||
|
||
if (principal instanceof Authentication && principal != ANNON) { | ||
String roles = ((Authentication) principal).getAuthorities().stream().map(GrantedAuthority::getAuthority) | ||
.collect(Collectors.joining(", ")); | ||
|
||
mdcPut("principal-name", principal.getName()); | ||
mdcPut("principal-authorities", roles); | ||
} | ||
|
||
log.info("{} {} {} ", request.getMethodValue(), response.getRawStatusCode(), uri); | ||
mdcClear(); | ||
} | ||
|
||
void mdcPut(String key, String value) { | ||
MDC.put(key, value); | ||
} | ||
|
||
void mdcClear() { | ||
MDC.clear(); | ||
} | ||
} |
75 changes: 75 additions & 0 deletions
75
gateway/src/main/java/org/georchestra/gateway/filter/global/AccessLogFilterConfig.java
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,75 @@ | ||
/* | ||
* Copyright (C) 2022 by the geOrchestra PSC | ||
* | ||
* This file is part of geOrchestra. | ||
* | ||
* geOrchestra is free software: you can redistribute it and/or modify it under | ||
* the terms of the GNU General Public License as published by the Free | ||
* Software Foundation, either version 3 of the License, or (at your option) | ||
* any later version. | ||
* | ||
* geOrchestra is distributed in the hope that it will be useful, but WITHOUT | ||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | ||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for | ||
* more details. | ||
* | ||
* You should have received a copy of the GNU General Public License along with | ||
* geOrchestra. If not, see <http://www.gnu.org/licenses/>. | ||
*/ | ||
|
||
package org.georchestra.gateway.filter.global; | ||
|
||
import java.net.URI; | ||
import java.util.ArrayList; | ||
import java.util.List; | ||
import java.util.regex.Pattern; | ||
|
||
import org.springframework.boot.context.properties.ConfigurationProperties; | ||
|
||
import lombok.Data; | ||
|
||
/** | ||
* Configuration to set white/black list over the request URL to determine if | ||
* the access log filter will log an entry for it. | ||
*/ | ||
@Data | ||
@ConfigurationProperties(prefix = "georchestra.gateway.accesslog") | ||
public class AccessLogFilterConfig { | ||
|
||
/** | ||
* Enable/disable the access log filter | ||
*/ | ||
private boolean enabled = true; | ||
|
||
/** | ||
* A list of java regular expressions applied to the request URL to include them | ||
* from logging. | ||
*/ | ||
List<Pattern> include = new ArrayList<>(); | ||
|
||
/** | ||
* A list of java regular expressions applied to the request URL to exclude them | ||
* from logging. A request URL must pass all the include filters before being | ||
* tested for exclusion. Useful to avoid flooding the logs with frequent | ||
* non-important requests such as static resources (i.e. static images, etc). | ||
*/ | ||
List<Pattern> exclude = new ArrayList<>(); | ||
|
||
/** | ||
* @param uri the origin URL (e.g. https://my.domain.com/geoserver/web/) | ||
* @return {@code true} if disabled or an access log entry shall be logged for | ||
* this request | ||
*/ | ||
public boolean matches(URI uri) { | ||
if (!enabled || (include.isEmpty() && exclude.isEmpty())) | ||
return true; | ||
|
||
String url = uri.toString(); | ||
return matches(url, include, true) && !matches(url, exclude, false); | ||
} | ||
|
||
private boolean matches(String url, List<Pattern> patterns, boolean fallbackIfEmpty) { | ||
return (patterns == null || patterns.isEmpty()) ? fallbackIfEmpty | ||
: patterns.stream().anyMatch(pattern -> pattern.matcher(url).matches()); | ||
} | ||
} |
77 changes: 77 additions & 0 deletions
77
gateway/src/main/java/org/georchestra/gateway/filter/global/RequestIdGlobalFilter.java
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,77 @@ | ||
/* | ||
* Copyright (C) 2022 by the geOrchestra PSC | ||
* | ||
* This file is part of geOrchestra. | ||
* | ||
* geOrchestra is free software: you can redistribute it and/or modify it under | ||
* the terms of the GNU General Public License as published by the Free | ||
* Software Foundation, either version 3 of the License, or (at your option) | ||
* any later version. | ||
* | ||
* geOrchestra is distributed in the hope that it will be useful, but WITHOUT | ||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | ||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for | ||
* more details. | ||
* | ||
* You should have received a copy of the GNU General Public License along with | ||
* geOrchestra. If not, see <http://www.gnu.org/licenses/>. | ||
*/ | ||
package org.georchestra.gateway.filter.global; | ||
|
||
import org.apache.commons.lang3.RandomStringUtils; | ||
import org.springframework.cloud.gateway.filter.GatewayFilterChain; | ||
import org.springframework.cloud.gateway.filter.GlobalFilter; | ||
import org.springframework.core.Ordered; | ||
import org.springframework.http.server.reactive.ServerHttpRequest; | ||
import org.springframework.http.server.reactive.ServerHttpResponse; | ||
import org.springframework.web.server.ServerWebExchange; | ||
|
||
import reactor.core.publisher.Mono; | ||
|
||
/** | ||
* Makes sure both the request and response have the same | ||
* {@literal X-Request-ID} header. | ||
* <p> | ||
* A new value is created for the header if not provided by the client. | ||
*/ | ||
public class RequestIdGlobalFilter implements GlobalFilter, Ordered { | ||
|
||
static final String REQUEST_ID_HEADER = "X-Request-ID"; | ||
|
||
/** | ||
* @return {@link Ordered#HIGHEST_PRECEDENCE} | ||
*/ | ||
public @Override int getOrder() { | ||
return Ordered.HIGHEST_PRECEDENCE; | ||
} | ||
|
||
/** | ||
* Makes sure both the request and response have the same | ||
* {@literal X-Request-ID} header. | ||
* <p> | ||
* A new value is created for the header if not provided by the client. | ||
*/ | ||
public @Override Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { | ||
|
||
final String requestId; | ||
final ServerHttpRequest request; | ||
String providedRequestId = exchange.getRequest().getHeaders().getFirst(REQUEST_ID_HEADER); | ||
if (null == providedRequestId) { | ||
requestId = RandomStringUtils.randomNumeric(16); | ||
request = exchange.getRequest().mutate().header(REQUEST_ID_HEADER, requestId).build(); | ||
exchange = exchange.mutate().request(request).build(); | ||
} else { | ||
requestId = providedRequestId; | ||
request = exchange.getRequest(); | ||
} | ||
|
||
ServerHttpResponse response = exchange.getResponse(); | ||
response.beforeCommit(() -> { | ||
response.getHeaders().set(REQUEST_ID_HEADER, requestId); | ||
return Mono.empty(); | ||
}); | ||
|
||
return chain.filter(exchange); | ||
} | ||
|
||
} |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Apparently, we're having 2 issues there:
doLog
(something seems to be wrong with doOnNext)There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I did several different tries with no luck:
My last try looked like this:
But still the doLog() call is never reached.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
AFAIK, removing the switchIfEmpty would not work, since I'm under the impression that the Principal doesn't get populated and doOnNext would not react to an empty Mono.
But I admit, this all still sounds very much like chinese to me
I admit I find it a bit bothering to rely on some code that is that difficult to even understand (let alone debug). Or maybe I'm just getting too old for this s#!t
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
that syntaxic sugar (is that modern java ?) almost looks like perl5 with less #@$& :)
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I wonder if there wouldn't be, also, a thread context propagation issue. By tweaking a few things (making AccessLogFilter class implement
Ordered
, commenting theif (config.matches...
block), I've been able to insert a hard-coded MDC. But it shows onparrallel-1
thread only while the access logs are onreactor-http-epoll-3
thread.Also, with those same tweaks, if I remove the
Ordered
implement, I'm loosing the MDC. So, maybe also some conflict with another filter, which would be very pleasant to debug :-/