mirror of
https://github.com/qaiu/netdisk-fast-download.git
synced 2026-11-25 06:47:00 +00:00
Merge pull request #297 from qaiu/fix/playground-security
修复演练场密码与脚本权限,准备发布 v0.4.9
This commit is contained in:
15 files changed
+175
-273
No files matched your search
@@ -470,7 +470,7 @@ docker run --rm -v /var/run/docker.sock:/var/run/docker.sock containrrr/watchtow
|
||||
> 注意: netdisk-fast-download.service中的ExecStart的路径改为实际路径
|
||||
```shell
|
||||
cd ~
|
||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.8/netdisk-fast-download-linux-amd64.zip
|
||||
wget -O netdisk-fast-download.zip https://github.com/qaiu/netdisk-fast-download/releases/download/v0.4.9/netdisk-fast-download-linux-amd64.zip
|
||||
unzip netdisk-fast-download.zip
|
||||
cd netdisk-fast-download
|
||||
bash service-install.sh
|
||||
|
||||
@@ -261,39 +261,11 @@ var methods = systemClass.getDeclaredMethods();
|
||||
|
||||
Nashorn引擎默认允许JavaScript访问所有Java类,这是一个严重的安全隐患。以下是建议的安全措施:
|
||||
|
||||
### 1. 使用ClassFilter限制类访问 🔒 必须
|
||||
### 1. 演练场与已注册解析器的类访问限制
|
||||
|
||||
```java
|
||||
import jdk.nashorn.api.scripting.ClassFilter;
|
||||
import jdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
两个入口都通过 `ParserScriptEngine.create()` 创建 Nashorn 引擎。引擎使用 `--no-java`,类过滤器拒绝按名称解析 Java 类。引擎在执行解析器代码前禁用包入口、脚本加载函数和脚本上下文全局变量。解析器仍可使用项目显式注入的分享信息、HTTP、Fetch 和日志接口。
|
||||
|
||||
public class SecurityClassFilter implements ClassFilter {
|
||||
@Override
|
||||
public boolean exposeToScripts(String className) {
|
||||
// 黑名单:禁止访问危险类
|
||||
if (className.startsWith("java.lang.Runtime") ||
|
||||
className.startsWith("java.lang.ProcessBuilder") ||
|
||||
className.startsWith("java.io.File") ||
|
||||
className.startsWith("java.nio.file") ||
|
||||
className.startsWith("java.lang.System") ||
|
||||
className.startsWith("java.lang.Class") ||
|
||||
className.startsWith("java.lang.reflect") ||
|
||||
className.startsWith("java.net.Socket") ||
|
||||
className.startsWith("java.net.URL")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 白名单:只允许特定的类
|
||||
// return className.startsWith("允许的包名");
|
||||
|
||||
return false; // 默认拒绝所有
|
||||
}
|
||||
}
|
||||
|
||||
// 使用ClassFilter创建引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
ScriptEngine engine = factory.getScriptEngine(new SecurityClassFilter());
|
||||
```
|
||||
`ParserScriptEngineTest` 检查受限全局变量的属性,并通过两个执行入口验证普通解析器的行为。
|
||||
|
||||
### 2. 设置执行超时 ⏱️ 强烈推荐
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.WorkerExecutor;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -134,15 +133,7 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
|
||||
*/
|
||||
private ScriptEngine initEngine() {
|
||||
try {
|
||||
// 使用安全的ClassFilter创建Nashorn引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
|
||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
||||
|
||||
if (engine == null) {
|
||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
||||
}
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
this.engine = engine;
|
||||
|
||||
// 注入Java对象到JavaScript环境
|
||||
@@ -151,14 +142,6 @@ public class JsParserExecutor implements IPanTool, AutoCloseable {
|
||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||
engine.put("JavaFetch", fetchBridge);
|
||||
|
||||
// 禁用Java对象访问
|
||||
engine.eval("var Java = undefined;");
|
||||
engine.eval("var JavaImporter = undefined;");
|
||||
engine.eval("var Packages = undefined;");
|
||||
engine.eval("var javax = undefined;");
|
||||
engine.eval("var org = undefined;");
|
||||
engine.eval("var com = undefined;");
|
||||
|
||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||
String fetchRuntime = loadFetchRuntime();
|
||||
if (!fetchRuntime.isEmpty()) {
|
||||
|
||||
@@ -5,7 +5,6 @@ import cn.qaiu.entity.ShareLinkInfo;
|
||||
import io.vertx.core.Future;
|
||||
import io.vertx.core.Promise;
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
import org.openjdk.nashorn.api.scripting.ScriptObjectMirror;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
@@ -111,15 +110,7 @@ public class JsPlaygroundExecutor implements AutoCloseable {
|
||||
*/
|
||||
private ScriptEngine initEngine() {
|
||||
try {
|
||||
// 使用安全的ClassFilter创建Nashorn引擎
|
||||
NashornScriptEngineFactory factory = new NashornScriptEngineFactory();
|
||||
|
||||
// 正确的方法签名: getScriptEngine(String[] args, ClassLoader appLoader, ClassFilter classFilter)
|
||||
ScriptEngine engine = factory.getScriptEngine(new String[0], null, new SecurityClassFilter());
|
||||
|
||||
if (engine == null) {
|
||||
throw new RuntimeException("无法创建JavaScript引擎,请确保Nashorn可用");
|
||||
}
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
this.engine = engine;
|
||||
|
||||
// 注入Java对象到JavaScript环境
|
||||
@@ -128,14 +119,6 @@ public class JsPlaygroundExecutor implements AutoCloseable {
|
||||
engine.put("shareLinkInfo", shareLinkInfoWrapper);
|
||||
engine.put("JavaFetch", fetchBridge);
|
||||
|
||||
// 禁用Java对象访问
|
||||
engine.eval("var Java = undefined;");
|
||||
engine.eval("var JavaImporter = undefined;");
|
||||
engine.eval("var Packages = undefined;");
|
||||
engine.eval("var javax = undefined;");
|
||||
engine.eval("var org = undefined;");
|
||||
engine.eval("var com = undefined;");
|
||||
|
||||
// 加载fetch运行时(Promise和fetch API polyfill)
|
||||
String fetchRuntime = JsParserExecutor.loadFetchRuntime();
|
||||
if (!fetchRuntime.isEmpty()) {
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import org.openjdk.nashorn.api.scripting.NashornScriptEngineFactory;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import javax.script.ScriptException;
|
||||
|
||||
final class ParserScriptEngine {
|
||||
private ParserScriptEngine() {}
|
||||
|
||||
static ScriptEngine create() throws ScriptException {
|
||||
ScriptEngine engine = new NashornScriptEngineFactory().getScriptEngine(
|
||||
new String[]{"--no-java"}, null, new SecurityClassFilter());
|
||||
// Remove host loaders and scripting-context globals before binding the parser APIs.
|
||||
engine.eval("""
|
||||
(function (global) {
|
||||
["load", "loadWithNewGlobal", "exit", "quit", "engine", "context",
|
||||
"Java", "JavaImporter", "Packages", "java", "javax", "javafx", "org",
|
||||
"com", "edu"].forEach(function (name) {
|
||||
Object.defineProperty(global, name, {
|
||||
value: void 0, writable: false, configurable: false
|
||||
});
|
||||
});
|
||||
})(this);
|
||||
""");
|
||||
return engine;
|
||||
}
|
||||
}
|
||||
@@ -1,118 +1,11 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import org.openjdk.nashorn.api.scripting.ClassFilter;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
/**
|
||||
* JavaScript执行器安全类过滤器
|
||||
* 用于限制JavaScript代码可以访问的Java类,防止恶意代码执行危险操作
|
||||
*
|
||||
* @author <a href="https://qaiu.top">QAIU</a>
|
||||
*/
|
||||
/** Scripts work through the supplied parser APIs and may not resolve Java classes by name. */
|
||||
public class SecurityClassFilter implements ClassFilter {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(SecurityClassFilter.class);
|
||||
|
||||
// 危险类黑名单
|
||||
private static final String[] DANGEROUS_CLASSES = {
|
||||
// 系统命令执行
|
||||
"java.lang.Runtime",
|
||||
"java.lang.ProcessBuilder",
|
||||
"java.lang.Process",
|
||||
|
||||
// 文件系统访问
|
||||
"java.io.File",
|
||||
"java.io.FileInputStream",
|
||||
"java.io.FileOutputStream",
|
||||
"java.io.FileReader",
|
||||
"java.io.FileWriter",
|
||||
"java.io.RandomAccessFile",
|
||||
"java.nio.file.Files",
|
||||
"java.nio.file.Paths",
|
||||
"java.nio.file.Path",
|
||||
"java.nio.channels.FileChannel",
|
||||
|
||||
// 系统访问
|
||||
"java.lang.System",
|
||||
"java.lang.SecurityManager",
|
||||
|
||||
// 反射相关
|
||||
"java.lang.Class",
|
||||
"java.lang.reflect.Method",
|
||||
"java.lang.reflect.Field",
|
||||
"java.lang.reflect.Constructor",
|
||||
"java.lang.reflect.AccessibleObject",
|
||||
"java.lang.ClassLoader",
|
||||
|
||||
// 网络访问
|
||||
"java.net.Socket",
|
||||
"java.net.ServerSocket",
|
||||
"java.net.DatagramSocket",
|
||||
"java.net.URL",
|
||||
"java.net.URLConnection",
|
||||
"java.net.HttpURLConnection",
|
||||
"java.net.InetAddress",
|
||||
|
||||
// 线程和并发
|
||||
"java.lang.Thread",
|
||||
"java.lang.ThreadGroup",
|
||||
"java.util.concurrent.Executor",
|
||||
"java.util.concurrent.ExecutorService",
|
||||
|
||||
// 数据库访问
|
||||
"java.sql.Connection",
|
||||
"java.sql.Statement",
|
||||
"java.sql.PreparedStatement",
|
||||
"java.sql.DriverManager",
|
||||
|
||||
// 脚本引擎(防止嵌套执行)
|
||||
"javax.script.ScriptEngine",
|
||||
"javax.script.ScriptEngineManager",
|
||||
|
||||
// JVM控制
|
||||
"java.lang.invoke.MethodHandle",
|
||||
"sun.misc.Unsafe",
|
||||
|
||||
// Nashorn内部类
|
||||
"jdk.nashorn.internal",
|
||||
"jdk.internal",
|
||||
};
|
||||
|
||||
@Override
|
||||
public boolean exposeToScripts(String className) {
|
||||
// 检查是否在黑名单中
|
||||
for (String dangerous : DANGEROUS_CLASSES) {
|
||||
if (className.equals(dangerous) || className.startsWith(dangerous + ".")) {
|
||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险类 - {}", className);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 额外的包级别限制
|
||||
String[] dangerousPackages = {
|
||||
"java.lang.reflect.",
|
||||
"java.io.",
|
||||
"java.nio.",
|
||||
"java.net.",
|
||||
"java.sql.",
|
||||
"javax.script.",
|
||||
"sun.",
|
||||
"jdk.internal.",
|
||||
"jdk.nashorn.internal."
|
||||
};
|
||||
|
||||
for (String pkg : dangerousPackages) {
|
||||
if (className.startsWith(pkg)) {
|
||||
log.warn("🔒 安全拦截: JavaScript尝试访问危险包 - {}", className);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 默认也拒绝(白名单策略更安全,但这里为了兼容性使用黑名单)
|
||||
// 如果要更严格,可以改为 return false
|
||||
log.debug("允许访问类: {}", className);
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,50 +7,7 @@
|
||||
// 全局类型定义,使用JSDoc注释
|
||||
// 这些类型定义将在VSCode中提供代码补全和类型检查
|
||||
|
||||
// ============================================================================
|
||||
// Nashorn Java 互操作全局对象
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Java 全局对象类型定义 (Nashorn引擎提供)
|
||||
* 用于访问Java类型和进行Java互操作
|
||||
* @typedef {Object} JavaGlobal
|
||||
* @property {function(string): any} type - 获取Java类,参数为完整类名(如"java.util.zip.CRC32")
|
||||
* @property {function(any): any} from - 将Java对象转换为JavaScript对象
|
||||
* @property {function(any): any} to - 将JavaScript对象转换为Java对象
|
||||
* @property {function(any): boolean} isType - 检查对象是否为指定Java类型
|
||||
* @property {function(any): boolean} isJavaObject - 检查对象是否为Java对象
|
||||
* @property {function(any): boolean} isJavaMethod - 检查对象是否为Java方法
|
||||
* @property {function(any): boolean} isJavaFunction - 检查对象是否为Java函数
|
||||
*/
|
||||
|
||||
/**
|
||||
* Java 全局对象 (Nashorn引擎提供)
|
||||
* @global
|
||||
* @type {JavaGlobal}
|
||||
*/
|
||||
var Java;
|
||||
|
||||
/**
|
||||
* java 命名空间对象类型定义 (Nashorn引擎提供)
|
||||
* 用于直接访问Java包和类
|
||||
* @typedef {Object} JavaNamespace
|
||||
* @property {Object} lang - java.lang 包
|
||||
* @property {Object} util - java.util 包
|
||||
* @property {Object} io - java.io 包
|
||||
* @property {Object} net - java.net 包
|
||||
* @property {Object} math - java.math 包
|
||||
* @property {Object} security - java.security 包
|
||||
* @property {Object} text - java.text 包
|
||||
* @property {Object} time - java.time 包
|
||||
*/
|
||||
|
||||
/**
|
||||
* java 命名空间对象 (Nashorn引擎提供)
|
||||
* @global
|
||||
* @type {JavaNamespace}
|
||||
*/
|
||||
var java;
|
||||
// 解析脚本通过项目注入的接口访问分享信息、HTTP 和日志。
|
||||
|
||||
/**
|
||||
* @typedef {Object} ShareLinkInfo
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package cn.qaiu.parser.customjs;
|
||||
|
||||
import cn.qaiu.WebClientVertxInit;
|
||||
import cn.qaiu.entity.ShareLinkInfo;
|
||||
import cn.qaiu.parser.custom.CustomParserConfig;
|
||||
import io.vertx.core.Vertx;
|
||||
import org.junit.Test;
|
||||
|
||||
import javax.script.ScriptEngine;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class ParserScriptEngineTest {
|
||||
@Test
|
||||
public void disablesClassLookupAndHostLoadersBeforeRunningScripts() throws Exception {
|
||||
SecurityClassFilter filter = new SecurityClassFilter();
|
||||
assertFalse(filter.exposeToScripts("java.lang.String"));
|
||||
assertFalse(filter.exposeToScripts("java.util.Formatter"));
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
for (String name : new String[]{"Java", "JavaImporter", "Packages", "java", "javax",
|
||||
"org", "com", "edu", "javafx", "load", "loadWithNewGlobal", "engine", "context", "exit", "quit"}) {
|
||||
assertEquals(name, "undefined", engine.eval("typeof " + name));
|
||||
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').writable"));
|
||||
assertEquals(name, Boolean.FALSE, engine.eval("Object.getOwnPropertyDescriptor(this, '" + name + "').configurable"));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void ordinaryScriptsCanStillCallAnInjectedParserApi() throws Exception {
|
||||
ScriptEngine engine = ParserScriptEngine.create();
|
||||
engine.put("logger", new JsPlaygroundLogger());
|
||||
assertEquals("ok", engine.eval("logger.info('parser test'); JSON.parse('{\"result\":\"ok\"}').result"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void bothExecutorsPreserveParserApisAndDisableHostGlobals() throws Exception {
|
||||
String script = """
|
||||
function parse(info, http, logger) {
|
||||
logger.info("parser test");
|
||||
return [info.getShareKey(), typeof fetch, typeof java, typeof loadWithNewGlobal].join("|");
|
||||
}
|
||||
""";
|
||||
String expected = "sample|function|undefined|undefined";
|
||||
ShareLinkInfo info = ShareLinkInfo.newBuilder().shareKey("sample").build();
|
||||
CustomParserConfig config = CustomParserConfig.builder()
|
||||
.type("sandbox_test").displayName("Sandbox test").isJsParser(true).jsCode(script).build();
|
||||
Vertx vertx = Vertx.vertx();
|
||||
try {
|
||||
WebClientVertxInit.init(vertx);
|
||||
try (JsPlaygroundExecutor playground = new JsPlaygroundExecutor(info, script);
|
||||
JsParserExecutor registered = new JsParserExecutor(info, config)) {
|
||||
assertEquals(expected, playground.executeParseAsync().toCompletionStage().toCompletableFuture()
|
||||
.get(10, TimeUnit.SECONDS));
|
||||
assertEquals(expected, registered.parse().toCompletionStage().toCompletableFuture()
|
||||
.get(10, TimeUnit.SECONDS));
|
||||
}
|
||||
} finally {
|
||||
vertx.close().toCompletionStage().toCompletableFuture().get(10, TimeUnit.SECONDS);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@
|
||||
</modules>
|
||||
|
||||
<properties>
|
||||
<revision>0.4.8</revision>
|
||||
<revision>0.4.9</revision>
|
||||
<java.version>17</java.version>
|
||||
<maven.compiler.source>17</maven.compiler.source>
|
||||
<maven.compiler.target>17</maven.compiler.target>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "nfd-web",
|
||||
"version": "0.4.8",
|
||||
"version": "0.4.9",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"serve": "vue-cli-service serve",
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
<el-icon :size="50"><WarningFilled /></el-icon>
|
||||
</div>
|
||||
<div class="auth-title">演练场功能已禁用</div>
|
||||
<div class="auth-subtitle">请联系管理员启用演练场功能</div>
|
||||
<div class="auth-subtitle">请联系管理员检查演练场开关与服务日志。私有模式需要先设置实例专属的访问密码。</div>
|
||||
<el-button type="primary" size="large" @click="goHome" class="auth-button">
|
||||
<span>返回首页</span>
|
||||
</el-button>
|
||||
|
||||
@@ -6,15 +6,16 @@ JS解析器演练场现在支持密码保护功能,可以通过配置文件控
|
||||
|
||||
## 配置说明
|
||||
|
||||
在 `web-service/src/main/resources/app-dev.yml` 文件中添加以下配置:
|
||||
编辑当前启用的配置文件。发行包默认使用 `resources/app-dev.yml`。
|
||||
|
||||
```yaml
|
||||
# JS演练场配置
|
||||
playground:
|
||||
enabled: false
|
||||
# 公开模式,默认false需要密码访问,设为true则无需密码
|
||||
public: false
|
||||
# 访问密码,建议修改默认密码!
|
||||
password: 'nfd_playground_2024'
|
||||
# 私有模式启用前须设置实例专属密码
|
||||
password: ''
|
||||
```
|
||||
|
||||
### 配置项说明
|
||||
@@ -24,8 +25,7 @@ playground:
|
||||
- `true`: 公开访问,无需密码
|
||||
|
||||
- `password`: 字符串,访问密码
|
||||
- 默认密码:`nfd_playground_2024`
|
||||
- **强烈建议在生产环境中修改为自定义密码!**
|
||||
- 无默认值。私有模式缺少密码、密码为空白或沿用旧版公开密码时,演练场保持关闭。
|
||||
|
||||
## 功能特点
|
||||
|
||||
@@ -64,24 +64,14 @@ playground:
|
||||
|
||||
⚠️ **重要安全提示:**
|
||||
|
||||
1. **修改默认密码**:在生产环境中,务必修改 `playground.password` 为自定义的强密码
|
||||
1. **设置专属密码**:启用私有模式前,请设置 `playground.password` 为自定义的强密码
|
||||
2. **使用密码保护**:建议保持 `public: false`,避免未授权访问
|
||||
3. **定期更换密码**:定期更换访问密码以提高安全性
|
||||
4. **配置文件保护**:确保配置文件的访问权限受到保护
|
||||
|
||||
## 系统启动提示
|
||||
|
||||
当系统启动时,会在日志中显示当前配置:
|
||||
|
||||
```
|
||||
INFO - Playground配置已加载: public=false, password=已设置
|
||||
```
|
||||
|
||||
如果使用默认密码,会显示警告:
|
||||
|
||||
```
|
||||
WARN - ⚠️ 警告:您正在使用默认密码,建议修改配置文件中的 playground.password 以确保安全!
|
||||
```
|
||||
配置文件及启用开关 `NFD_PLAYGROUND_ENABLED` 生效后,服务会检查私有模式密码。若检查失败,日志会提示配置 `playground.password` 并重启服务,其他功能继续启动。显式选择 `public: true` 会允许免密码访问管理接口。
|
||||
|
||||
## API 端点
|
||||
|
||||
@@ -145,9 +135,9 @@ A: 修改配置文件中的 `playground.password` 为新密码,然后重启服
|
||||
|
||||
A: 当前版本密码以明文形式存储在配置文件中,请确保配置文件的访问权限受到保护
|
||||
|
||||
### Q: Session 有效期多久?
|
||||
### 登录令牌有效期多久?
|
||||
|
||||
A: Session 由 Vert.x 管理,默认在浏览器会话期间有效,关闭浏览器后失效
|
||||
私有模式的令牌自签发起最多有效 24 小时。服务重启或重新加载演练场配置会使已签发的令牌失效。
|
||||
|
||||
## 后续版本计划
|
||||
|
||||
@@ -156,7 +146,6 @@ A: Session 由 Vert.x 管理,默认在浏览器会话期间有效,关闭浏
|
||||
- [ ] 支持环境变量配置密码
|
||||
- [ ] 支持加密存储密码
|
||||
- [ ] 支持多用户账户系统
|
||||
- [ ] 支持 Token 认证方式
|
||||
- [ ] 支持 Session 超时配置
|
||||
|
||||
## 相关文档
|
||||
|
||||
@@ -26,7 +26,7 @@ public class PlaygroundConfig {
|
||||
/**
|
||||
* 单例实例
|
||||
*/
|
||||
private static PlaygroundConfig instance;
|
||||
private static volatile PlaygroundConfig instance = new PlaygroundConfig();
|
||||
|
||||
/**
|
||||
* 已颁发的认证Token及其创建时间
|
||||
@@ -47,9 +47,8 @@ public class PlaygroundConfig {
|
||||
|
||||
/**
|
||||
* 访问密码
|
||||
* 默认密码:nfd_playground_2024
|
||||
*/
|
||||
private String password = "nfd_playground_2024";
|
||||
private String password;
|
||||
|
||||
/**
|
||||
* 私有构造函数
|
||||
@@ -117,13 +116,6 @@ public class PlaygroundConfig {
|
||||
* 获取单例实例
|
||||
*/
|
||||
public static PlaygroundConfig getInstance() {
|
||||
if (instance == null) {
|
||||
synchronized (PlaygroundConfig.class) {
|
||||
if (instance == null) {
|
||||
instance = new PlaygroundConfig();
|
||||
}
|
||||
}
|
||||
}
|
||||
return instance;
|
||||
}
|
||||
|
||||
@@ -131,23 +123,13 @@ public class PlaygroundConfig {
|
||||
* 从JsonObject加载配置
|
||||
*/
|
||||
public static void loadFromJson(JsonObject config) {
|
||||
PlaygroundConfig cfg = getInstance();
|
||||
if (config != null && config.containsKey("playground")) {
|
||||
JsonObject playgroundConfig = config.getJsonObject("playground");
|
||||
cfg.enabled = playgroundConfig.getBoolean("enabled", false);
|
||||
cfg.isPublic = playgroundConfig.getBoolean("public", false);
|
||||
cfg.password = playgroundConfig.getString("password", "nfd_playground_2024");
|
||||
|
||||
log.info("Playground配置已加载: enabled={}, public={}, password={}",
|
||||
cfg.enabled, cfg.isPublic, cfg.isPublic ? "N/A" : "已设置");
|
||||
|
||||
if (!cfg.enabled) {
|
||||
log.info("演练场功能已禁用");
|
||||
} else if (!cfg.isPublic && "nfd_playground_2024".equals(cfg.password)) {
|
||||
log.warn("⚠️ 警告:您正在使用默认密码,建议修改配置文件中的 playground.password 以确保安全!");
|
||||
PlaygroundConfig cfg = new PlaygroundConfig();
|
||||
if (config != null && config.getValue("playground") instanceof JsonObject playground) {
|
||||
cfg.enabled = playground.getBoolean("enabled", false);
|
||||
cfg.isPublic = playground.getBoolean("public", false);
|
||||
if (playground.getValue("password") instanceof String configuredPassword) {
|
||||
cfg.password = configuredPassword;
|
||||
}
|
||||
} else {
|
||||
log.info("未找到playground配置,使用默认值: enabled=false, public=false");
|
||||
}
|
||||
String enabledOverride = System.getProperty("NFD_PLAYGROUND_ENABLED");
|
||||
if (enabledOverride == null || enabledOverride.isBlank()) {
|
||||
@@ -155,7 +137,16 @@ public class PlaygroundConfig {
|
||||
}
|
||||
if (enabledOverride != null && !enabledOverride.isBlank()) {
|
||||
cfg.enabled = Boolean.parseBoolean(enabledOverride);
|
||||
log.info("Playground enabled 已被 NFD_PLAYGROUND_ENABLED 覆盖为 {}", cfg.enabled);
|
||||
}
|
||||
|
||||
// Validate after all overrides so enabling via the environment follows the same rules.
|
||||
if (cfg.enabled && !cfg.isPublic && (cfg.password == null || cfg.password.isBlank()
|
||||
|| "nfd_playground_2024".equals(cfg.password.strip()))) {
|
||||
cfg.enabled = false;
|
||||
log.warn("演练场已禁用:请在 app-dev.yml 中设置实例专属的 playground.password,替换空值或旧版默认密码,然后重启服务。");
|
||||
} else {
|
||||
log.info("演练场配置已加载:enabled={}, public={}", cfg.enabled, cfg.isPublic);
|
||||
}
|
||||
instance = cfg;
|
||||
}
|
||||
}
|
||||
@@ -20,8 +20,8 @@ playground:
|
||||
enabled: false
|
||||
# 公开模式,默认false需要密码访问,设为true则无需密码
|
||||
public: false
|
||||
# 访问密码,建议修改默认密码!
|
||||
password: 'nfd_playground_2024'
|
||||
# 私有模式启用前请填写实例专属密码;留空或沿用旧版默认密码将禁用演练场。
|
||||
password: ''
|
||||
|
||||
# vertx核心线程配置(一般无需改的), 为0表示eventLoopPoolSize将会采用默认配置(CPU核心*2) workerPoolSize将会采用默认20
|
||||
vertx:
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
package cn.qaiu.lz.web.config;
|
||||
|
||||
import io.vertx.core.json.JsonObject;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class PlaygroundPasswordTest {
|
||||
@Test
|
||||
public void validatesPrivateModeAfterTheEnableOverride() {
|
||||
String key = "NFD_PLAYGROUND_ENABLED";
|
||||
String previous = System.getProperty(key);
|
||||
try {
|
||||
System.setProperty(key, "true");
|
||||
JsonObject playground = new JsonObject().put("enabled", false);
|
||||
JsonObject config = new JsonObject().put("playground", playground);
|
||||
for (String password : new String[]{null, "", " ", "nfd_playground_2024"}) {
|
||||
playground.put("password", password);
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
}
|
||||
playground.put("password", "instance-specific-test-value");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertTrue(PlaygroundConfig.getInstance().isEnabled());
|
||||
assertEquals(playground.getString("password"), PlaygroundConfig.getInstance().getPassword());
|
||||
String token = PlaygroundConfig.getInstance().generateToken();
|
||||
|
||||
PlaygroundConfig.loadFromJson(new JsonObject());
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
assertFalse(PlaygroundConfig.getInstance().validateToken(token));
|
||||
|
||||
playground.put("public", true).remove("password");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertTrue(PlaygroundConfig.getInstance().isEnabled());
|
||||
System.setProperty(key, "false");
|
||||
PlaygroundConfig.loadFromJson(config);
|
||||
assertFalse(PlaygroundConfig.getInstance().isEnabled());
|
||||
} finally {
|
||||
if (previous == null) System.clearProperty(key);
|
||||
else System.setProperty(key, previous);
|
||||
PlaygroundConfig.loadFromJson(new JsonObject());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user