Add persistent admin password login and deploy verified release

This commit is contained in:
tongtong committed 2026-11-26 10:24:05 +08:00
1 parent beeca041ef
commit bf424102c8
12 files changed
+319 -35

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
#!/bin/bash
set -euo pipefail
cd /opt/vibe-launcher
STAGE=$(mktemp -d /opt/vibe-launcher/deploy8.XXXXXXXX)
mkdir -p "$STAGE/target"
cp target/vibe-launcher-backend.jar "$STAGE/target/"
cp Dockerfile "$STAGE/"
cp -p auth.env "$STAGE/auth.env.backup"
python3 - <<'PY'
from pathlib import Path
import secrets
p = Path('/opt/vibe-launcher/auth.env')
s = p.read_text()
if 'ADMIN_USERNAME=' not in s: s += '\nADMIN_USERNAME=admin\n'
if 'ADMIN_PASSWORD=' not in s: s += 'ADMIN_PASSWORD=' + secrets.token_urlsafe(24) + '\n'
p.write_text(s)
p.chmod(0o600)
PY
kubectl -n vibe-launcher create secret generic vibe-launcher-auth --from-env-file=auth.env --dry-run=client -o yaml | kubectl apply -f -
docker build -t docker.io/library/vibe-launcher-backend:1.1.0-deploy8 "$STAGE"
docker save docker.io/library/vibe-launcher-backend:1.1.0-deploy8 | k3s ctr images import -
kubectl apply -f deploy.yaml
if ! kubectl -n vibe-launcher rollout status deploy/vibe-launcher-backend --timeout=180s; then
kubectl -n vibe-launcher set image deploy/vibe-launcher-backend server=docker.io/library/vibe-launcher-backend:1.1.0-deploy7
exit 1
fi
bash verify.sh
python3 verify-login.py
+1 -1
View File
@@ -26,7 +26,7 @@ spec:
spec:
containers:
- name: server
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy7
image: docker.io/library/vibe-launcher-backend:1.1.0-deploy8
imagePullPolicy: IfNotPresent
ports:
- name: http
+40
View File
@@ -0,0 +1,40 @@
#!/usr/bin/env python3
"""Verify deployed password login without logging credentials or changing layouts."""
import http.cookiejar
import json
import os
from pathlib import Path
import urllib.request
import urllib.error
base = os.environ.get('BASE', 'https://api.ttstd.com/launcher').rstrip('/')
auth = dict(line.split('=', 1) for line in Path(os.environ.get('AUTH_FILE', '/opt/vibe-launcher/auth.env')).read_text().splitlines() if '=' in line and not line.startswith('#'))
jar = http.cookiejar.CookieJar()
client = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
def request(path, expected=200, body=None, method=None, csrf=True):
headers = {'Content-Type': 'application/json'}
if csrf: headers['X-Launcher-Request'] = '1'
req = urllib.request.Request(base + path, data=json.dumps(body).encode() if body is not None else None, headers=headers, method=method)
try: response = client.open(req, timeout=15)
except urllib.error.HTTPError as error: response = error
assert response.code == expected, (path, response.code, expected)
data = response.read()
print(path, response.code)
return response.headers, data
request('/api/auth/session', 401)
request('/api/auth/login', 403, {}, csrf=False)
request('/api/auth/login', 401, {'username': auth['ADMIN_USERNAME'], 'password': 'invalid'})
headers, _ = request('/api/auth/login', body={'username': auth['ADMIN_USERNAME'], 'password': auth['ADMIN_PASSWORD']})
for attribute in ['HttpOnly', 'Secure', 'SameSite=Strict', 'Max-Age=2592000']:
assert attribute in headers['Set-Cookie'], attribute
request('/api/auth/session')
request('/api/admin/layout')
request('/api/admin/widget-providers')
request('/api/admin/history')
request('/api/admin/layout', 403, {}, method='PUT', csrf=False)
request('/api/admin/layout', 428, {}, method='PUT')
request('/api/layout', 401) # browser admin login must not authorize device API
request('/api/auth/logout', body={})
request('/api/auth/session', 401)
request('/api/admin/layout', 401)
print('Password login, cookie flags, authenticated reads, CSRF, device isolation and logout verified.')
@@ -0,0 +1,106 @@
package com.ttstd.launcher;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.web.bind.annotation.*;
@RestController
class BrowserAuth {
private static final String COOKIE = "launcher_login";
private static final long LIFETIME = 30L * 24 * 60 * 60;
private long failureWindow;
private int failures;
private final String username;
private final byte[] password;
private final byte[] key;
private final boolean enabled;
private final boolean secure;
BrowserAuth(@Value("${launcher.admin-username:admin}") String username,
@Value("${launcher.admin-password:}") String password,
@Value("${launcher.cookie-secure:true}") boolean secure) {
if (!password.isEmpty() && password.length() < 12)
throw new IllegalArgumentException("ADMIN_PASSWORD 至少需要 12 个字符");
this.username = username;
this.password = RequestPolicy.sha256(password);
this.key = RequestPolicy.sha256(username + "\n" + password);
this.enabled = !password.isEmpty();
this.secure = secure;
}
void checkMutation(HttpServletRequest request) {
if (!request.getMethod().equals("GET") && !"1".equals(request.getHeader("X-Launcher-Request")))
throw new ApiError(403, "请求校验失败,请刷新页面");
}
@PostMapping("/api/auth/login")
synchronized Map<String, Object> login(@RequestBody Map<String, String> body, HttpServletRequest request, HttpServletResponse response) {
checkMutation(request);
long now = Instant.now().getEpochSecond();
if (now - failureWindow >= 60) { failureWindow = now; failures = 0; }
if (failures >= 20) throw new ApiError(429, "登录尝试过多,请稍后再试");
if (!enabled || !MessageDigest.isEqual(RequestPolicy.sha256(body.getOrDefault("username", "")), RequestPolicy.sha256(username))
|| !MessageDigest.isEqual(RequestPolicy.sha256(body.getOrDefault("password", "")), password))
{
failures++;
throw new ApiError(401, "账号或密码错误");
}
failures = 0;
String payload = (Instant.now().getEpochSecond() + LIFETIME) + "." + java.util.UUID.randomUUID();
cookie(response, payload + "." + sign(payload), LIFETIME);
return Map.of("username", username);
}
@GetMapping("/api/auth/session")
Map<String, Object> session(HttpServletRequest request) {
if (!authenticated(request)) throw new ApiError(401, "请先登录");
return Map.of("username", username);
}
@PostMapping("/api/auth/logout")
Map<String, Object> logout(HttpServletRequest request, HttpServletResponse response) {
checkMutation(request);
cookie(response, "", 0);
return Map.of("ok", true);
}
boolean authenticated(HttpServletRequest request) {
if (!enabled || request.getCookies() == null) return false;
for (var cookie : request.getCookies()) {
if (!COOKIE.equals(cookie.getName())) continue;
String value = cookie.getValue();
int split = value.lastIndexOf('.');
if (split < 0) return false;
String payload = value.substring(0, split);
try {
long expires = Long.parseLong(payload.substring(0, payload.indexOf('.')));
return expires > Instant.now().getEpochSecond() && MessageDigest.isEqual(
sign(payload).getBytes(StandardCharsets.UTF_8), value.substring(split + 1).getBytes(StandardCharsets.UTF_8));
} catch (RuntimeException invalid) { return false; }
}
return false;
}
private String sign(String payload) {
try {
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(key, "HmacSHA256"));
return Base64.getUrlEncoder().withoutPadding().encodeToString(mac.doFinal(payload.getBytes(StandardCharsets.UTF_8)));
} catch (java.security.GeneralSecurityException error) { throw new IllegalStateException(error); }
}
private void cookie(HttpServletResponse response, String value, long age) {
response.addHeader(HttpHeaders.SET_COOKIE, ResponseCookie.from(COOKIE, value).httpOnly(true)
.secure(secure).sameSite("Strict").path("/").maxAge(age).build().toString());
}
}
@@ -14,16 +14,18 @@ import org.springframework.web.filter.OncePerRequestFilter;
@Component
class RequestPolicy extends OncePerRequestFilter {
@org.springframework.beans.factory.annotation.Autowired
private BrowserAuth browserAuth;
private final byte[] admin;
private final byte[] device;
RequestPolicy(@Value("${launcher.admin-token}") String adminToken,
@Value("${launcher.device-token}") String deviceToken) {
if (!adminToken.matches("[!-~]{24,256}") || !deviceToken.matches("[!-~]{24,256}")
if ((!adminToken.isEmpty() && !adminToken.matches("[!-~]{24,256}")) || !deviceToken.matches("[!-~]{24,256}")
|| adminToken.equals(deviceToken)) {
throw new IllegalArgumentException("请配置两组不同的 ADMIN_TOKEN 和 DEVICE_TOKEN,各使用 24–256 位可打印 ASCII 字符");
throw new IllegalArgumentException("DEVICE_TOKEN 需要 24–256 位可打印 ASCII 字符;可选 ADMIN_TOKEN 需符合相同要求且与设备令牌不同");
}
this.admin = sha256("Bearer " + adminToken);
this.admin = sha256(adminToken.isEmpty() ? java.util.UUID.randomUUID().toString() : "Bearer " + adminToken);
this.device = sha256("Bearer " + deviceToken);
}
@@ -39,6 +41,10 @@ class RequestPolicy extends OncePerRequestFilter {
}
void requireAdmin(HttpServletRequest request, HttpServletResponse response) {
if (browserAuth != null && browserAuth.authenticated(request)) {
browserAuth.checkMutation(request);
return;
}
require(request, response, admin);
}
@@ -7,3 +7,7 @@ spring.mvc.throw-exception-if-no-handler-found=true
launcher.admin-token=${ADMIN_TOKEN:}
launcher.device-token=${DEVICE_TOKEN:}
launcher.database=${LAYOUT_DB:backend/data/layouts.sqlite}
launcher.admin-username=${ADMIN_USERNAME:admin}
launcher.admin-password=${ADMIN_PASSWORD:}
launcher.cookie-secure=${COOKIE_SECURE:true}
@@ -0,0 +1,44 @@
package com.ttstd.launcher;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import jakarta.servlet.http.Cookie;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.*;
class BrowserAuthTest {
@Test void persistentLoginAndPasswordChange() {
var auth = new BrowserAuth("admin", "test-password-123456", true);
var req = new MockHttpServletRequest("POST", "/api/auth/login");
var res = new MockHttpServletResponse();
assertThrows(ApiError.class, () -> auth.login(Map.of(), req, res));
req.addHeader("X-Launcher-Request", "1");
assertThrows(ApiError.class, () -> auth.login(Map.of("password", "wrong"), req, res));
auth.login(Map.of("username", "admin", "password", "test-password-123456"), req, res);
String header = res.getHeader("Set-Cookie");
assertTrue(header.contains("HttpOnly"));
assertTrue(header.contains("Secure"));
assertTrue(header.contains("SameSite=Strict"));
assertTrue(header.contains("Max-Age=2592000"));
var cookie = new Cookie("launcher_login", header.split(";", 2)[0].split("=", 2)[1]);
req.setCookies(cookie);
assertTrue(auth.authenticated(req));
assertTrue(new BrowserAuth("admin", "test-password-123456", true).authenticated(req));
assertFalse(new BrowserAuth("admin", "changed-password-123456", true).authenticated(req));
var policy = new RequestPolicy("", "test-device-token-123456789");
org.springframework.test.util.ReflectionTestUtils.setField(policy, "browserAuth", auth);
req.setMethod("GET");
policy.requireAdmin(req, new MockHttpServletResponse());
var write = new MockHttpServletRequest("PUT", "/api/admin/layout");
write.setCookies(cookie);
assertThrows(ApiError.class, () -> policy.requireAdmin(write, new MockHttpServletResponse()));
write.addHeader("X-Launcher-Request", "1");
policy.requireAdmin(write, new MockHttpServletResponse());
assertThrows(ApiError.class, () -> policy.requireDevice(req, new MockHttpServletResponse()));
req.setMethod("POST");
cookie.setValue(cookie.getValue() + "tampered");
assertFalse(auth.authenticated(req));
var out = new MockHttpServletResponse();
auth.logout(req, out);
assertTrue(out.getHeader("Set-Cookie").contains("Max-Age=0"));
}
}