001/**
002 * Copyright (C) 2006-2020 Talend Inc. - www.talend.com
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.talend.sdk.component.server.front.security.web;
017
018import static java.util.Optional.ofNullable;
019import static java.util.stream.Collectors.toSet;
020
021import java.util.Set;
022import java.util.stream.Stream;
023
024import javax.annotation.PostConstruct;
025import javax.enterprise.context.ApplicationScoped;
026import javax.inject.Inject;
027import javax.servlet.ServletRequest;
028import javax.servlet.http.HttpServletRequest;
029import javax.ws.rs.core.HttpHeaders;
030
031import org.talend.sdk.component.server.configuration.ComponentServerConfiguration;
032
033@ApplicationScoped
034public class EndpointSecurityService {
035
036    @Inject
037    private ComponentServerConfiguration configuration;
038
039    private Set<String> tokens;
040
041    @PostConstruct
042    private void init() {
043        tokens = Stream
044                .of(configuration.getSecuredEndpointsTokens().split(","))
045                .map(String::trim)
046                .filter(it -> !it.isEmpty() && !"-".equals(it))
047                .collect(toSet());
048    }
049
050    public boolean isAllowed(final ServletRequest servletRequest) {
051        return isSecured(servletRequest) || isLocal(servletRequest);
052    }
053
054    private boolean isLocal(final String addr) {
055        return addr != null && (addr.startsWith("127.0.0.") || addr.equals("::1") || addr.equals("0:0:0:0:0:0:0:1"));
056    }
057
058    private boolean isSecured(final ServletRequest servletRequest) {
059        final String authorization = HttpServletRequest.class.cast(servletRequest).getHeader(HttpHeaders.AUTHORIZATION);
060        return authorization != null && tokens.contains(authorization);
061    }
062
063    private boolean isLocal(final ServletRequest servletRequest) {
064        return HttpServletRequest.class.isInstance(servletRequest)
065                && ofNullable(HttpServletRequest.class.cast(servletRequest).getRemoteAddr())
066                        .map(this::isLocal)
067                        .orElse(false);
068    }
069}