git clone功能
网站登录 → 创建项目 Git Token → clone → 本地修改、commit → push main → 网站工作区刷新后显示最新内容 → 网站手动发布到社区
This commit is contained in:
+136
@@ -0,0 +1,136 @@
|
||||
package com.linkerbot.vibemake.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.linkerbot.vibemake.common.BusinessException;
|
||||
import com.linkerbot.vibemake.service.git.*;
|
||||
import com.linkerbot.vibemake.service.state.ClientAddresses;
|
||||
|
||||
import jakarta.servlet.*;
|
||||
import jakarta.servlet.http.*;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.regex.*;
|
||||
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class GitAuthenticationFilter extends OncePerRequestFilter {
|
||||
private static final org.slf4j.Logger log =
|
||||
org.slf4j.LoggerFactory.getLogger(GitAuthenticationFilter.class);
|
||||
public static final String ACCESS = GitAuthenticationFilter.class.getName() + ".access";
|
||||
public static final String ACTION = GitAuthenticationFilter.class.getName() + ".action";
|
||||
private static final Pattern PATH =
|
||||
Pattern.compile("/git/projects/([A-Za-z0-9]{1,32})\\.git/(.+)");
|
||||
private final GitTokens tokens;
|
||||
private final LfsGateway lfs;
|
||||
private final GitLimits limits;
|
||||
private final ClientAddresses addresses;
|
||||
private final ObjectMapper json;
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request, HttpServletResponse response, FilterChain chain)
|
||||
throws IOException, ServletException {
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
String ip = addresses.resolve(request);
|
||||
try {
|
||||
tokens.enabled();
|
||||
limits.authenticationAllowed(ip);
|
||||
Matcher matcher =
|
||||
PATH.matcher(
|
||||
request.getRequestURI().substring(request.getContextPath().length()));
|
||||
if (!matcher.matches()) throw BusinessException.notFound();
|
||||
String code = matcher.group(1);
|
||||
String endpoint = matcher.group(2);
|
||||
String authorization = request.getHeader("Authorization");
|
||||
GitAccess access;
|
||||
if (endpoint.startsWith("info/lfs/actions/")) {
|
||||
if (authorization == null || !authorization.startsWith("Bearer "))
|
||||
throw GitTokens.unauthorized();
|
||||
LfsGateway.Action action =
|
||||
lfs.authenticate(
|
||||
endpoint.substring("info/lfs/actions/".length()),
|
||||
code,
|
||||
authorization.substring(7),
|
||||
request.getMethod());
|
||||
access = action.access();
|
||||
request.setAttribute(ACTION, action);
|
||||
} else {
|
||||
if (authorization == null
|
||||
|| !authorization.startsWith("Basic ")
|
||||
|| authorization.length() > 2048) throw GitTokens.unauthorized();
|
||||
String decoded;
|
||||
try {
|
||||
decoded =
|
||||
new String(
|
||||
Base64.getDecoder().decode(authorization.substring(6)),
|
||||
StandardCharsets.UTF_8);
|
||||
} catch (IllegalArgumentException error) {
|
||||
throw GitTokens.unauthorized();
|
||||
}
|
||||
int separator = decoded.indexOf(':');
|
||||
if (separator < 1) throw GitTokens.unauthorized();
|
||||
access =
|
||||
tokens.authenticate(
|
||||
decoded.substring(0, separator),
|
||||
decoded.substring(separator + 1),
|
||||
code);
|
||||
}
|
||||
limits.request(access, endpoint.startsWith("info/lfs/"));
|
||||
request.setAttribute(ACCESS, access);
|
||||
} catch (BusinessException error) {
|
||||
if (request.getHeader("Authorization") != null)
|
||||
log.warn("Git 认证或限流拒绝 code={} status={}", error.code(), error.status());
|
||||
// Git 客户端的首次无凭据请求用于协商 Basic challenge,不计为密码认证失败。
|
||||
if (error.status() == 401 && request.getHeader("Authorization") != null)
|
||||
limits.authenticationFailed(ip);
|
||||
failure(request, response, json, error);
|
||||
return;
|
||||
} catch (RuntimeException error) {
|
||||
log.warn("Git 认证服务异常 errorType={}", error.getClass().getSimpleName());
|
||||
failure(
|
||||
request,
|
||||
response,
|
||||
json,
|
||||
new BusinessException(503, "GIT_UNAVAILABLE", "Git 鉴权服务暂不可用"));
|
||||
return;
|
||||
}
|
||||
chain.doFilter(request, response);
|
||||
}
|
||||
|
||||
public static void failure(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
ObjectMapper json,
|
||||
BusinessException error)
|
||||
throws IOException {
|
||||
if (response.isCommitted()) {
|
||||
response.getOutputStream().close();
|
||||
return;
|
||||
}
|
||||
response.resetBuffer();
|
||||
response.setHeader("Content-Length", null);
|
||||
response.setStatus(error.status());
|
||||
response.setHeader("Cache-Control", "no-store");
|
||||
if (error.status() == 401)
|
||||
response.setHeader(
|
||||
"WWW-Authenticate", "Basic realm=\"Vibemake Git\", charset=\"UTF-8\"");
|
||||
if (error.status() == 429) response.setHeader("Retry-After", "60");
|
||||
if (request.getRequestURI().contains("/info/lfs/")) {
|
||||
response.setContentType(LfsGateway.MEDIA + ";charset=UTF-8");
|
||||
json.writeValue(response.getOutputStream(), Map.of("message", error.getMessage()));
|
||||
} else {
|
||||
response.setContentType("text/plain;charset=UTF-8");
|
||||
response.getOutputStream()
|
||||
.write(
|
||||
("error: " + error.getMessage() + "\n")
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package com.linkerbot.vibemake.security;
|
||||
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.*;
|
||||
import org.springframework.core.annotation.Order;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
|
||||
@Configuration
|
||||
public class GitSecurityConfiguration {
|
||||
@Bean
|
||||
public FilterRegistrationBean<GitAuthenticationFilter> disableGitServletRegistration(
|
||||
GitAuthenticationFilter filter) {
|
||||
FilterRegistrationBean<GitAuthenticationFilter> registration =
|
||||
new FilterRegistrationBean<>(filter);
|
||||
registration.setEnabled(false);
|
||||
return registration;
|
||||
}
|
||||
|
||||
@Bean
|
||||
@Order(1)
|
||||
public SecurityFilterChain gitSecurityFilterChain(
|
||||
HttpSecurity http, GitAuthenticationFilter filter) throws Exception {
|
||||
return http.securityMatcher("/git/**")
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.cors(cors -> cors.disable())
|
||||
.sessionManagement(
|
||||
session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.requestCache(cache -> cache.disable())
|
||||
.formLogin(form -> form.disable())
|
||||
.httpBasic(basic -> basic.disable())
|
||||
.logout(logout -> logout.disable())
|
||||
// 专用过滤器已完成每请求鉴权,不创建可被普通 Bearer 链复用的登录状态。
|
||||
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
|
||||
.addFilterBefore(filter, UsernamePasswordAuthenticationFilter.class)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user