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

SpiNNakerManchester / JavaSpiNNaker / 7361

12 Dec 2025 04:33PM UTC coverage: 36.322%. First build
7361

push

github

rowleya
Changes required for version 4.0.0

1915 of 5902 branches covered (32.45%)

Branch coverage included in aggregate %.

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

8985 of 24107 relevant lines covered (37.27%)

0.74 hits per line

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

55.65
/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
import static org.springframework.security.web.servlet.util.matcher.PathPatternRequestMatcher.pathPattern;
29

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

39
import javax.net.ssl.X509TrustManager;
40

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

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

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

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

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

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

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

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

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

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

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

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

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

167
        // ------------------------------------------------------------------------
168

169
        @Autowired
170
        private BasicAuthEntryPoint authenticationEntryPoint;
171

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

175
        @Autowired
176
        private AppAuthTransformationFilter authApplicationFilter;
177

178
        @Autowired
179
        private AuthenticationFailureHandler authenticationFailureHandler;
180

181
        @Autowired
182
        private AuthProperties properties;
183

184
        @Autowired
185
        private URLPathMaker urlMaker;
186

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

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

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

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

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

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

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

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

346
                private final String userInfoUri;
347

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

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

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

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

373
                private Map<String, Object> userinfo(String token) {
374
                        log.debug("Fetching user info from {}", userInfoUri);
×
375
                        var headers = new HttpHeaders();
×
376
                        headers.setAccept(List.of(APPLICATION_JSON));
×
377
                        headers.setBearerAuth(token);
×
378
                        var request = new RequestEntity<>(headers, GET,
×
379
                                        URI.create(userInfoUri));
×
380
                                        
NEW
381
                        var restTemplate = new RestTemplateBuilder().build();
×
382
                        restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
×
383
                        var response =
×
384
                                        restTemplate.exchange(request, PARAMETERIZED_RESPONSE_TYPE);
×
385

386
                        return response.getBody();
×
387
                }
388
        }
389

390
        /**
391
         * @return A converter that handles the initial extraction of collabratories
392
         *         and organisations from the info we have available when a user
393
         *         logs in explicitly in the web UI.
394
         * @see LocalAuthProviderImpl#mapAuthorities(OidcUserAuthority, Collection)
395
         */
396
        @Bean("hbp.collab-and-org.user-converter.shim")
397
        @Role(ROLE_SUPPORT)
398
        GrantedAuthoritiesMapper userAuthoritiesMapper() {
399
                var baseMapper = new SimpleAuthorityMapper();
2✔
400
                return authorities -> {
2✔
401
                        var mappedAuthorities = baseMapper.mapAuthorities(authorities);
×
402
                        authorities.forEach(authority -> {
×
403
                                /*
404
                                 * Check for OidcUserAuthority because Spring Security 5.2
405
                                 * returns each scope as a GrantedAuthority, which we don't care
406
                                 * about.
407
                                 */
408
                                if (authority instanceof OidcUserAuthority) {
×
409
                                        localAuthProvider.mapAuthorities(
×
410
                                                        (OidcUserAuthority) authority, mappedAuthorities);
411
                                }
412
                                mappedAuthorities.add(authority);
×
413
                        });
×
414
                        return mappedAuthorities;
×
415
                };
416
        }
417

418
        @Bean
419
        @Role(ROLE_SUPPORT)
420
        LogoutHandler logoutHandler() {
421
                var handler = new SecurityContextLogoutHandler();
2✔
422
                handler.setClearAuthentication(true);
2✔
423
                handler.setInvalidateHttpSession(true);
2✔
424
                return handler;
2✔
425
        }
426
}
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