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

SpiNNakerManchester / JavaSpiNNaker / 7003

01 Sep 2025 09:15AM UTC coverage: 36.277% (+0.008%) from 36.269%
7003

push

github

web-flow
Merge pull request #1295 from SpiNNakerManchester/fix_oidc_auth

Fix OIDC auth

1905 of 5888 branches covered (32.35%)

Branch coverage included in aggregate %.

9 of 28 new or added lines in 3 files covered. (32.14%)

4 existing lines in 1 file now uncovered.

8965 of 24076 relevant lines covered (37.24%)

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.RequestEntity;
53
import org.springframework.http.client.ClientHttpResponse;
54
import org.springframework.security.access.prepost.PreAuthorize;
55
import org.springframework.security.config.Customizer;
56
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
57
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
58
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
59
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
60
import org.springframework.security.core.GrantedAuthority;
61
import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;
62
import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
63
import org.springframework.security.oauth2.client.http.OAuth2ErrorResponseErrorHandler;
64
import org.springframework.security.oauth2.core.OAuth2AuthenticatedPrincipal;
65
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
66
import org.springframework.security.oauth2.core.oidc.OidcUserInfo;
67
import org.springframework.security.oauth2.core.oidc.user.OidcUserAuthority;
68
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
69
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector;
70
import org.springframework.security.oauth2.server.resource.introspection.SpringOpaqueTokenIntrospector;
71
import org.springframework.security.web.SecurityFilterChain;
72
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
73
import org.springframework.security.web.authentication.logout.LogoutHandler;
74
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
75
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
76
import org.springframework.web.servlet.handler.HandlerMappingIntrospector;
77

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

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

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

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

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

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

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

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

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

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

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

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

169
        // ------------------------------------------------------------------------
170

171
        @Autowired
172
        private BasicAuthEntryPoint authenticationEntryPoint;
173

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

177
        @Autowired
178
        private AppAuthTransformationFilter authApplicationFilter;
179

180
        @Autowired
181
        private AuthenticationFailureHandler authenticationFailureHandler;
182

183
        @Autowired
184
        private AuthProperties properties;
185

186
        @Autowired
187
        private URLPathMaker urlMaker;
188

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

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

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

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

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

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

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

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

348
                private final String userInfoUri;
349

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

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

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

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

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

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

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

394
        private final class Formatter implements LogFormatter {
×
395

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

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

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

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