167 lines
6.6 KiB
Java
167 lines
6.6 KiB
Java
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();
|
|
}
|
|
}
|