在 Spring Authorization Server 中嵌入 Groovy 脚本

解读

国内主流企业把 Spring Authorization Server(简称 SAS)作为 OAuth2 授权中心时,常遇到“策略热调整”需求:不同租户、不同时间段、甚至不同渠道都要动态切换授权规则。硬编码 Java 策略每次上线都要走全量灰度、封板、出包、审批的漫长流程,无法满足业务“今天提需求、明天就生效”的节奏。于是面试官抛出“在 SAS 里嵌入 Groovy 脚本”这一题,考察候选人能否在不破坏 SAS 安全模型的前提下,把 Groovy 的运行时元编程能力与 Spring 的官方扩展点结合起来,实现毫秒级热加载、租户级隔离、沙箱级防护的动态授权方案。答不到“如何防注入、如何降权、如何回滚”这三点,基本会被判为“只写过 Demo”。

知识点

  1. SAS 核心扩展点:OAuth2TokenCustomizer<JwtEncodingContext>、AuthenticationProvider、AuthorizationServerSettings
  2. Groovy 集成方式:GroovyClassLoader 与 Spring ScriptFactory 的优劣对比;CompilationCustomizer(SecureASTCustomizer、SandboxTransformer)做字节码级拦截
  3. 热加载机制:GroovyScriptEngine + FileSystemWatcher 实现毫秒级感知;配合 Spring @RefreshScope 避免Bean 定义缓存导致脚本不生效
  4. 安全沙箱:GroovyInterceptable + GroovySystem.exit() 黑名单;Java SecurityManager 在 JDK17 被标记为 deprecated 后的替代方案——自定义 SecurityContext + ByteBuddy Agent
  5. 租户隔离:ThreadLocalTenantHolder 把租户 ID 带到脚本上下文;GroovyShell 的 Binding 只暴露只读变量
  6. 回滚与审计:版本化脚本(Git + JdbcScriptRepository);ScriptExecutionListener 记录耗时、异常、返回结果到ELK;CircuitBreaker 脚本异常三次自动降级到兜底 Java 策略
  7. 性能陷阱:GroovyClassLoader 每执行一次 new 一个类导致Metaspace OOM;正确姿势是全局缓存 CompiledScript,用 ConcurrentHashMap<Class<?>, SoftReference> 做类缓存
  8. 国产合规:脚本内容需经过静态敏感词扫描(基于DFA 算法),满足**网信办 2017 年《互联网安全监督检查规定》**对“用户生成内容”的审查要求

答案

  1. 引入依赖
    仅保留最小 Groovy 模块,防止开发者顺手写 GroovyShell.evaluate() 造成漏洞:

    implementation 'org.apache.groovy:groovy:4.0.14'
    implementation 'org.apache.groovy:groovy-sandbox:4.0.14'
    
  2. 定义脚本接口
    把 SAS 需要动态化的决策抽象成纯接口,脚本只需实现逻辑,无需感知 SAS 内部 API:

    interface DynamicScopeService {
        Set<String> resolveScopes(Authentication auth, HttpServletRequest request);
    }
    
  3. 安全编译
    使用 SecureASTCustomizer 关闭new File()、System.exit()、ReflectUtils 等 19 项高危 AST:

    SecureASTCustomizer secure = new SecureASTCustomizer();
    secure.setClosuresAllowed(true);
    secure.setMethodDefinitionAllowed(false);   // 禁止脚本再定义新方法,降低复杂度
    secure.setImportsWhitelist(Arrays.asList("java.util", "org.springframework.security"));
    CompilerConfiguration config = new CompilerConfiguration();
    config.addCompilationCustomizers(secure);
    GroovyClassLoader loader = new GroovyClassLoader(this.getClass().getClassLoader(), config);
    
  4. 热加载与缓存
    脚本文件放在 /opt/sas/scripts/tenant_#{tenantId}/DynamicScopeService.groovy,采用 GroovyScriptEngine 监听目录:

    GroovyScriptEngine engine = new GroovyScriptEngine(new String[]{scriptRoot}, loader);
    Class<?> scriptClass = engine.loadScriptByName(scriptName);
    DynamicScopeService instance = (DynamicScopeService) scriptClass.getDeclaredConstructor().newInstance();
    

    实例缓存到 Caffeine<String, DynamicScopeService>,key 为“tenantId + sha256(scriptContent)”,过期写后 5 分钟自动失效,兼顾热加载与性能。

  5. 嵌入 SAS
    在 OAuth2TokenCustomizer<JwtEncodingContext> 中注入 DynamicScopeService:

    @Component
    public class GroovyScopeCustomizer implements OAuth2TokenCustomizer<JwtEncodingContext> {
        @Override
        public void customize(JwtEncodingContext context) {
            String tenantId = TenantContextHolder.get();
            DynamicScopeService service = GroovyScriptCache.get(tenantId);
            Set<String> extraScopes = service.resolveScopes(context.getPrincipal(), request);
            context.getClaims().claim("scopes", extraScopes);
        }
    }
    

    至此,租户级动态 scope 已注入 JWT,且无需重启授权服务器。

  6. 兜底与回滚
    脚本一旦抛出异常,CircuitBreaker 计数 +1,三次后自动使用本地 Java 兜底实现;同时DingTalk 群机器人秒级告警,运维平台一键回滚到上一 Git 版本,RTO < 30s,满足国内金融级 SLA。

拓展思考

  1. 多语言混合:如果企业里还有Python 策略工程师,可用 GraalVM Polyglot 把 Python 脚本编译成 LLVM bitcode,再与 Groovy 脚本统一缓存管理,实现“一个热加载框架,多语言策略共用”。
  2. 零信任架构:脚本热加载虽爽,但供应链攻击不可忽视。可引入国产 SM2 签名:脚本上线前用运维私钥签名,SAS 启动时用内置公钥验签,验签失败直接拒绝加载,满足等保 2.0 对关键业务系统的“可信验证”要求。
  3. 性能极限:当 QPS 涨到 5 万,Caffeine 缓存 + Groovy 调用仍会出现 Young GC 抖动。可把脚本预编译为字节码后上传 JAR 到 Spring Boot Layered Docker,利用 Kubernetes 的 Rollout 做秒级替换,既保留动态性,又享受原生性能,实现“动态语言编写、静态语言运行”的混合模式。