package com.micer.easyball;

import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.context.annotation.Bean;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpRequest;import org.springframework.http.client.ClientHttpResponse;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;

// RestTemplate interceptor to block non-http/https and internal IPs
class SafeRestTemplateInterceptor implements ClientHttpRequestInterceptor {
    @Override
    public ClientHttpResponse intercept(ClientHttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        try {
            URI uri = request.getURI();
            String scheme = uri.getScheme();
            if (scheme == null || (!"http".equalsIgnoreCase(scheme) && !"https".equalsIgnoreCase(scheme))) {
                throw new IOException("Blocked non-HTTP/HTTPS scheme");
            }

            String host = uri.getHost();
            if (host == null || host.isEmpty()) {
                throw new IOException("Blocked empty host");
            }

            InetAddress[] addrs = InetAddress.getAllByName(host);
            for (InetAddress a : addrs) {
                if (a.isLoopbackAddress() || a.isSiteLocalAddress() || a.isAnyLocalAddress() || a.isLinkLocalAddress() || a.isMulticastAddress()) {
                    throw new IOException("Blocked internal or loopback address");
                }
            }
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            throw new IOException("Blocked request: " + e.getMessage());
        }
        return execution.execute(request, body);
    }
}

@SpringBootApplication
@MapperScan("com.micer.easyball.mapper")
public class EasyballApplication {

    public static void main(String[] args) {
        SpringApplication.run(EasyballApplication.class, args);
    }

    @Bean
    public RestTemplate restTemplate() {
        RestTemplate rt = new RestTemplate();
        rt.getInterceptors().add(new SafeRestTemplateInterceptor());
        return rt;
    }
}
