fix: resolve client IP behind proxy and align upload limits #22

Merged
xhgit merged 1 commits from Morris/webup-cloud:morris into main 2026-11-14 09:35:36 +08:00
6 changed files with 279 additions and 9 deletions

No files matched your search

@@ -38,7 +38,7 @@ public class AuthController {
@NotBlank @Size(max = 10) String captchaCode) {}
public static String ip(HttpServletRequest req) {
return req.getRemoteAddr();
return ClientIp.of(req);
}
public static String ua(HttpServletRequest req) {
@@ -52,8 +52,13 @@ public class AuthController {
}
private void check(String email, String id, String code, HttpServletRequest r) {
store.limit("auth-ip:" + ip(r), 20, 60);
String address = ip(r);
// Per-address bucket: a single client cannot exhaust the shared allowance for everyone.
store.limit("auth-ip:" + address, 20, 60);
store.limit("auth-email:" + SecurityConfig.hash(email.toLowerCase(Locale.ROOT)), 10, 300);
// Global ceiling across all addresses, raised well above the per-address limit so ordinary
// traffic is never affected while total login throughput stays bounded.
store.limit("auth-global", 600, 60);
captcha.verify(id, code);
}
@@ -0,0 +1,114 @@
package run.webup.platform;
import jakarta.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.util.List;
/**
* Resolves the real client address behind the bundled reverse proxy.
*
* <p>The control plane is normally reached through the frontend nginx container. Because that proxy
* overwrites the forwarded headers, {@code request.getRemoteAddr()} is always the proxy address;
* using it directly would collapse every user into one rate-limit bucket and let a single caller
* lock out the whole platform.
*
* <p>Forwarded headers are only honoured when the direct peer is a proxy we operate (loopback or a
* private/container address). A public peer therefore cannot spoof its address by sending the
* header itself.
*/
public final class ClientIp {
private static final String FORWARDED_FOR = "X-Forwarded-For";
private static final String REAL_IP = "X-Real-IP";
private ClientIp() {}
/** Returns the client address used for rate limiting and audit records. */
public static String of(HttpServletRequest request) {
String peer = normalize(request.getRemoteAddr());
if (!trustedProxy(peer)) return peer;
// X-Real-IP is written by our own nginx from $remote_addr, so it cannot be spoofed by a client.
String real = normalize(request.getHeader(REAL_IP));
if (ipLiteral(real)) return real;
// Otherwise take the right-most X-Forwarded-For entry: that is the value our proxy appended.
// Anything further left came from the client and is not trustworthy.
String forwarded = lastValidForwardedFor(request.getHeader(FORWARDED_FOR));
return forwarded == null ? peer : forwarded;
}
private static String lastValidForwardedFor(String header) {
if (header == null || header.isBlank()) return null;
List<String> parts = List.of(header.split(","));
for (int i = parts.size() - 1; i >= 0; i--) {
String candidate = normalize(parts.get(i));
if (ipLiteral(candidate)) return candidate;
}
return null;
}
/** Trims whitespace, strips IPv6 brackets and unwraps IPv4-mapped IPv6 addresses. */
static String normalize(String value) {
if (value == null) return "";
String address = value.trim();
if (address.isEmpty()) return "";
if (address.startsWith("[")) {
int end = address.indexOf(']');
if (end > 0) address = address.substring(1, end);
}
if (address.regionMatches(true, 0, "::ffff:", 0, 7)) address = address.substring(7);
return address.length() > 64 ? address.substring(0, 64) : address;
}
/**
* True for both IPv4 and IPv6 literals. Guards {@link InetAddress#getByName} so a malformed
* header value can never trigger a DNS lookup.
*/
static boolean ipLiteral(String value) {
if (value == null || value.isEmpty()) return false;
boolean digitsAndDots = true;
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
if (!Character.isDigit(c) && c != '.') {
digitsAndDots = false;
break;
}
}
if (digitsAndDots) return value.indexOf('.') > 0;
// Conservative IPv6 check: hex digits, colons and at most one embedded IPv4 tail.
for (int i = 0; i < value.length(); i++) {
char c = value.charAt(i);
boolean ok =
Character.digit(c, 16) >= 0 || c == ':' || c == '.' || c == '%' || c == ']' || c == '[';
if (!ok) return false;
}
return value.indexOf(':') >= 0;
}
/** True when the direct peer is a reverse proxy we operate rather than an arbitrary client. */
static boolean trustedProxy(String peer) {
if (!ipLiteral(peer)) return false;
try {
InetAddress address = InetAddress.getByName(peer);
return address.isLoopbackAddress()
|| address.isAnyLocalAddress()
|| address.isSiteLocalAddress()
|| sharedAddressSpace(peer);
} catch (Exception e) {
return false;
}
}
/** RFC 6598 shared address space, used by container and overlay networks. */
private static boolean sharedAddressSpace(String peer) {
if (!peer.startsWith("100.")) return false;
String[] parts = peer.split("\\.");
if (parts.length != 4) return false;
try {
int second = Integer.parseInt(parts[1]);
return second >= 64 && second <= 127;
} catch (NumberFormatException e) {
return false;
}
}
}
@@ -0,0 +1,90 @@
package run.webup.platform;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
import jakarta.servlet.http.HttpServletRequest;
import org.junit.jupiter.api.Test;
class ClientIpTest {
private static HttpServletRequest request(String remoteAddr, String forwardedFor, String realIp) {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRemoteAddr()).thenReturn(remoteAddr);
when(request.getHeader("X-Forwarded-For")).thenReturn(forwardedFor);
when(request.getHeader("X-Real-IP")).thenReturn(realIp);
return request;
}
@Test
void directPublicClientIsNeverRewrittenByHeaders() {
// A public peer must not be able to spoof its address.
assertEquals(
"203.0.113.9",
ClientIp.of(request("203.0.113.9", "1.2.3.4", "5.6.7.8")));
}
@Test
void trustedProxyResolvesRealClientFromRealIp() {
assertEquals(
"203.0.113.9",
ClientIp.of(request("172.19.0.5", null, "203.0.113.9")));
}
@Test
void trustedProxyFallsBackToForwardedFor() {
assertEquals(
"203.0.113.9",
ClientIp.of(request("172.19.0.5", "203.0.113.9", null)));
}
@Test
void usesRightMostForwardedEntrySoClientCannotSpoofPrefix() {
// The client sent "1.2.3.4"; our proxy appended the real address on the right.
assertEquals(
"203.0.113.9",
ClientIp.of(request("172.19.0.5", "1.2.3.4, 203.0.113.9", null)));
}
@Test
void separateClientsGetSeparateBuckets() {
// Regression: behind the proxy these used to both resolve to 172.19.0.5.
String first = ClientIp.of(request("172.19.0.5", null, "198.51.100.7"));
String second = ClientIp.of(request("172.19.0.5", null, "198.51.100.8"));
assertNotEquals(first, second);
}
@Test
void loopbackProxyIsTrusted() {
assertEquals("203.0.113.9", ClientIp.of(request("127.0.0.1", null, "203.0.113.9")));
assertEquals("203.0.113.9", ClientIp.of(request("::1", null, "203.0.113.9")));
}
@Test
void ipv4MappedIpv6IsUnwrapped() {
assertEquals(
"203.0.113.9",
ClientIp.of(request("::ffff:172.19.0.5", null, "::ffff:203.0.113.9")));
}
@Test
void bracketedIpv6IsUnwrapped() {
assertEquals("2001:db8::1", ClientIp.normalize("[2001:db8::1]"));
}
@Test
void malformedForwardedValueFallsBackToPeerInsteadOfResolvingDns() {
assertEquals(
"172.19.0.5",
ClientIp.of(request("172.19.0.5", "not-an-ip", "also-not-an-ip")));
}
@Test
void blankAndNullInputsAreSafe() {
assertEquals("", ClientIp.normalize(null));
assertEquals("", ClientIp.normalize(" "));
assertFalse(ClientIp.ipLiteral(""));
assertFalse(ClientIp.trustedProxy(""));
assertEquals("172.19.0.5", ClientIp.of(request("172.19.0.5", " ", " ")));
}
}
+15 -6
View File
@@ -4,26 +4,35 @@ server {
root /usr/share/nginx/html;
index index.html;
server_tokens off;
client_max_body_size 1m;
client_max_body_size 26m;
add_header X-Content-Type-Options nosniff always;
add_header Referrer-Policy strict-origin-when-cross-origin always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data: https:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'" always;
# Oversized uploads are answered in the same JSON shape as the API instead of nginx's HTML page.
error_page 413 = @upload_too_large;
location @upload_too_large {
default_type application/json;
return 413 '{"message":"单文件不能超过 25MiB"}';
}
location /api/public/extensions/plugin-frame/ {
# This response carries the backend's sandbox policy. The app shell remains non-frameable.
add_header X-Content-Type-Options nosniff always;
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For "";
proxy_set_header X-Real-IP "";
# Overwrite rather than append: a client-supplied value must never reach the backend. The
# backend only reads these when the direct peer is a trusted proxy.
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
}
location /api/ {
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Host $host;
# Backend intentionally does not trust user-supplied forwarded IP headers.
proxy_set_header X-Forwarded-For "";
proxy_set_header X-Real-IP "";
# Overwrite rather than append: a client-supplied value must never reach the backend. The
# backend only trusts these when the direct peer is a private/loopback proxy address.
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Real-IP $remote_addr;
}
location / { try_files $uri $uri/ /index.html; }
}
+46
View File
@@ -913,6 +913,10 @@
.landing-menu {
display: none;
}
/* Only rendered inside the collapsed mobile menu; desktop keeps the standalone 登录 link. */
.landing-nav-login {
display: none;
}
.mobile-break {
display: none;
}
@@ -996,8 +1000,50 @@
}
}
@media (max-width: 850px) {
.landing-nav {
position: relative;
gap: 10px;
}
.landing-menu {
display: inline-flex;
margin-left: auto;
}
.landing-nav nav {
position: absolute;
top: calc(100% + 1px);
left: 16px;
right: 16px;
display: none;
flex-direction: column;
gap: 2px;
padding: 8px;
background: var(--landing-surface, #fff);
border: 1px solid var(--landing-border, #eef1f6);
border-radius: 12px;
box-shadow: 0 18px 40px #1d2d4814;
z-index: 40;
}
.landing-nav nav.expanded {
display: flex;
}
.landing-nav nav > a {
padding: 12px 14px;
border-radius: 8px;
font-size: 13px;
}
.landing-nav nav > a:hover {
background: var(--landing-accentSoft, #edf3ff);
}
.landing-nav nav .landing-nav-login {
display: block;
padding: 12px 14px;
border-radius: 8px;
font-size: 13px;
color: var(--landing-muted, #7a879b);
}
.landing-nav nav .landing-nav-login:hover {
background: var(--landing-accentSoft, #edf3ff);
color: var(--landing-accent, #3868f5);
}
.landing-hero {
grid-template-columns: 1fr;
+7 -1
View File
@@ -105,7 +105,13 @@ onMounted(async () => {
<a href="#features" @click="menu = false">平台能力</a
><a href="#workflow" @click="menu = false">开发流程</a
><a href="#plans" @click="menu = false">托管套餐</a
><a href="#questions" @click="menu = false">常见问题</a>
><a href="#questions" @click="menu = false">常见问题</a
><RouterLink
class="landing-nav-login"
to="/login"
@click="menu = false"
>登录</RouterLink
>
</nav>
<div class="landing-nav-actions">
<RouterLink class="landing-login" to="/login">登录</RouterLink