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

SpiNNakerManchester / JavaSpiNNaker / 14382497709

10 Apr 2025 02:05PM UTC coverage: 38.261% (-0.03%) from 38.289%
14382497709

push

github

rowleya
Add licenses

9191 of 24022 relevant lines covered (38.26%)

1.15 hits per line

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

53.15
/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.POST;
22
import static org.springframework.http.MediaType.APPLICATION_JSON;
23
import static org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames.ACCESS_TOKEN;
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.annotation.authentication.builders.AuthenticationManagerBuilder;
57
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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

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
@EnableGlobalMethodSecurity(prePostEnabled = true)
95
@UsedInJavadocOnly(PreAuthorize.class)
96
public class SecurityConfig {
3✔
97
        private static final Logger log = getLogger(SecurityConfig.class);
3✔
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 =
3✔
115
                                        new ParameterizedTypeReference<>() {
3✔
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);
3✔
134
                        log.info("custom SSL trust injection point installed");
3✔
135
                } catch (Exception e) {
×
136
                        throw new RuntimeException("failed to set up SSL trust", e);
×
137
                }
3✔
138
        }
3✔
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();
3✔
161
                var tm = trustManager(loadTrustStore(p));
3✔
162
                customTm = tm;
3✔
163
                log.info("set trust store from {}", p.getTruststorePath().getURI());
3✔
164
                return tm;
3✔
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);
3✔
196
        }
3✔
197

198
        private String oidcPath(String suffix) {
199
                return urlMaker.systemUrl("perform_oidc/" + suffix);
3✔
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
         * @throws Exception
214
         *             If anything goes wrong with setting up.
215
         */
216
        private void defineAccessPolicy(HttpSecurity http) throws Exception {
217
                http.authorizeRequests()
3✔
218
                                // Login process and static resources are available to all
219
                                .antMatchers(urlMaker.systemUrl("login*"),
3✔
220
                                                urlMaker.systemUrl("perform_*"), oidcPath("**"),
3✔
221
                                                urlMaker.systemUrl("error"),
3✔
222
                                                urlMaker.systemUrl("resources/*"),
3✔
223
                                                urlMaker.serviceUrl("openapi.json"),
3✔
224
                                                urlMaker.serviceUrl("swagger*"),
3✔
225
                                                urlMaker.serviceUrl("index.css"))
3✔
226
                                .permitAll()
3✔
227
                                // Everything else requires post-login
228
                                .anyRequest().authenticated();
3✔
229
        }
3✔
230

231
        /**
232
         * How we handle the mechanics of login with the REST API.
233
         *
234
         * @param http
235
         *            Where the configuration is applied to.
236
         * @throws Exception
237
         *             If anything goes wrong with setting up. Not expected.
238
         */
239
        private void defineAPILoginRules(HttpSecurity http) throws Exception {
240
                if (properties.isBasic()) {
3✔
241
                        http.httpBasic().authenticationEntryPoint(authenticationEntryPoint);
3✔
242
                }
243
                if (properties.getOpenid().isEnable()) {
3✔
244
                        http.oauth2ResourceServer()
×
245
                                        .authenticationEntryPoint(authenticationEntryPoint)
×
246
                                        .opaqueToken()
×
247
                                        .introspector(new UserInfoOpaqueTokenIntrospector());
×
248
                }
249
        }
3✔
250

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

286
        /**
287
         * Logging out is common code between the UI and the API, but pretty
288
         * pointless for Basic Auth as browsers will just log straight back in
289
         * again. Still, it is meaningful (it invalidates the session).
290
         *
291
         * @param http
292
         *            Where the configuration is applied to.
293
         * @throws Exception
294
         *             If anything goes wrong with setting up. Not expected.
295
         */
296
        private void defineLogoutRules(HttpSecurity http) throws Exception {
297
                var loginUrl = urlMaker.systemUrl("login.html");
3✔
298
                http.logout().logoutUrl(urlMaker.systemUrl("perform_logout"))
3✔
299
                                .addLogoutHandler((req, resp, auth) -> clearToken(req))
3✔
300
                                .deleteCookies(SESSION_COOKIE).invalidateHttpSession(true)
3✔
301
                                .logoutSuccessUrl(loginUrl);
3✔
302
        }
3✔
303

304
        /**
305
         * Define our main security controls.
306
         *
307
         * @param http
308
         *            Used to build the filter chain.
309
         * @return The filter chain that implements the controls.
310
         * @throws Exception
311
         *             If anything goes wrong with setting up. Not expected.
312
         */
313
        @Bean
314
        @Role(ROLE_SUPPORT)
315
        public SecurityFilterChain securityFilter(HttpSecurity http)
316
                        throws Exception {
317
                defineAccessPolicy(http);
3✔
318
                defineAPILoginRules(http);
3✔
319
                defineWebUILoginRules(http);
3✔
320
                defineLogoutRules(http);
3✔
321
                http.addFilterAfter(authApplicationFilter,
3✔
322
                                BasicAuthenticationFilter.class);
323
                return http.build();
3✔
324
        }
325

326
        private final class UserInfoOpaqueTokenIntrospector
327
                        implements OpaqueTokenIntrospector {
328
                private final OpaqueTokenIntrospector delegate;
329

330
                private final String userInfoUri;
331

332
                private UserInfoOpaqueTokenIntrospector() {
×
333
                        var p = properties.getOpenid();
×
334

335
                        delegate = new SpringOpaqueTokenIntrospector(p.getIntrospection(),
×
336
                                        p.getId(), p.getSecret());
×
337
                        userInfoUri = p.getUserinfo();
×
338
                }
×
339

340
                @Override
341
                public OAuth2AuthenticatedPrincipal introspect(String token) {
342
                        var authorized = delegate.introspect(token);
×
343
                        Instant issuedAt = authorized.getAttribute("issued-at");
×
344
                        Instant expiresAt = authorized.getAttribute("expires-at");
×
345

346
                        var userAttributes = userinfo(token);
×
347
                        var authorities = new LinkedHashSet<GrantedAuthority>();
×
348
                        var auth = new OidcUserAuthority(
×
349
                                        new OidcIdToken(token, issuedAt, expiresAt, userAttributes),
350
                                        new OidcUserInfo(userAttributes));
351
                        localAuthProvider.mapAuthorities(auth, authorities);
×
352
                        return new DefaultOAuth2User(authorities, userAttributes,
×
353
                                        "preferred_username");
354
                }
355

356
                private Map<String, Object> userinfo(String token) {
357
                        var headers = new HttpHeaders();
×
358
                        headers.setAccept(List.of(APPLICATION_JSON));
×
359
                        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
×
360
                        var request = new RequestEntity<>(ACCESS_TOKEN + "=" + token,
×
361
                                        headers, POST, URI.create(userInfoUri));
×
362

363
                        var restLog = LogFactory.getLog(LoggingCustomizer.class);
×
364
                        var restTemplate = new RestTemplateBuilder().customizers(
×
365
                                        new LoggingCustomizer(restLog, new Formatter())).build();
×
366
                        restTemplate.setErrorHandler(new OAuth2ErrorResponseErrorHandler());
×
367
                        var response =
×
368
                                        restTemplate.exchange(request, PARAMETERIZED_RESPONSE_TYPE);
×
369

370
                        return response.getBody();
×
371
                }
372
        }
373

374
        private final class Formatter implements LogFormatter {
×
375

376
                @Override
377
                public String formatResponse(ClientHttpResponse response)
378
                                throws IOException {
379
                        return String.format("Response:\n    Headers: %s\n    Body: %s",
×
380
                                        response.getHeaders(),
×
381
                                        new String(copyToByteArray(response.getBody())));
×
382
                }
383

384
                @Override
385
                public String formatRequest(HttpRequest request, byte[] body) {
386
                        return String.format(
×
387
                                        "%s Request to %s:\n"
388
                                        + "    Headers: %s\n"
389
                                        + "    Body: %s",
390
                                        request.getMethod(), request.getURI(), request.getHeaders(),
×
391
                                        new String(body));
392
                }
393
        }
394

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

423
        @Bean
424
        @Role(ROLE_SUPPORT)
425
        LogoutHandler logoutHandler() {
426
                var handler = new SecurityContextLogoutHandler();
3✔
427
                handler.setClearAuthentication(true);
3✔
428
                handler.setInvalidateHttpSession(true);
3✔
429
                return handler;
3✔
430
        }
431
}
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