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

SpiNNakerManchester / JavaSpiNNaker / 6985

29 Aug 2025 11:16AM UTC coverage: 36.278% (-0.03%) from 36.307%
6985

push

github

rowleya
Try "normal" way of getting user info

1906 of 5888 branches covered (32.37%)

Branch coverage included in aggregate %.

0 of 7 new or added lines in 1 file covered. (0.0%)

6 existing lines in 1 file now uncovered.

8965 of 24078 relevant lines covered (37.23%)

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.security.web.util.matcher.AntPathRequestMatcher.antMatcher;
24
import static org.springframework.util.StreamUtils.copyToByteArray;
25
import static uk.ac.manchester.spinnaker.alloc.security.AppAuthTransformationFilter.clearToken;
26
import static uk.ac.manchester.spinnaker.alloc.security.Utils.installInjectableTrustStoreAsDefault;
27
import static uk.ac.manchester.spinnaker.alloc.security.Utils.loadTrustStore;
28
import static uk.ac.manchester.spinnaker.alloc.security.Utils.trustManager;
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.hobsoft.spring.resttemplatelogger.LogFormatter;
43
import org.hobsoft.spring.resttemplatelogger.LoggingCustomizer;
44
import org.slf4j.Logger;
45
import org.springframework.beans.factory.annotation.Autowired;
46
import org.springframework.boot.web.client.RestTemplateBuilder;
47
import org.springframework.context.annotation.Bean;
48
import org.springframework.context.annotation.Role;
49
import org.springframework.core.ParameterizedTypeReference;
50
import org.springframework.http.HttpHeaders;
51
import org.springframework.http.HttpRequest;
52
import org.springframework.http.MediaType;
53
import org.springframework.http.RequestEntity;
54
import org.springframework.http.client.ClientHttpResponse;
55
import org.springframework.security.access.prepost.PreAuthorize;
56
import org.springframework.security.config.Customizer;
57
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
58
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
59
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
60
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
61
import org.springframework.security.core.GrantedAuthority;
62
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
63
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
64
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
65
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
66
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
67
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
68
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
69
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
70
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
71
import org.springframework.security.oauth2.server.resource.introspection.SpringOpaqueTokenIntrospector;
72
import org.springframework.security.web.SecurityFilterChain;
73
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
74
import org.springframework.security.web.authentication.logout.LogoutHandler;
75
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
76
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
77
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
78

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

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

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

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

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

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

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

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

127
        private static final String SESSION_COOKIE = "JSESSIONID";
128

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

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

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

170
        // ------------------------------------------------------------------------
171

172
        @Autowired
173
        private BasicAuthEntryPoint authenticationEntryPoint;
174

175
        @Autowired
176
        private LocalAuthenticationProvider<?> localAuthProvider;
177

178
        @Autowired
179
        private AppAuthTransformationFilter authApplicationFilter;
180

181
        @Autowired
182
        private AuthenticationFailureHandler authenticationFailureHandler;
183

184
        @Autowired
185
        private AuthProperties properties;
186

187
        @Autowired
188
        private URLPathMaker urlMaker;
189

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

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

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

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

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

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

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

345
        private final class UserInfoOpaqueTokenIntrospector
346
                        implements OpaqueTokenIntrospector {
347
                private final OpaqueTokenIntrospector delegate;
348

349
                private final String userInfoUri;
350

351
                private UserInfoOpaqueTokenIntrospector() {
×
352
                        var p = properties.getOpenid();
×
353

NEW
354
                        delegate = SpringOpaqueTokenIntrospector
×
NEW
355
                                        .withIntrospectionUri(p.getIntrospection())
×
NEW
356
                                        .clientId(p.getId()).clientSecret(p.getSecret()).build();
×
357
                        userInfoUri = p.getUserinfo();
×
358
                }
×
359

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

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

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

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

391
                        return response.getBody();
×
392
                }
393
        }
394

395
        private final class Formatter implements LogFormatter {
×
396

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

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

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

444
        @Bean
445
        @Role(ROLE_SUPPORT)
446
        LogoutHandler logoutHandler() {
447
                var handler = new SecurityContextLogoutHandler();
2✔
448
                handler.setClearAuthentication(true);
2✔
449
                handler.setInvalidateHttpSession(true);
2✔
450
                return handler;
2✔
451
        }
452
}
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