• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

SpiNNakerManchester / JavaSpiNNaker / 6986

29 Aug 2025 02:13PM UTC coverage: 36.267% (-0.01%) from 36.278%
6986

push

github

rowleya
Fix some deprecation issues

1908 of 5888 branches covered (32.4%)

Branch coverage included in aggregate %.

8 of 8 new or added lines in 1 file covered. (100.0%)

30 existing lines in 5 files now uncovered.

8959 of 24076 relevant lines covered (37.21%)

0.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

52.27
/SpiNNaker-allocserv/src/main/java/uk/ac/manchester/spinnaker/alloc/security/SecurityConfig.java
1
/*
2
 * Copyright (c) 2021 The University of Manchester
3
 *
4
 * Licensed under the Apache License, Version 2.0 (the "License");
5
 * you may not use this file except in compliance with the License.
6
 * You may obtain a copy of the License at
7
 *
8
 *     https://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 * Unless required by applicable law or agreed to in writing, software
11
 * distributed under the License is distributed on an "AS IS" BASIS,
12
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 * See the License for the specific language governing permissions and
14
 * limitations under the License.
15
 */
16
package uk.ac.manchester.spinnaker.alloc.security;
17

18
import static org.slf4j.LoggerFactory.getLogger;
19
import static org.springframework.beans.factory.config.BeanDefinition.ROLE_APPLICATION;
20
import static org.springframework.beans.factory.config.BeanDefinition.ROLE_SUPPORT;
21
import static org.springframework.http.HttpMethod.GET;
22
import static org.springframework.http.MediaType.APPLICATION_JSON;
23
import static org.springframework.util.StreamUtils.copyToByteArray;
24
import static uk.ac.manchester.spinnaker.alloc.security.AppAuthTransformationFilter.clearToken;
25
import static uk.ac.manchester.spinnaker.alloc.security.Utils.installInjectableTrustStoreAsDefault;
26
import static uk.ac.manchester.spinnaker.alloc.security.Utils.loadTrustStore;
27
import static uk.ac.manchester.spinnaker.alloc.security.Utils.trustManager;
28

29
import java.io.IOException;
30
import java.net.URI;
31
import java.security.GeneralSecurityException;
32
import java.time.Instant;
33
import java.util.Collection;
34
import java.util.LinkedHashSet;
35
import java.util.List;
36
import java.util.Map;
37

38
import javax.net.ssl.X509TrustManager;
39

40
import org.apache.commons.logging.LogFactory;
41
import org.hobsoft.spring.resttemplatelogger.LogFormatter;
42
import org.hobsoft.spring.resttemplatelogger.LoggingCustomizer;
43
import org.slf4j.Logger;
44
import org.springframework.beans.factory.annotation.Autowired;
45
import org.springframework.boot.web.client.RestTemplateBuilder;
46
import org.springframework.context.annotation.Bean;
47
import org.springframework.context.annotation.Role;
48
import org.springframework.core.ParameterizedTypeReference;
49
import org.springframework.http.HttpHeaders;
50
import org.springframework.http.HttpRequest;
51
import org.springframework.http.RequestEntity;
52
import org.springframework.http.client.ClientHttpResponse;
53
import org.springframework.security.access.prepost.PreAuthorize;
54
import org.springframework.security.config.Customizer;
55
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
56
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
57
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
58
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
59
import org.springframework.security.core.GrantedAuthority;
60
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
61
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
62
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
63
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
64
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
65
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
66
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
67
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
68
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
69
import org.springframework.security.oauth2.server.resource.introspection.SpringOpaqueTokenIntrospector;
70
import org.springframework.security.web.SecurityFilterChain;
71
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
72
import org.springframework.security.web.authentication.logout.LogoutHandler;
73
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
74
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
75
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
76

77
import jakarta.servlet.DispatcherType;
78
import uk.ac.manchester.spinnaker.alloc.ServiceConfig.URLPathMaker;
79
import uk.ac.manchester.spinnaker.alloc.SpallocProperties.AuthProperties;
80
import uk.ac.manchester.spinnaker.utils.UsedInJavadocOnly;
81

82
/**
83
 * The security and administration configuration of the service.
84
 * <p>
85
 * <strong>Note:</strong> role expressions ({@link #IS_USER} and
86
 * {@link #IS_ADMIN}) must be applied (with {@code @}{@link PreAuthorize}) to
87
 * <em>interfaces</em> of classes (or methods of those interfaces) that are
88
 * Spring Beans in order for the security interception to be applied correctly.
89
 * This is the <em>only</em> combination that is known to work reliably.
90
 *
91
 * @author Donal Fellows
92
 */
93
@EnableWebSecurity
94
@Role(ROLE_APPLICATION)
95
@EnableMethodSecurity(prePostEnabled = true)
96
@UsedInJavadocOnly(PreAuthorize.class)
97
public class SecurityConfig {
2✔
98
        private static final Logger log = getLogger(SecurityConfig.class);
2✔
99

100
        /** How to assert that a user must be an admin. */
101
        public static final String IS_ADMIN = "hasRole('ADMIN')";
102

103
        /** How to assert that a user must be an admin. */
104
        public static final String IS_NMPI_EXEC = "hasRole('NMPI_EXEC')";
105

106
        /** How to assert that a user must be able to read summaries. */
107
        public static final String IS_READER = "hasRole('READER')";
108

109
        /** How to filter out job details that a given user may see (or not). */
110
        public static final String MAY_SEE_JOB_DETAILS = "#permit.admin or "
111
                        + " #permit.nmpiexec or "
112
                        + " #permit.name == filterObject.owner.orElse(null)";
113

114
        private static final ParameterizedTypeReference<
115
                        Map<String, Object>> PARAMETERIZED_RESPONSE_TYPE =
2✔
116
                                        new ParameterizedTypeReference<>() {
2✔
117
                                        };
118

119
        /**
120
         * How to assert that a user must be able to make jobs and read job details
121
         * in depth.
122
         */
123
        public static final String IS_USER = "hasRole('USER')";
124

125
        private static final String SESSION_COOKIE = "JSESSIONID";
126

127
        // ------------------------------------------------------------------------
128
        // What follows is UGLY stuff to make Java open HTTPS right
129
        private static X509TrustManager customTm;
130

131
        // Static because it has to be done very early.
132
        static {
133
                try {
134
                        installInjectableTrustStoreAsDefault(() -> customTm);
2✔
135
                        log.info("custom SSL trust injection point installed");
2✔
UNCOV
136
                } catch (Exception e) {
×
137
                        throw new RuntimeException("failed to set up SSL trust", e);
×
138
                }
2✔
139
        }
2✔
140

141
        /**
142
         * Builds a custom trust manager to plug into the Java runtime. This is so
143
         * that we can access resources managed by Keycloak, which is necessary
144
         * because Java doesn't trust its certificate by default (for messy
145
         * reasons).
146
         *
147
         * @param props
148
         *            Configuration properties
149
         * @return the custom trust manager, <em>already injected</em>
150
         * @throws IOException
151
         *             If the trust store can't be loaded because of I/O
152
         * @throws GeneralSecurityException
153
         *             If there is a security problem with the trust store
154
         * @see <a href="https://stackoverflow.com/a/24561444/301832">Stack
155
         *      Overflow</a>
156
         */
157
        @Bean
158
        @Role(ROLE_SUPPORT)
159
        static X509TrustManager customTrustManager(AuthProperties props)
160
                        throws IOException, GeneralSecurityException {
161
                var p = props.getOpenid();
2✔
162
                var tm = trustManager(loadTrustStore(p));
2✔
163
                customTm = tm;
2✔
164
                log.info("set trust store from {}", p.getTruststorePath().getURI());
2✔
165
                return tm;
2✔
166
        }
167

168
        // ------------------------------------------------------------------------
169

170
        @Autowired
171
        private BasicAuthEntryPoint authenticationEntryPoint;
172

173
        @Autowired
174
        private LocalAuthenticationProvider<?> localAuthProvider;
175

176
        @Autowired
177
        private AppAuthTransformationFilter authApplicationFilter;
178

179
        @Autowired
180
        private AuthenticationFailureHandler authenticationFailureHandler;
181

182
        @Autowired
183
        private AuthProperties properties;
184

185
        @Autowired
186
        private URLPathMaker urlMaker;
187

188
        /**
189
         * Configure things we plug into.
190
         *
191
         * @param auth
192
         *            The authentication manager builder to configure.
193
         */
194
        @Autowired
195
        public void configureGlobal(AuthenticationManagerBuilder auth) {
196
                auth.authenticationProvider(localAuthProvider);
2✔
197
        }
2✔
198

199
        private String oidcPath(String suffix) {
200
                return urlMaker.systemUrl("perform_oidc/" + suffix);
2✔
201
        }
202

203
        /**
204
         * Set up access control policies where they're not done by method security.
205
         * The {@code /info} part reveals admin details; you need {@code ROLE_ADMIN}
206
         * to view it. Everything to do with logging in <strong>must not</strong>
207
         * require being logged in. For anything else, as long as you are
208
         * authenticated we're happy. <em>Some</em> calls have additional
209
         * requirements; those are annotated with {@link PreAuthorize @PreAuthorize}
210
         * and a suitable auth expression.
211
         *
212
         * @param http
213
         *            Where the configuration is applied to.
214
         * @param introspector
215
         *           The introspector used to build request matchers.
216
         * @throws Exception
217
         *             If anything goes wrong with setting up.
218
         */
219
        private void defineAccessPolicy(HttpSecurity http,
220
                        HandlerMappingIntrospector introspector) throws Exception {
221
                http.authorizeHttpRequests((authorize) -> authorize
2✔
222
                                // Allow forwarded requests
223
                                .dispatcherTypeMatchers(DispatcherType.FORWARD).permitAll()
2✔
224
                                // Login process and static resources are available to all
225
                                .requestMatchers(urlMaker.systemUrl("login*"),
2✔
226
                                                urlMaker.systemUrl("perform_*"),
2✔
227
                                                oidcPath("**"),
2✔
228
                                                urlMaker.systemUrl("error"),
2✔
229
                                                urlMaker.systemUrl("resources/*"),
2✔
230
                                                urlMaker.serviceUrl("openapi.json"),
2✔
231
                                                urlMaker.serviceUrl("swagger*"),
2✔
232
                                                urlMaker.serviceUrl("index.css"))
2✔
233
                                .permitAll()
2✔
234
                                // Everything else requires post-login
235
                                .anyRequest().authenticated());
2✔
236
        }
2✔
237

238
        /**
239
         * How we handle the mechanics of login with the REST API.
240
         *
241
         * @param http
242
         *            Where the configuration is applied to.
243
         * @throws Exception
244
         *             If anything goes wrong with setting up. Not expected.
245
         */
246
        private void defineAPILoginRules(HttpSecurity http) throws Exception {
247
                if (properties.isBasic()) {
2!
248
                        http.httpBasic((authorize) -> authorize
2✔
249
                                        .authenticationEntryPoint(authenticationEntryPoint));
2✔
250
                }
251
                if (properties.getOpenid().isEnable()) {
2!
UNCOV
252
                        http.oauth2ResourceServer((authorize) -> authorize
×
253
                                        .authenticationEntryPoint(authenticationEntryPoint)
×
254
                                        .opaqueToken(oauth2 -> oauth2
×
255
                                                .introspector(new UserInfoOpaqueTokenIntrospector())));
×
256
                }
257
        }
2✔
258

259
        /**
260
         * How we handle the mechanics of login within the web UI.
261
         *
262
         * @param http
263
         *            Where the configuration is applied to.
264
         * @throws Exception
265
         *             If anything goes wrong with setting up. Not expected.
266
         */
267
        private void defineWebUILoginRules(HttpSecurity http) throws Exception {
268
                var loginUrl = urlMaker.systemUrl("login.html");
2✔
269
                var rootPage = urlMaker.systemUrl("");
2✔
270
                if (properties.getOpenid().isEnable()) {
2!
271
                        /*
272
                         * We're both, so we can have logins AND tokens. The logins are for
273
                         * using the HTML UI, and the tokens are for using from SpiNNaker
274
                         * tools (especially within the collabratory and the Jupyter
275
                         * notebook).
276
                         */
UNCOV
277
                        http.oauth2Login(oauth2 -> oauth2.loginPage(loginUrl)
×
278
                                        .loginProcessingUrl(oidcPath("login/code/*"))
×
279
                                        .authorizationEndpoint(
×
280
                                                        auth -> auth.baseUri(oidcPath("auth")))
×
281
                                        .defaultSuccessUrl(rootPage, true)
×
282
                                        .failureUrl(loginUrl + "?error=true")
×
283
                                        .userInfoEndpoint(auth -> auth
×
284
                                                .userAuthoritiesMapper(userAuthoritiesMapper()))
×
285
                                        .permitAll());
×
286
                        http.oauth2Client(Customizer.withDefaults());
×
287
                }
288
                if (properties.isLocalForm()) {
2!
289
                        http.formLogin(auth -> auth.loginPage(loginUrl)
2✔
290
                                        .loginProcessingUrl(urlMaker.systemUrl("perform_login"))
2✔
291
                                        .defaultSuccessUrl(rootPage, true)
2✔
292
                                        .failureUrl(loginUrl + "?error=true")
2✔
293
                                        .failureHandler(authenticationFailureHandler)
2✔
294
                                        .permitAll());
2✔
295
                }
296
        }
2✔
297

298
        /**
299
         * Logging out is common code between the UI and the API, but pretty
300
         * pointless for Basic Auth as browsers will just log straight back in
301
         * again. Still, it is meaningful (it invalidates the session).
302
         *
303
         * @param http
304
         *            Where the configuration is applied to.
305
         * @throws Exception
306
         *             If anything goes wrong with setting up. Not expected.
307
         */
308
        private void defineLogoutRules(HttpSecurity http) throws Exception {
309
                var loginUrl = urlMaker.systemUrl("login.html");
2✔
310
                http.logout(cust -> cust.logoutUrl(urlMaker.systemUrl("perform_logout"))
2✔
311
                                .addLogoutHandler((req, resp, auth) -> clearToken(req))
2✔
312
                                .deleteCookies(SESSION_COOKIE).invalidateHttpSession(true)
2✔
313
                                .logoutSuccessUrl(loginUrl));
2✔
314
        }
2✔
315

316
        /**
317
         * Define our main security controls.
318
         *
319
         * @param http
320
         *            Used to build the filter chain.
321
         * @param introspector
322
         *            The introspector used to build request matchers.
323
         * @return The filter chain that implements the controls.
324
         * @throws Exception
325
         *             If anything goes wrong with setting up. Not expected.
326
         */
327
        @Bean
328
        @Role(ROLE_SUPPORT)
329
        public SecurityFilterChain securityFilter(HttpSecurity http,
330
                        HandlerMappingIntrospector introspector)
331
                        throws Exception {
332
                defineAccessPolicy(http, introspector);
2✔
333
                defineAPILoginRules(http);
2✔
334
                defineWebUILoginRules(http);
2✔
335
                defineLogoutRules(http);
2✔
336
                http.addFilterAfter(authApplicationFilter,
2✔
337
                                BasicAuthenticationFilter.class);
338
                http.securityContext((securityContext) ->
2✔
339
                                securityContext.requireExplicitSave(false));
2✔
340
                return http.build();
2✔
341
        }
342

343
        private final class UserInfoOpaqueTokenIntrospector
344
                        implements OpaqueTokenIntrospector {
345
                private final OpaqueTokenIntrospector delegate;
346

347
                private final String userInfoUri;
348

UNCOV
349
                private UserInfoOpaqueTokenIntrospector() {
×
350
                        var p = properties.getOpenid();
×
351

UNCOV
352
                        delegate = SpringOpaqueTokenIntrospector
×
353
                                        .withIntrospectionUri(p.getIntrospection())
×
354
                                        .clientId(p.getId()).clientSecret(p.getSecret()).build();
×
355
                        userInfoUri = p.getUserinfo();
×
356
                }
×
357

358
                @Override
359
                public OAuth2AuthenticatedPrincipal introspect(String token) {
UNCOV
360
                        var authorized = delegate.introspect(token);
×
361
                        Instant issuedAt = authorized.getAttribute("issued-at");
×
362
                        Instant expiresAt = authorized.getAttribute("expires-at");
×
363

UNCOV
364
                        var userAttributes = userinfo(token);
×
365
                        var authorities = new LinkedHashSet<GrantedAuthority>();
×
366
                        var auth = new OidcUserAuthority(
×
367
                                        new OidcIdToken(token, issuedAt, expiresAt, userAttributes),
368
                                        new OidcUserInfo(userAttributes));
UNCOV
369
                        localAuthProvider.mapAuthorities(auth, authorities);
×
370
                        return new DefaultOAuth2User(authorities, userAttributes,
×
371
                                        "preferred_username");
372
                }
373

374
                private Map<String, Object> userinfo(String token) {
UNCOV
375
                        log.debug("Fetching user info from {}", userInfoUri);
×
376
                        var headers = new HttpHeaders();
×
377
                        headers.setAccept(List.of(APPLICATION_JSON));
×
378
                        headers.setBearerAuth(token);
×
379
                        var request = new RequestEntity<>(headers, GET,
×
380
                                        URI.create(userInfoUri));
×
381

UNCOV
382
                        var restLog = LogFactory.getLog(LoggingCustomizer.class);
×
383
                        var restTemplate = new RestTemplateBuilder().customizers(
×
384
                                        new LoggingCustomizer(restLog, new Formatter())).build();
×
385
                        restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
×
386
                        var response =
×
387
                                        restTemplate.exchange(request, PARAMETERIZED_RESPONSE_TYPE);
×
388

UNCOV
389
                        return response.getBody();
×
390
                }
391
        }
392

UNCOV
393
        private final class Formatter implements LogFormatter {
×
394

395
                @Override
396
                public String formatResponse(ClientHttpResponse response)
397
                                throws IOException {
UNCOV
398
                        return String.format("Response:\n    Headers: %s\n    Body: %s",
×
399
                                        response.getHeaders(),
×
400
                                        new String(copyToByteArray(response.getBody())));
×
401
                }
402

403
                @Override
404
                public String formatRequest(HttpRequest request, byte[] body) {
UNCOV
405
                        return String.format(
×
406
                                        "%s Request to %s:\n"
407
                                        + "    Headers: %s\n"
408
                                        + "    Body: %s",
UNCOV
409
                                        request.getMethod(), request.getURI(), request.getHeaders(),
×
410
                                        new String(body));
411
                }
412
        }
413

414
        /**
415
         * @return A converter that handles the initial extraction of collabratories
416
         *         and organisations from the info we have available when a user
417
         *         logs in explicitly in the web UI.
418
         * @see LocalAuthProviderImpl#mapAuthorities(OidcUserAuthority, Collection)
419
         */
420
        @Bean("hbp.collab-and-org.user-converter.shim")
421
        @Role(ROLE_SUPPORT)
422
        GrantedAuthoritiesMapper userAuthoritiesMapper() {
423
                var baseMapper = new SimpleAuthorityMapper();
2✔
424
                return authorities -> {
2✔
UNCOV
425
                        var mappedAuthorities = baseMapper.mapAuthorities(authorities);
×
426
                        authorities.forEach(authority -> {
×
427
                                /*
428
                                 * Check for OidcUserAuthority because Spring Security 5.2
429
                                 * returns each scope as a GrantedAuthority, which we don't care
430
                                 * about.
431
                                 */
UNCOV
432
                                if (authority instanceof OidcUserAuthority) {
×
433
                                        localAuthProvider.mapAuthorities(
×
434
                                                        (OidcUserAuthority) authority, mappedAuthorities);
435
                                }
UNCOV
436
                                mappedAuthorities.add(authority);
×
437
                        });
×
438
                        return mappedAuthorities;
×
439
                };
440
        }
441

442
        @Bean
443
        @Role(ROLE_SUPPORT)
444
        LogoutHandler logoutHandler() {
445
                var handler = new SecurityContextLogoutHandler();
2✔
446
                handler.setClearAuthentication(true);
2✔
447
                handler.setInvalidateHttpSession(true);
2✔
448
                return handler;
2✔
449
        }
450
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc