001/*
002 * Copyright 2026 The Apache Software Foundation.
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.apache.wiki.http.filter;
017
018import jakarta.servlet.http.HttpServletRequest;
019import jakarta.servlet.http.HttpServletRequestWrapper;
020import java.util.ArrayList;
021import java.util.Collections;
022import java.util.Enumeration;
023import java.util.List;
024import org.apache.wiki.util.URIScheme;
025
026/**
027 * see {@link ForwardedHeaderFilter}
028 * @since 3.0.1
029 */
030public class ForwardedRequest extends HttpServletRequestWrapper {
031
032    private final boolean isTrusted;
033    private final String requestHostname;   // resolved + validated, or null
034    private final String requestProtocol;
035    private final String clientAddress;
036    private final String requestPort;
037
038    ForwardedRequest(final HttpServletRequest req, final boolean trusted) {
039        super(req);
040        isTrusted = trusted;
041        // 1. Only consider X-Forwarded-* when the immediate peer is a trusted proxy.
042        // 2. Take the FIRST comma-separated element: mod_proxy APPENDS to a client-supplied
043        //    value, yielding "evil.example, wiki.example".
044        // 3. Validate the result against allowedHosts; on failure fall back to the container.
045        // 4. Validate the plain Host header the same way, regardless of proxy trust.
046        if (trusted) {
047            clientAddress = req.getHeader("X-Forwarded-For");
048            requestHostname = req.getHeader("X-Forwarded-Host");
049            requestProtocol = req.getHeader("X-Forwarded-Proto");
050            requestPort = req.getHeader("X-Forwarded-Port");
051        } else {
052            clientAddress = null;
053            requestHostname = null;
054            requestProtocol = null;
055            requestPort = null;
056        }
057    }
058
059    @Override
060    public String getServerName() {
061        return requestHostname != null ? stripPort(requestHostname) : super.getServerName();
062    }
063
064    @Override
065    public int getRemotePort() {
066        if (requestPort != null) {
067            return Integer.parseInt(requestPort);
068        }
069        return super.getRemotePort();
070    }
071
072    @Override
073    public String getRemoteAddr() {
074        /*
075        Lists the originating client IP address followed by the IP addresses 
076        of any intermediate proxies, separated by commas (e.g., clientIP, proxy1IP, proxy2IP).
077         */
078        if (clientAddress != null) {
079            String[] split = clientAddress.split("\\,");
080            return split[0];
081        }
082        return super.getRemoteAddr();
083    }
084
085    @Override
086    public int getServerPort() {
087        if (requestHostname != null) {
088            if (requestHostname.contains(":")) {
089                return Integer.parseInt(requestHostname.substring(requestHostname.indexOf(":") + 1));
090            }
091        }
092
093        return super.getServerPort();
094    }
095
096    @Override
097    public String getScheme() {
098        return requestProtocol != null ? requestProtocol : super.getScheme();
099    }
100
101    @Override
102    public boolean isSecure() {
103        return URIScheme.HTTPS.same(getScheme());
104    }
105
106    // Hide the raw headers so no future code path can re-read them unvalidated.
107    @Override
108    public String getHeader(final String name) {
109        return isForwardingHeader(name) ? null : super.getHeader(name);
110    }
111
112    @Override
113    public Enumeration<String> getHeaders(final String name) {
114        return isForwardingHeader(name) ? Collections.emptyEnumeration() : super.getHeaders(name);
115    }
116
117    @Override
118    public Enumeration<String> getHeaderNames() {
119        List<String> filtered = new ArrayList<>();
120        Enumeration<String> em = super.getHeaderNames();
121        while (em.hasMoreElements()) {
122            String key = em.nextElement();
123            if (!isTrusted && isForwardingHeader(key)) {
124                continue;
125            }
126            filtered.add(key);
127        }
128
129        return new Enumeration<String>() {
130            int ptr = 0;
131
132            @Override
133            public boolean hasMoreElements() {
134                if (ptr < filtered.size()) {
135                    return true;
136                }
137                return false;
138            }
139
140            @Override
141            public String nextElement() {
142                String v = filtered.get(ptr);
143                ptr++;
144                return v;
145            }
146        };
147    }
148
149    private String stripPort(String host) {
150        if (host != null && host.contains(":")) {
151            return host.substring(0, host.indexOf(":"));
152        }
153        return host;
154    }
155
156    private boolean isForwardingHeader(String name) {
157        return name.toLowerCase().startsWith("x-forwarded-");
158    }
159}