Add administrator-controlled IP project entry redirects

This commit is contained in:
WebUp Cloud committed 2026-11-08 12:25:01 +08:00
1 parent 1f25bbd1f9
commit 2f93fb023a
13 files changed
+439 -5

No files matched your search

@@ -161,6 +161,7 @@ public class AdminController {
Map.entry("mainDomain", 253),
Map.entry("deploymentDomain", 253),
Map.entry("domainDeliveryTarget", 253),
Map.entry("ipEntryOrigin", 100),
Map.entry("domainTemplate", 300),
Map.entry("filing", 100),
Map.entry("footer", 500),
@@ -190,18 +191,22 @@ public class AdminController {
&& !e.getValue().isEmpty()
&& !e.getValue().matches("https://[^\\s]+|/brand/[A-Za-z0-9_.-]+"))
throw new ApiError.Failure(400, "Logo 需要 HTTPS 地址");
String value =
e.getKey().equals("ipEntryOrigin")
? IpEntryService.validateOrigin(e.getValue())
: e.getValue();
users
.db()
.update(
"UPDATE system_settings SET setting_value=?,updated_at=CURRENT_TIMESTAMP WHERE"
+ " setting_key=?",
e.getValue(),
value,
e.getKey());
audit(
actor.id(),
"SETTING_UPDATE",
e.getKey(),
"旧值: " + before.get(e.getKey()) + "; 新值: " + e.getValue(),
"旧值: " + before.get(e.getKey()) + "; 新值: " + value,
AuthController.ip(req));
}
return readSettings();
@@ -0,0 +1,41 @@
package run.webup.platform;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import jakarta.validation.constraints.Size;
import java.util.Map;
import java.util.UUID;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
@RestController
public class IpEntryController {
private final IpEntryService entries;
private final ProjectController projects;
public IpEntryController(IpEntryService entries, ProjectController projects) {
this.entries = entries;
this.projects = projects;
}
public record Config(boolean enabled, @Size(max = 63) String alias) {}
@PutMapping("/api/admin/sites/{project}/ip-entry")
@PreAuthorize("hasAuthority('hosting:write')")
public Object configure(
@AuthenticationPrincipal SecurityConfig.Identity who,
@PathVariable UUID project,
@Valid @RequestBody Config config,
HttpServletRequest req) {
entries.configure(project, who.id(), config.enabled(), config.alias(), AuthController.ip(req));
return Map.of("message", config.enabled() ? "IP 入口已开启" : "IP 入口已关闭");
}
@GetMapping("/api/projects/{project}/ip-entry")
public Object forProject(
@AuthenticationPrincipal SecurityConfig.Identity who, @PathVariable UUID project) {
projects.find(who, project);
return entries.forProject(project);
}
}
@@ -0,0 +1,40 @@
package run.webup.platform;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;
import org.springframework.web.filter.OncePerRequestFilter;
/** Handles the dedicated IP virtual host before normal control-plane routes. */
final class IpEntryFilter extends OncePerRequestFilter {
private static final Pattern ALIAS = Pattern.compile("/([a-z0-9][a-z0-9-]{1,61}[a-z0-9])/?");
private final IpEntryService entries;
IpEntryFilter(IpEntryService entries) {
this.entries = entries;
}
@Override
protected void doFilterInternal(
HttpServletRequest req, HttpServletResponse res, FilterChain chain)
throws ServletException, IOException {
var path = ALIAS.matcher(req.getRequestURI().substring(req.getContextPath().length()));
String host = req.getHeader("Host");
if (!(req.getMethod().equals("GET") || req.getMethod().equals("HEAD"))
|| !path.matches()
|| host == null
|| !host.matches("[0-9.]+(?::[0-9]+)?")
|| !entries.matchesHost(host)) {
chain.doFilter(req, res);
return;
}
var target = entries.redirect(path.group(1));
res.setHeader("Cache-Control", "no-store");
res.setStatus(
target.isPresent() ? HttpServletResponse.SC_FOUND : HttpServletResponse.SC_NOT_FOUND);
target.ifPresent(uri -> res.setHeader("Location", uri.toASCIIString()));
}
}
@@ -0,0 +1,166 @@
package run.webup.platform;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.util.*;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class IpEntryService {
private static final Set<String> RESERVED_PATHS =
Set.of(
"projects",
"develop",
"models",
"wallet",
"hosting",
"domains",
"tickets",
"extensions",
"account",
"actuator",
"health",
"robots",
"favicon",
"brand",
"ip-entry");
private final JdbcTemplate db;
private final ObjectMapper json;
public IpEntryService(JdbcTemplate db, ObjectMapper json) {
this.db = db;
this.json = json;
}
static String validateOrigin(String input) {
if (input.isBlank()) return "";
try {
var uri = URI.create(input.trim());
if (!Set.of("http", "https").contains(uri.getScheme())
|| uri.getHost() == null
|| !uri.getHost().matches("(?:0|[1-9][0-9]{0,2})(?:\\.(?:0|[1-9][0-9]{0,2})){3}")
|| Arrays.stream(uri.getHost().split("\\."))
.anyMatch(part -> Integer.parseInt(part) > 255)
|| uri.getRawUserInfo() != null
|| uri.getRawQuery() != null
|| uri.getRawFragment() != null
|| !Set.of("", "/").contains(uri.getRawPath())
|| uri.getPort() == 0
|| uri.getPort() > 65535) throw new IllegalArgumentException();
int defaultPort = uri.getScheme().equals("https") ? 443 : 80;
int port = uri.getPort();
return uri.getScheme()
+ "://"
+ uri.getHost()
+ (port < 0 || port == defaultPort ? "" : ":" + port);
} catch (RuntimeException error) {
throw new ApiError.Failure(400, "请输入 HTTP 或 HTTPS 的 IPv4 入口地址,可带端口,不含路径");
}
}
private String origin() {
return db.queryForObject(
"SELECT setting_value FROM system_settings WHERE setting_key='ipEntryOrigin'",
String.class);
}
@Transactional
public void configure(UUID project, UUID actor, boolean enabled, String alias, String ip) {
var projects = db.queryForList("SELECT status FROM projects WHERE id=? FOR UPDATE", project);
if (projects.isEmpty()) throw new ApiError.Failure(404, "项目不存在");
if (enabled) {
if ("ARCHIVED".equals(projects.getFirst().get("status")))
throw new ApiError.Failure(409, "归档项目不能启用 IP 入口");
if (origin().isBlank()) throw new ApiError.Failure(409, "请先在系统设置中填写 IP 入口地址");
alias = DomainNames.slug(alias);
if (RESERVED_PATHS.contains(alias)) throw new ApiError.Failure(400, "该项目路径是系统保留名称");
if (db.update(
"UPDATE project_ip_entries SET alias=?,enabled=TRUE WHERE project_id=?",
alias,
project)
== 0)
db.update(
"INSERT INTO project_ip_entries(project_id,alias,enabled) VALUES (?,?,TRUE)",
project,
alias);
} else {
db.update("UPDATE project_ip_entries SET enabled=FALSE WHERE project_id=?", project);
}
db.update(
"INSERT INTO admin_operation_logs(id,actor_id,action,target,ip,details) VALUES"
+ " (?,?,?,?,?,?)",
UUID.randomUUID(),
actor,
"IP_ENTRY_UPDATE",
project.toString(),
ip,
enabled ? "启用 IP 入口 /" + alias : "关闭 IP 入口");
}
public Map<String, Object> forProject(UUID project) {
String origin = origin();
var entries =
db.queryForList(
"SELECT alias FROM project_ip_entries WHERE project_id=? AND enabled=TRUE", project);
if (origin.isBlank() || entries.isEmpty()) return Map.of("status", "DISABLED", "url", "");
String url = target(project).isPresent() ? origin + "/" + entries.getFirst().get("alias") : "";
return Map.of("status", url.isEmpty() ? "WAITING" : "ACTIVE", "url", url);
}
boolean matchesHost(String requestHost) {
String origin = origin();
return !origin.isBlank() && URI.create(origin).getRawAuthority().equalsIgnoreCase(requestHost);
}
Optional<URI> redirect(String alias) {
var entries =
db.queryForList(
"SELECT project_id FROM project_ip_entries WHERE alias=? AND enabled=TRUE", alias);
if (entries.isEmpty()) return Optional.empty();
return target((UUID) entries.getFirst().get("project_id"));
}
private Optional<URI> target(UUID project) {
var deployments =
db.queryForList(
"SELECT d.spec_json FROM project_deployments d JOIN projects p ON p.id=d.project_id"
+ " JOIN project_moderation m ON m.project_id=p.id"
+ " JOIN project_subscriptions s ON s.project_id=p.id"
+ " WHERE d.project_id=? AND p.status<>'ARCHIVED' AND m.status='APPROVED'"
+ " AND s.status='ACTIVE' AND s.paid_until>CURRENT_TIMESTAMP AND d.status='ACTIVE'"
+ " ORDER BY d.created_at DESC LIMIT 1",
project);
if (deployments.isEmpty()) return Optional.empty();
var operations =
db.queryForList(
"SELECT action,status FROM runtime_operations WHERE project_id=?"
+ " ORDER BY created_at DESC,id DESC LIMIT 1",
project);
if (!operations.isEmpty()
&& (!"RESUME".equals(operations.getFirst().get("action"))
|| !"DONE".equals(operations.getFirst().get("status")))) return Optional.empty();
var serviceIds = new HashSet<String>();
try {
for (var service : json.readTree(deployments.getFirst().get("spec_json").toString()))
serviceIds.add(service.path("id").asText());
} catch (JsonProcessingException error) {
return Optional.empty();
}
var domains =
db.queryForList(
"SELECT d.hostname,d.service_id FROM project_domains d"
+ " JOIN project_services s ON s.id=d.service_id AND s.project_id=d.project_id"
+ " WHERE d.project_id=? AND d.status='ACTIVE' AND d.desired_state='ACTIVE'"
+ " AND s.enabled=TRUE ORDER BY d.is_primary DESC,d.created_at,d.id",
project);
return domains.stream()
.filter(row -> serviceIds.contains(row.get("service_id").toString()))
.map(
row ->
URI.create("https://" + DomainNames.hostname(row.get("hostname").toString()) + "/"))
.findFirst();
}
}
@@ -41,7 +41,8 @@ public class SecurityConfig {
}
@Bean
SecurityFilterChain security(HttpSecurity http, JdbcTemplate db) throws Exception {
SecurityFilterChain security(HttpSecurity http, JdbcTemplate db, IpEntryService entries)
throws Exception {
var pluginFrame =
PathPatternRequestMatcher.withDefaults()
.matcher("/api/public/extensions/plugin-frame/{id}");
@@ -81,6 +82,7 @@ public class SecurityConfig {
r.setContentType("application/json;charset=UTF-8");
r.getWriter().write("{\"message\":\"没有执行此操作的权限\"}");
}));
http.addFilterBefore(new IpEntryFilter(entries), UsernamePasswordAuthenticationFilter.class);
http.addFilterBefore(
new OncePerRequestFilter() {
protected void doFilterInternal(
@@ -32,13 +32,15 @@ public class SiteAdminController {
return db.queryForList(
"SELECT p.id,p.name,p.stack,p.status AS"
+ " project_status,p.created_at,u.email,u.display_name,COALESCE(m.status,'PENDING') AS"
+ " review_status,m.reason AS review_reason,s.status AS"
+ " review_status,m.reason AS review_reason,i.alias AS ip_entry_alias,"
+ " COALESCE(i.enabled,FALSE) AS ip_entry_enabled,s.status AS"
+ " subscription_status,s.paid_until,(SELECT COUNT(*) FROM project_services v WHERE"
+ " v.project_id=p.id) AS services,(SELECT COUNT(*) FROM project_deployments d WHERE"
+ " d.project_id=p.id AND d.status='ACTIVE') AS active_deployments,(SELECT o.status"
+ " FROM runtime_operations o WHERE o.project_id=p.id ORDER BY o.created_at DESC LIMIT"
+ " 1) AS operation_status FROM projects p JOIN users u ON u.id=p.owner_id LEFT JOIN"
+ " project_moderation m ON m.project_id=p.id LEFT JOIN project_subscriptions s ON"
+ " project_moderation m ON m.project_id=p.id LEFT JOIN project_ip_entries i ON"
+ " i.project_id=p.id LEFT JOIN project_subscriptions s ON"
+ " s.project_id=p.id WHERE (LOWER(p.name) LIKE ? OR LOWER(u.email) LIKE ?) AND"
+ " (?='ALL' OR COALESCE(m.status,'PENDING')=?) ORDER BY p.created_at DESC LIMIT 200",
pattern,
@@ -0,0 +1,7 @@
INSERT INTO system_settings VALUES ('ipEntryOrigin','',CURRENT_TIMESTAMP);
CREATE TABLE project_ip_entries (
project_id UUID PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE,
alias VARCHAR(63) NOT NULL UNIQUE,
enabled BOOLEAN NOT NULL DEFAULT TRUE
);
@@ -137,6 +137,80 @@ class DomainIntegrationTest {
coordinator.execute(row);
}
@Test
void ipPathRequiresAdminAndRedirectsOnlyToAnActiveReviewedProject() throws Exception {
UUID admin = users.create("ip-admin@test.com", "Admin", "StrongPassword123", "test");
users.db().update("INSERT INTO user_roles VALUES (?,'SUPER_ADMIN')", admin);
String adminToken =
users
.login("ip-admin@test.com", "StrongPassword123", "test", "test", 1)
.get("token")
.toString();
String memberToken =
users
.login("domains@test.com", "StrongPassword123", "test", "test", 1)
.get("token")
.toString();
String ip = "192.0.2.20:8088", alias = "/student-info";
String adminRoute = "/api/admin/sites/" + project + "/ip-entry";
String memberRoute = "/api/projects/" + project + "/ip-entry";
String enable = "{\"enabled\":true,\"alias\":\"student-info\"}";
try {
mvc.perform(
put("/api/admin/settings")
.header("Authorization", "Bearer " + adminToken)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"ipEntryOrigin\":\"http://" + ip + "\"}"))
.andExpect(status().isOk());
mvc.perform(
put(adminRoute)
.header("Authorization", "Bearer " + memberToken)
.contentType(MediaType.APPLICATION_JSON)
.content(enable))
.andExpect(status().isForbidden());
mvc.perform(
put(adminRoute)
.header("Authorization", "Bearer " + adminToken)
.contentType(MediaType.APPLICATION_JSON)
.content(enable))
.andExpect(status().isOk());
mvc.perform(get(memberRoute).header("Authorization", "Bearer " + memberToken))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("WAITING"));
mvc.perform(get(alias).header("Host", ip)).andExpect(status().isNotFound());
publish();
UUID domain = (UUID) platform("published-student-site").get("id");
users.db().update("UPDATE project_domains SET status='ACTIVE' WHERE id=?", domain);
mvc.perform(get(alias).header("Host", "unrelated.example"))
.andExpect(status().isUnauthorized());
mvc.perform(get(alias + "/").header("Host", ip))
.andExpect(status().isFound())
.andExpect(header().string("Location", "https://published-student-site.webup.run/"))
.andExpect(header().string("Cache-Control", "no-store"));
mvc.perform(get(memberRoute).header("Authorization", "Bearer " + memberToken))
.andExpect(status().isOk())
.andExpect(jsonPath("$.url").value("http://" + ip + alias));
users
.db()
.update("UPDATE project_moderation SET status='BANNED' WHERE project_id=?", project);
mvc.perform(get(alias).header("Host", ip)).andExpect(status().isNotFound());
users
.db()
.update("UPDATE project_moderation SET status='APPROVED' WHERE project_id=?", project);
mvc.perform(
put(adminRoute)
.header("Authorization", "Bearer " + adminToken)
.contentType(MediaType.APPLICATION_JSON)
.content("{\"enabled\":false}"))
.andExpect(status().isOk());
mvc.perform(get(alias).header("Host", ip)).andExpect(status().isNotFound());
} finally {
users
.db()
.update("UPDATE system_settings SET setting_value='' WHERE setting_key='ipEntryOrigin'");
}
}
@Test
void stablePlatformBindingIsIdempotentAndNeverReassignsRemovedHost() {
var a = platform("stable-project");
+24
View File
@@ -33,6 +33,30 @@
- `ERROR`:保留具体阶段错误,最多五次自动尝试,之后需手动重试。
- `REMOVING` / `REMOVED`:入口解绑执行中 / 已确认。
## IP 项目入口
在「系统设置」填写对外的 IPv4 入口地址,例如 `http://192.0.2.20`。然后在「网站管理与人工审核」为项目开启 IP 入口并填写路径名。浏览器访问 `http://192.0.2.20/student-info` 后,会跳转到该项目已生效的 HTTPS 域名。若有多个可用域名,优先使用主域名。
将该 IP 的 HTTP 流量接到控制面,反向代理需保留请求的 `Host` 和原路径。例如在专用 Nginx 虚拟主机中配置:
```nginx
server {
listen 80;
server_name 192.0.2.20;
location ~ "^/[a-z0-9][a-z0-9-]{1,61}[a-z0-9]/?$" {
proxy_set_header Host $http_host;
proxy_pass http://127.0.0.1:8080;
}
location / { return 404; }
}
```
将示例 IP 和上游地址换成实际配置。如果入口本身用 HTTPS,代理还需提供覆盖该 IP 的证书。清空系统设置中的入口地址即可关闭所有 IP 入口;也可从网站管理关闭单个项目。
入口只对审核通过、托管套餐有效、部署生效且域名就绪的项目开放。项目被封禁、归档或停运后,入口停止跳转。项目名使用唯一的小写路径名,关闭入口后仍为该项目保留原路径。
## 域名运行校验
证书核对包含目标域名、Secret 名称、当前 observedGeneration 的 Ready 条件和有效期。Ingress 入口需要控制器报告外部地址;自建控制器需正确配置发布地址。工作负载必须有实际 Ready Pod,不能仅凭创建 API 返回成功就视为上线。
平台域名调用阿里云 DNS 时先查询精确主机记录;已有冲突不覆盖。借用已有正确 CNAME 时不取得删除权。新增记录返回 ID 后才登记由本平台创建;创建超时后无法证明归属的记录按外部记录保留,不冒险清理。解绑只删除明确登记且内容仍匹配的记录;AK 身份改变后保留原记录并要求人工核对。删除重试会先检查记录是否已经不存在。
+1
View File
@@ -103,6 +103,7 @@ const fields = [
["mainDomain", "官网域名"],
["deploymentDomain", "用户部署根域名"],
["domainDeliveryTarget", "项目入口 CNAME 目标(已接入的 Ingress 域名)"],
["ipEntryOrigin", "项目 IP 入口地址(如 http://192.0.2.20,留空关闭)"],
["domainTemplate", "用户域名模板({project} 为项目名)"],
["faviconUrl", "Favicon HTTPS 地址"],
["filing", "备案信息"],
+26
View File
@@ -59,6 +59,23 @@ async function history(p: any) {
error.value = (e as Error).message;
}
}
async function configureIpEntry(site: any, enabled: boolean) {
const alias = enabled
? prompt("设置 IP 入口的项目路径,例如 student-info", site.ip_entry_alias || "")
: "";
if (alias === null) return;
error.value = "";
try {
const result = await api(`/admin/sites/${site.id}/ip-entry`, {
method: "PUT",
body: body({ enabled, alias: alias.trim() }),
});
success.value = result.message;
await load();
} catch (cause) {
error.value = (cause as Error).message;
}
}
onMounted(load);
</script>
<template>
@@ -105,6 +122,7 @@ onMounted(load);
}}<small class="block"
>{{ p.stack }} · {{ p.services }} 服务</small
>
<small v-if="p.ip_entry_enabled" class="block">IP 入口 /{{ p.ip_entry_alias }}</small>
</td>
<td>
{{ p.display_name }}<small class="block">{{ p.email }}</small>
@@ -151,6 +169,14 @@ onMounted(load);
封禁</button
><button class="link" @click="history(p)">执行记录</button>
</div>
<div v-if="store.user?.permissions.includes('hosting:write')" class="table-actions">
<button class="link" :disabled="busy" @click="configureIpEntry(p, true)">
{{ p.ip_entry_enabled ? "编辑 IP 入口" : "开启 IP 入口" }}
</button>
<button v-if="p.ip_entry_enabled" class="link danger" :disabled="busy" @click="configureIpEntry(p, false)">
关闭 IP 入口
</button>
</div>
</td>
</tr>
<tr v-if="!sites.length">
+7
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { api, body } from "../api";
import ProjectIpEntry from "./ProjectIpEntry.vue";
const projects = ref<any[]>([]),
project = ref(""),
services = ref<any[]>([]),
@@ -240,6 +241,12 @@ onUnmounted(() => clearInterval(timer));
output
}}</pre>
</section>
<ProjectIpEntry
v-if="project"
:key="project"
:project-id="project"
:deployment-status="deployments[0]?.status"
/>
<div class="section-title" style="margin-top: 26px">
<h3>托管套餐</h3>
<span>购买快照,保护既有资源与价格</span>
+39
View File
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { ref, watch } from "vue";
import { api } from "../api";
const props = defineProps<{ projectId: string; deploymentStatus?: string }>();
const entry = ref<{ status: "ACTIVE" | "WAITING" | "DISABLED"; url: string }>();
const error = ref("");
const loading = ref(false);
let request = 0;
async function load() {
const id = props.projectId;
const current = ++request;
loading.value = true;
error.value = "";
try {
const result = await api<typeof entry.value>(`/projects/${id}/ip-entry`);
if (request === current && props.projectId === id) entry.value = result;
} catch (cause) {
if (request === current && props.projectId === id) error.value = (cause as Error).message;
} finally {
if (request === current) loading.value = false;
}
}
watch([() => props.projectId, () => props.deploymentStatus], load, { immediate: true });
</script>
<template>
<div class="alert info" aria-label="网站 IP 入口">
<strong>网站 IP 入口</strong>
<p v-if="error" role="alert">{{ error }}</p>
<p v-else-if="entry?.status === 'ACTIVE'">
<a class="link" :href="entry.url" target="_blank" rel="noopener noreferrer">{{ entry.url }}</a>
</p>
<p v-else-if="entry?.status === 'WAITING'">管理员已开启。项目发布并启用域名后,入口会显示在这里。</p>
<p v-else-if="entry?.status === 'DISABLED'">管理员尚未为此项目开启。</p>
<p v-else>正在读取 IP 入口…</p>
<button class="link" :disabled="loading" @click="load">刷新 IP 入口</button>
</div>
</template>