Skip to content

Commit 8da475d

Browse files
authored
MDC hanlder refactoring (#1911)
Signed-off-by: Marinov Avgustin <Avgustin.Marinov@bosch.com>
1 parent 64771e9 commit 8da475d

File tree

5 files changed

+79
-41
lines changed

5 files changed

+79
-41
lines changed

hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityAutoConfiguration.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
import org.eclipse.hawkbit.security.DdiSecurityProperties;
2222
import org.eclipse.hawkbit.security.InMemoryUserAuthoritiesResolver;
2323
import org.eclipse.hawkbit.security.HawkbitSecurityProperties;
24-
import org.eclipse.hawkbit.security.MDCHandler;
24+
import org.eclipse.hawkbit.security.MdcHandler;
2525
import org.eclipse.hawkbit.security.SecurityContextSerializer;
2626
import org.eclipse.hawkbit.security.SecurityContextTenantAware;
2727
import org.eclipse.hawkbit.security.SecurityTokenGenerator;
@@ -124,8 +124,8 @@ public SystemSecurityContext systemSecurityContext(
124124

125125
@Bean
126126
@ConditionalOnMissingBean
127-
public MDCHandler mdcHandler() {
128-
return MDCHandler.getInstance();
127+
public MdcHandler mdcHandler() {
128+
return MdcHandler.getInstance();
129129
}
130130

131131
@Bean

hawkbit-autoconfigure/src/main/java/org/eclipse/hawkbit/autoconfigure/security/SecurityManagedConfiguration.java

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@
3333
import org.eclipse.hawkbit.security.HttpControllerPreAuthenticateSecurityTokenFilter;
3434
import org.eclipse.hawkbit.security.HttpControllerPreAuthenticatedGatewaySecurityTokenFilter;
3535
import org.eclipse.hawkbit.security.HttpControllerPreAuthenticatedSecurityHeaderFilter;
36-
import org.eclipse.hawkbit.security.MDCHandler;
36+
import org.eclipse.hawkbit.security.MdcHandler;
3737
import org.eclipse.hawkbit.security.PreAuthTokenSourceTrustAuthenticationProvider;
3838
import org.eclipse.hawkbit.security.SystemSecurityContext;
3939
import org.eclipse.hawkbit.tenancy.TenantAware;
@@ -62,7 +62,6 @@
6262
import org.springframework.security.core.authority.SimpleGrantedAuthority;
6363
import org.springframework.security.core.context.SecurityContextHolder;
6464
import org.springframework.security.web.SecurityFilterChain;
65-
import org.springframework.security.web.access.intercept.AuthorizationFilter;
6665
import org.springframework.security.web.authentication.AnonymousAuthenticationFilter;
6766
import org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint;
6867
import org.springframework.security.web.firewall.FirewalledRequest;
@@ -203,7 +202,7 @@ protected SecurityFilterChain filterChainDDI(final HttpSecurity http) throws Exc
203202
.sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
204203
}
205204

206-
MDCHandler.Filter.addLoggingFilter(http);
205+
MdcHandler.Filter.addMdcFilter(http);
207206

208207
return http.build();
209208
}
@@ -320,7 +319,7 @@ protected SecurityFilterChain filterChainDDIDL(final HttpSecurity http) throws E
320319
.sessionManagement(configurer -> configurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
321320
}
322321

323-
MDCHandler.Filter.addLoggingFilter(http);
322+
MdcHandler.Filter.addMdcFilter(http);
324323

325324
return http.build();
326325
}
@@ -453,7 +452,7 @@ SecurityFilterChain filterChainREST(
453452
httpSecurityCustomizer.customize(http);
454453
}
455454

456-
MDCHandler.Filter.addLoggingFilter(http);
455+
MdcHandler.Filter.addMdcFilter(http);
457456

458457
return http.build();
459458
}

hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/MDCHandler.java renamed to hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/MdcHandler.java

Lines changed: 68 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -30,36 +30,34 @@
3030
import java.util.concurrent.Callable;
3131

3232
@NoArgsConstructor(access = AccessLevel.PRIVATE)
33-
public class MDCHandler {
33+
public class MdcHandler {
3434

3535
public static String MDC_KEY_TENANT = "tenant";
3636
public static String MDC_KEY_USER = "user";
3737

38-
private static final MDCHandler SINGLETON = new MDCHandler();
38+
private static final MdcHandler SINGLETON = new MdcHandler();
3939

4040
@Value("${hawkbit.logging.mdchandler.enabled:true}")
4141
private boolean mdcEnabled;
4242
@Autowired(required = false)
4343
private SpringSecurityAuditorAware springSecurityAuditorAware = new SpringSecurityAuditorAware();
44-
@Autowired(required = false)
45-
private SystemSecurityContext securityContext;
4644

4745
/**
4846
* @return The holder singleton instance.
4947
*/
50-
public static MDCHandler getInstance() {
48+
public static MdcHandler getInstance() {
5149
return SINGLETON;
5250
}
5351

5452
/**
55-
* Executes callable and returns the result. If MDC is enabled, it sets the tenant and / or user in the MDC context.
53+
* Executes callable and returns the result. If MDC is enabled, it sets the tenant and / or user from the authentication in the MDC context.
5654
*
5755
* @param <T> the return type
5856
* @param callable the callable to execute
5957
* @return the result
6058
* @throws Exception if thrown by the callable
6159
*/
62-
public <T> T withLogging(final Callable<T> callable) throws Exception {
60+
public <T> T callWithAuth(final Callable<T> callable) throws Exception {
6361
if (!mdcEnabled) {
6462
return callable.call();
6563
}
@@ -76,43 +74,84 @@ public <T> T withLogging(final Callable<T> callable) throws Exception {
7674
tenant = null;
7775
}
7876

79-
final String currentTenant = MDC.get(MDC_KEY_TENANT);
80-
if (Objects.equals(currentTenant, tenant)) {
81-
return putUserAndCall(callable);
82-
} else {
83-
put(MDC_KEY_TENANT, tenant);
84-
try {
85-
return putUserAndCall(callable);
86-
} finally {
87-
put(MDC_KEY_TENANT, currentTenant);
88-
}
77+
final String user = springSecurityAuditorAware
78+
.getCurrentAuditor()
79+
.filter(username -> !username.equals("system")) // null and system are the same - system user
80+
.orElse(null);
81+
82+
return callWithTenantAndUser0(callable, tenant, user);
83+
}
84+
85+
/**
86+
* Executes callable and returns the result. If MDC is enabled, it sets the tenant and / or user from the authentication in the MDC context.
87+
* Calls the {@link #callWithAuth(Callable)} method and wraps any catchable exception into a {@link RuntimeException}.
88+
*
89+
* @param <T> the return type
90+
* @param callable the callable to execute
91+
* @return the result
92+
*/
93+
public <T> T callWithAuthRE(final Callable<T> callable) {
94+
try {
95+
return callWithAuth(callable);
96+
} catch (final RuntimeException re) {
97+
throw re;
98+
} catch (final Exception e) {
99+
throw new RuntimeException(e);
89100
}
90101
}
91102

92103
/**
93-
* With logging throwing Runtime Exception (withLoggingRE). Calls the {@link #withLogging(Callable)} method and
94-
* wraps any catchable exception into a {@link RuntimeException}.
104+
* Executes callable and returns the result. If MDC is enabled, it sets the tenant and / or user in the MDC context.
105+
*
106+
* @param <T> the return type
107+
* @param callable the callable to execute
108+
* @param tenant the tenant to set in the MDC context
109+
* @param user the user to set in the MDC context
110+
* @return the result
111+
*/
112+
public <T> T callWithTenantAndUser(final Callable<T> callable, final String tenant, final String user) throws Exception {
113+
if (!mdcEnabled) {
114+
return callable.call();
115+
}
116+
117+
return callWithTenantAndUser0(callable, tenant, user);
118+
}
119+
120+
/**
121+
* Executes callable and returns the result. If MDC is enabled, it sets the tenant and / or user from the authentication in the MDC context.
122+
* Calls the {@link #callWithTenantAndUser(Callable, String, String)} method and wraps any catchable exception into a {@link RuntimeException}.
95123
*
96124
* @param <T> the return type
97125
* @param callable the callable to execute
126+
* @param tenant the tenant to set in the MDC context
127+
* @param user the user to set in the MDC context
98128
* @return the result
99129
*/
100-
public <T> T withLoggingRE(final Callable<T> callable) {
130+
public <T> T callWithTenantAndUserRE(final Callable<T> callable, final String tenant, final String user) {
101131
try {
102-
return withLogging(callable);
132+
return callWithTenantAndUser(callable, tenant, user);
103133
} catch (final RuntimeException re) {
104134
throw re;
105135
} catch (final Exception e) {
106136
throw new RuntimeException(e);
107137
}
108138
}
109139

110-
private <T> T putUserAndCall(final Callable<T> callable) throws Exception {
111-
final String user = springSecurityAuditorAware
112-
.getCurrentAuditor()
113-
.filter(username -> !username.equals("system")) // null and system are the same - system user
114-
.orElse(null);
140+
private static <T> T callWithTenantAndUser0(final Callable<T> callable, final String tenant, final String user) throws Exception {
141+
final String currentTenant = MDC.get(MDC_KEY_TENANT);
142+
if (Objects.equals(currentTenant, tenant)) {
143+
return callWithUser(callable, user);
144+
} else {
145+
put(MDC_KEY_TENANT, tenant);
146+
try {
147+
return callWithUser(callable, user);
148+
} finally {
149+
put(MDC_KEY_TENANT, currentTenant);
150+
}
151+
}
152+
}
115153

154+
private static <T> T callWithUser(final Callable<T> callable, final String user) throws Exception {
116155
final String currentUser = MDC.get(MDC_KEY_USER);
117156
if (Objects.equals(currentUser, user)) {
118157
return callable.call();
@@ -137,17 +176,17 @@ private static void put(final String key, final String value) {
137176
@NoArgsConstructor(access = AccessLevel.PRIVATE)
138177
public static class Filter {
139178

140-
public static void addLoggingFilter(final HttpSecurity httpSecurity) {
179+
public static void addMdcFilter(final HttpSecurity httpSecurity) {
141180
httpSecurity.addFilterBefore(new OncePerRequestFilter() {
142181

143-
private final MDCHandler mdcFilter = MDCHandler.getInstance();
182+
private final MdcHandler mdcFilter = MdcHandler.getInstance();
144183

145184
@Override
146185
protected void doFilterInternal(
147186
final HttpServletRequest request, final HttpServletResponse response, final FilterChain filterChain)
148187
throws ServletException, IOException {
149188
try {
150-
mdcFilter.withLogging(() -> {
189+
mdcFilter.callWithAuth(() -> {
151190
filterChain.doFilter(request, response);
152191
return null;
153192
});

hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SecurityContextTenantAware.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ private static <T> T runInContext(final SecurityContext securityContext, final S
142142
} else {
143143
SecurityContextHolder.setContext(securityContext);
144144
try {
145-
return MDCHandler.getInstance().withLoggingRE(supplier::get);
145+
return MdcHandler.getInstance().callWithAuthRE(supplier::get);
146146
} finally {
147147
SecurityContextHolder.setContext(originalContext);
148148
}
@@ -153,7 +153,7 @@ private static <T> T runAsSystem(final TenantRunner<T> tenantRunner) {
153153
final SecurityContext currentContext = SecurityContextHolder.getContext();
154154
SystemSecurityContext.setSystemContext(currentContext);
155155
try {
156-
return MDCHandler.getInstance().withLoggingRE(tenantRunner::run);
156+
return MdcHandler.getInstance().callWithAuthRE(tenantRunner::run);
157157
} finally {
158158
SecurityContextHolder.setContext(currentContext);
159159
}

hawkbit-security-core/src/main/java/org/eclipse/hawkbit/security/SystemSecurityContext.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ public <T> T runAsSystemAsTenant(final Callable<T> callable, final String tenant
110110
log.debug("Entering system code execution");
111111
return tenantAware.runAsTenant(tenant, () -> {
112112
setSystemContext(SecurityContextHolder.getContext());
113-
return MDCHandler.getInstance().withLoggingRE(callable);
113+
return MdcHandler.getInstance().callWithAuthRE(callable);
114114
});
115115
} finally {
116116
SecurityContextHolder.setContext(oldContext);
@@ -139,7 +139,7 @@ public <T> T runAsControllerAsTenant(@NotEmpty final String tenant, @NotNull fin
139139
try {
140140
return tenantAware.runAsTenant(tenant, () -> {
141141
setCustomSecurityContext(tenant, oldContext.getAuthentication().getPrincipal(), authorities);
142-
return MDCHandler.getInstance().withLoggingRE(callable);
142+
return MdcHandler.getInstance().callWithAuthRE(callable);
143143
});
144144
} finally {
145145
SecurityContextHolder.setContext(oldContext);

0 commit comments

Comments
 (0)