Unverified Commit 976dd526 authored by OJ Kwon's avatar OJ Kwon Committed by GitHub

feat(custom-transform): middleware dynamic assert transform (#63538)

### What

This PR implements runtime warning for dynamic codes (`eval`,
`Function`...) in edge runtime. Webpack uses middleware plugin to
replace / wrap codes, in case of Turbopack we don't have equivalent, so
creating a new transform visitor and run it if the context is edge.
Since sandbox augments global fn (__next_*), transform simply wraps the
expr if it matches to the condition.

Closes PACK-2804
parent aeafed94
...@@ -177,6 +177,19 @@ impl AppProject { ...@@ -177,6 +177,19 @@ impl AppProject {
Value::new(self.rsc_ty()), Value::new(self.rsc_ty()),
self.project().next_mode(), self.project().next_mode(),
self.project().next_config(), self.project().next_config(),
NextRuntime::NodeJs,
))
}
#[turbo_tasks::function]
async fn edge_rsc_module_options_context(self: Vc<Self>) -> Result<Vc<ModuleOptionsContext>> {
Ok(get_server_module_options_context(
self.project().project_path(),
self.project().execution_context(),
Value::new(self.rsc_ty()),
self.project().next_mode(),
self.project().next_config(),
NextRuntime::Edge,
)) ))
} }
...@@ -188,6 +201,19 @@ impl AppProject { ...@@ -188,6 +201,19 @@ impl AppProject {
Value::new(self.route_ty()), Value::new(self.route_ty()),
self.project().next_mode(), self.project().next_mode(),
self.project().next_config(), self.project().next_config(),
NextRuntime::NodeJs,
))
}
#[turbo_tasks::function]
async fn edge_route_module_options_context(self: Vc<Self>) -> Result<Vc<ModuleOptionsContext>> {
Ok(get_server_module_options_context(
self.project().project_path(),
self.project().execution_context(),
Value::new(self.route_ty()),
self.project().next_mode(),
self.project().next_config(),
NextRuntime::Edge,
)) ))
} }
...@@ -292,7 +318,7 @@ impl AppProject { ...@@ -292,7 +318,7 @@ impl AppProject {
ModuleAssetContext::new( ModuleAssetContext::new(
Vc::cell(transitions), Vc::cell(transitions),
self.project().edge_compile_time_info(), self.project().edge_compile_time_info(),
self.rsc_module_options_context(), self.edge_rsc_module_options_context(),
self.edge_rsc_resolve_options_context(), self.edge_rsc_resolve_options_context(),
Vc::cell("app-edge-rsc".to_string()), Vc::cell("app-edge-rsc".to_string()),
) )
...@@ -314,7 +340,7 @@ impl AppProject { ...@@ -314,7 +340,7 @@ impl AppProject {
ModuleAssetContext::new( ModuleAssetContext::new(
Default::default(), Default::default(),
self.project().edge_compile_time_info(), self.project().edge_compile_time_info(),
self.route_module_options_context(), self.edge_route_module_options_context(),
self.edge_route_resolve_options_context(), self.edge_route_resolve_options_context(),
Vc::cell("app-edge-route".to_string()), Vc::cell("app-edge-route".to_string()),
) )
...@@ -339,6 +365,19 @@ impl AppProject { ...@@ -339,6 +365,19 @@ impl AppProject {
Value::new(self.ssr_ty()), Value::new(self.ssr_ty()),
self.project().next_mode(), self.project().next_mode(),
self.project().next_config(), self.project().next_config(),
NextRuntime::NodeJs,
))
}
#[turbo_tasks::function]
async fn edge_ssr_module_options_context(self: Vc<Self>) -> Result<Vc<ModuleOptionsContext>> {
Ok(get_server_module_options_context(
self.project().project_path(),
self.project().execution_context(),
Value::new(self.ssr_ty()),
self.project().next_mode(),
self.project().next_config(),
NextRuntime::Edge,
)) ))
} }
...@@ -378,7 +417,7 @@ impl AppProject { ...@@ -378,7 +417,7 @@ impl AppProject {
fn edge_ssr_transition(self: Vc<Self>) -> Vc<ContextTransition> { fn edge_ssr_transition(self: Vc<Self>) -> Vc<ContextTransition> {
ContextTransition::new( ContextTransition::new(
self.project().edge_compile_time_info(), self.project().edge_compile_time_info(),
self.ssr_module_options_context(), self.edge_ssr_module_options_context(),
self.edge_ssr_resolve_options_context(), self.edge_ssr_resolve_options_context(),
Vc::cell("app-edge-ssr".to_string()), Vc::cell("app-edge-ssr".to_string()),
) )
......
...@@ -362,7 +362,7 @@ impl PagesProject { ...@@ -362,7 +362,7 @@ impl PagesProject {
ModuleAssetContext::new( ModuleAssetContext::new(
Default::default(), Default::default(),
self.project().edge_compile_time_info(), self.project().edge_compile_time_info(),
self.ssr_module_options_context(), self.edge_ssr_module_options_context(),
self.edge_ssr_resolve_options_context(), self.edge_ssr_resolve_options_context(),
Vc::cell("edge-ssr".to_string()), Vc::cell("edge-ssr".to_string()),
) )
...@@ -373,7 +373,7 @@ impl PagesProject { ...@@ -373,7 +373,7 @@ impl PagesProject {
ModuleAssetContext::new( ModuleAssetContext::new(
Default::default(), Default::default(),
self.project().edge_compile_time_info(), self.project().edge_compile_time_info(),
self.api_module_options_context(), self.edge_api_module_options_context(),
self.edge_ssr_resolve_options_context(), self.edge_ssr_resolve_options_context(),
Vc::cell("edge-api".to_string()), Vc::cell("edge-api".to_string()),
) )
...@@ -384,7 +384,7 @@ impl PagesProject { ...@@ -384,7 +384,7 @@ impl PagesProject {
ModuleAssetContext::new( ModuleAssetContext::new(
Default::default(), Default::default(),
self.project().edge_compile_time_info(), self.project().edge_compile_time_info(),
self.ssr_data_module_options_context(), self.edge_ssr_data_module_options_context(),
self.edge_ssr_resolve_options_context(), self.edge_ssr_resolve_options_context(),
Vc::cell("edge-ssr-data".to_string()), Vc::cell("edge-ssr-data".to_string()),
) )
...@@ -400,6 +400,21 @@ impl PagesProject { ...@@ -400,6 +400,21 @@ impl PagesProject {
}), }),
self.project().next_mode(), self.project().next_mode(),
self.project().next_config(), self.project().next_config(),
NextRuntime::NodeJs,
))
}
#[turbo_tasks::function]
async fn edge_ssr_module_options_context(self: Vc<Self>) -> Result<Vc<ModuleOptionsContext>> {
Ok(get_server_module_options_context(
self.project().project_path(),
self.project().execution_context(),
Value::new(ServerContextType::Pages {
pages_dir: self.pages_dir(),
}),
self.project().next_mode(),
self.project().next_config(),
NextRuntime::Edge,
)) ))
} }
...@@ -413,6 +428,21 @@ impl PagesProject { ...@@ -413,6 +428,21 @@ impl PagesProject {
}), }),
self.project().next_mode(), self.project().next_mode(),
self.project().next_config(), self.project().next_config(),
NextRuntime::NodeJs,
))
}
#[turbo_tasks::function]
async fn edge_api_module_options_context(self: Vc<Self>) -> Result<Vc<ModuleOptionsContext>> {
Ok(get_server_module_options_context(
self.project().project_path(),
self.project().execution_context(),
Value::new(ServerContextType::PagesApi {
pages_dir: self.pages_dir(),
}),
self.project().next_mode(),
self.project().next_config(),
NextRuntime::Edge,
)) ))
} }
...@@ -426,6 +456,23 @@ impl PagesProject { ...@@ -426,6 +456,23 @@ impl PagesProject {
}), }),
self.project().next_mode(), self.project().next_mode(),
self.project().next_config(), self.project().next_config(),
NextRuntime::NodeJs,
))
}
#[turbo_tasks::function]
async fn edge_ssr_data_module_options_context(
self: Vc<Self>,
) -> Result<Vc<ModuleOptionsContext>> {
Ok(get_server_module_options_context(
self.project().project_path(),
self.project().execution_context(),
Value::new(ServerContextType::PagesData {
pages_dir: self.pages_dir(),
}),
self.project().next_mode(),
self.project().next_config(),
NextRuntime::Edge,
)) ))
} }
......
...@@ -18,6 +18,7 @@ use next_core::{ ...@@ -18,6 +18,7 @@ use next_core::{
get_server_resolve_options_context, ServerContextType, get_server_resolve_options_context, ServerContextType,
}, },
next_telemetry::NextFeatureTelemetry, next_telemetry::NextFeatureTelemetry,
util::NextRuntime,
}; };
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tracing::Instrument; use tracing::Instrument;
...@@ -809,6 +810,7 @@ impl Project { ...@@ -809,6 +810,7 @@ impl Project {
Value::new(ServerContextType::Middleware), Value::new(ServerContextType::Middleware),
self.next_mode(), self.next_mode(),
self.next_config(), self.next_config(),
NextRuntime::Edge,
), ),
get_edge_resolve_options_context( get_edge_resolve_options_context(
self.project_path(), self.project_path(),
...@@ -842,6 +844,7 @@ impl Project { ...@@ -842,6 +844,7 @@ impl Project {
Value::new(ServerContextType::Instrumentation), Value::new(ServerContextType::Instrumentation),
self.next_mode(), self.next_mode(),
self.next_config(), self.next_config(),
NextRuntime::NodeJs,
), ),
get_server_resolve_options_context( get_server_resolve_options_context(
self.project_path(), self.project_path(),
......
...@@ -67,7 +67,7 @@ use crate::{ ...@@ -67,7 +67,7 @@ use crate::{
get_decorators_transform_options, get_jsx_transform_options, get_decorators_transform_options, get_jsx_transform_options,
get_typescript_transform_options, get_typescript_transform_options,
}, },
util::{foreign_code_context_condition, load_next_js_templateon}, util::{foreign_code_context_condition, load_next_js_templateon, NextRuntime},
}; };
#[turbo_tasks::value(serialization = "auto_for_input")] #[turbo_tasks::value(serialization = "auto_for_input")]
...@@ -325,11 +325,14 @@ pub async fn get_server_module_options_context( ...@@ -325,11 +325,14 @@ pub async fn get_server_module_options_context(
ty: Value<ServerContextType>, ty: Value<ServerContextType>,
mode: Vc<NextMode>, mode: Vc<NextMode>,
next_config: Vc<NextConfig>, next_config: Vc<NextConfig>,
next_runtime: NextRuntime,
) -> Result<Vc<ModuleOptionsContext>> { ) -> Result<Vc<ModuleOptionsContext>> {
let mut next_server_rules = let mut next_server_rules =
get_next_server_transforms_rules(next_config, ty.into_value(), mode, false).await?; get_next_server_transforms_rules(next_config, ty.into_value(), mode, false, next_runtime)
.await?;
let mut foreign_next_server_rules = let mut foreign_next_server_rules =
get_next_server_transforms_rules(next_config, ty.into_value(), mode, true).await?; get_next_server_transforms_rules(next_config, ty.into_value(), mode, true, next_runtime)
.await?;
let internal_custom_rules = let internal_custom_rules =
get_next_server_internal_transforms_rules(ty.into_value(), *next_config.mdx_rs().await?) get_next_server_internal_transforms_rules(ty.into_value(), *next_config.mdx_rs().await?)
.await?; .await?;
......
...@@ -14,8 +14,10 @@ use crate::{ ...@@ -14,8 +14,10 @@ use crate::{
get_server_actions_transform_rule, next_amp_attributes::get_next_amp_attr_rule, get_server_actions_transform_rule, next_amp_attributes::get_next_amp_attr_rule,
next_cjs_optimizer::get_next_cjs_optimizer_rule, next_cjs_optimizer::get_next_cjs_optimizer_rule,
next_disallow_re_export_all_in_page::get_next_disallow_export_all_in_page_rule, next_disallow_re_export_all_in_page::get_next_disallow_export_all_in_page_rule,
next_middleware_dynamic_assert::get_middleware_dynamic_assert_rule,
next_pure::get_next_pure_rule, server_actions::ActionsTransform, next_pure::get_next_pure_rule, server_actions::ActionsTransform,
}, },
util::NextRuntime,
}; };
/// Returns a list of module rules which apply server-side, Next.js-specific /// Returns a list of module rules which apply server-side, Next.js-specific
...@@ -25,6 +27,7 @@ pub async fn get_next_server_transforms_rules( ...@@ -25,6 +27,7 @@ pub async fn get_next_server_transforms_rules(
context_ty: ServerContextType, context_ty: ServerContextType,
mode: Vc<NextMode>, mode: Vc<NextMode>,
foreign_code: bool, foreign_code: bool,
next_runtime: NextRuntime,
) -> Result<Vec<ModuleRule>> { ) -> Result<Vec<ModuleRule>> {
let mut rules = vec![]; let mut rules = vec![];
...@@ -111,6 +114,10 @@ pub async fn get_next_server_transforms_rules( ...@@ -111,6 +114,10 @@ pub async fn get_next_server_transforms_rules(
// optimize_use_state)) // optimize_use_state))
rules.push(get_next_image_rule()); rules.push(get_next_image_rule());
if let NextRuntime::Edge = next_runtime {
rules.push(get_middleware_dynamic_assert_rule(mdx_rs));
}
} }
Ok(rules) Ok(rules)
......
...@@ -5,6 +5,7 @@ pub(crate) mod next_cjs_optimizer; ...@@ -5,6 +5,7 @@ pub(crate) mod next_cjs_optimizer;
pub(crate) mod next_disallow_re_export_all_in_page; pub(crate) mod next_disallow_re_export_all_in_page;
pub(crate) mod next_dynamic; pub(crate) mod next_dynamic;
pub(crate) mod next_font; pub(crate) mod next_font;
pub(crate) mod next_middleware_dynamic_assert;
pub(crate) mod next_optimize_server_react; pub(crate) mod next_optimize_server_react;
pub(crate) mod next_page_config; pub(crate) mod next_page_config;
pub(crate) mod next_pure; pub(crate) mod next_pure;
......
use anyhow::Result;
use async_trait::async_trait;
use next_custom_transforms::transforms::middleware_dynamic::next_middleware_dynamic;
use turbo_tasks::Vc;
use turbopack_binding::{
swc::core::ecma::{ast::*, visit::VisitMutWith},
turbopack::{
ecmascript::{CustomTransformer, EcmascriptInputTransform, TransformContext},
turbopack::module_options::{ModuleRule, ModuleRuleEffect},
},
};
use super::module_rule_match_js_no_url;
pub fn get_middleware_dynamic_assert_rule(enable_mdx_rs: bool) -> ModuleRule {
let transformer =
EcmascriptInputTransform::Plugin(Vc::cell(Box::new(NextMiddlewareDynamicAssert {}) as _));
ModuleRule::new(
module_rule_match_js_no_url(enable_mdx_rs),
vec![ModuleRuleEffect::ExtendEcmascriptTransforms {
prepend: Vc::cell(vec![]),
append: Vc::cell(vec![transformer]),
}],
)
}
#[derive(Debug)]
struct NextMiddlewareDynamicAssert {}
#[async_trait]
impl CustomTransformer for NextMiddlewareDynamicAssert {
async fn transform(&self, program: &mut Program, _ctx: &TransformContext<'_>) -> Result<()> {
let mut visitor = next_middleware_dynamic();
program.visit_mut_with(&mut visitor);
Ok(())
}
}
use swc_core::{ecma::visit::VisitMutWith, quote};
use turbopack_binding::swc::core::ecma::{ast::*, visit::VisitMut};
enum WrappedExpr {
Eval,
WasmCompile,
WasmInstantiate,
}
/// Replaces call / expr to dynamic evaluation in the give code to
/// wrapped expression (__next_eval__, __next_webassembly_compile__,..) to raise
/// corresponding error.
///
/// This transform is specific to edge runtime which are not allowed to
/// call certain dynamic evaluation (eval, webassembly.instantiate, etc)
///
/// check middleware-plugin for corresponding webpack side transform.
pub fn next_middleware_dynamic() -> MiddlewareDynamic {
MiddlewareDynamic {}
}
pub struct MiddlewareDynamic {}
impl VisitMut for MiddlewareDynamic {
fn visit_mut_expr(&mut self, expr: &mut Expr) {
let mut should_wrap = None;
expr.visit_mut_children_with(self);
if let Expr::Call(call_expr) = &expr {
let callee = &call_expr.callee;
if let Callee::Expr(callee) = callee {
// `eval('some')`, or `Function('some')`
if let Expr::Ident(ident) = &**callee {
if ident.sym == "eval" || ident.sym == "Function" {
should_wrap = Some(WrappedExpr::Eval);
}
}
if let Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(prop_ident),
..
}) = &**callee
{
if let Expr::Ident(ident) = &**obj {
// `global.eval('some')`
if ident.sym == "global" && prop_ident.sym == "eval" {
should_wrap = Some(WrappedExpr::Eval);
}
// `WebAssembly.compile('some')` & `WebAssembly.instantiate('some')`
if ident.sym == "WebAssembly" {
if prop_ident.sym == "compile" {
should_wrap = Some(WrappedExpr::WasmCompile);
} else if prop_ident.sym == "instantiate" {
should_wrap = Some(WrappedExpr::WasmInstantiate);
}
}
}
if let Expr::Member(MemberExpr {
obj,
prop: MemberProp::Ident(member_prop_ident),
..
}) = &**obj
{
if let Expr::Ident(ident) = &**obj {
// `global.WebAssembly.compile('some')` &
// `global.WebAssembly.instantiate('some')`
if ident.sym == "global" && member_prop_ident.sym == "WebAssembly" {
if prop_ident.sym == "compile" {
should_wrap = Some(WrappedExpr::WasmCompile);
} else if prop_ident.sym == "instantiate" {
should_wrap = Some(WrappedExpr::WasmInstantiate);
}
}
}
}
}
}
match should_wrap {
Some(WrappedExpr::Eval) => {
*expr = quote!("__next_eval__(function() { return $orig_call });" as Expr, orig_call: Expr = Expr::Call(call_expr.clone()));
}
Some(WrappedExpr::WasmCompile) => {
*expr = quote!("__next_webassembly_compile__(function() { return $orig_call });" as Expr, orig_call: Expr = Expr::Call(call_expr.clone()));
}
Some(WrappedExpr::WasmInstantiate) => {
*expr = quote!("__next_webassembly_instantiate__(function() { return $orig_call });" as Expr, orig_call: Expr = Expr::Call(call_expr.clone()));
}
None => {}
}
}
if let Expr::New(NewExpr { callee, .. }) = &expr {
if let Expr::Ident(ident) = &**callee {
if ident.sym == "Function" {
*expr = quote!("__next_eval__(function() { return $orig_call });" as Expr, orig_call: Expr = expr.clone());
}
}
}
}
}
...@@ -5,6 +5,7 @@ pub mod disallow_re_export_all_in_page; ...@@ -5,6 +5,7 @@ pub mod disallow_re_export_all_in_page;
pub mod dynamic; pub mod dynamic;
pub mod fonts; pub mod fonts;
pub mod import_analyzer; pub mod import_analyzer;
pub mod middleware_dynamic;
pub mod next_ssg; pub mod next_ssg;
pub mod optimize_server_react; pub mod optimize_server_react;
pub mod page_config; pub mod page_config;
......
...@@ -9513,9 +9513,7 @@ ...@@ -9513,9 +9513,7 @@
"Edge route usage of dynamic code evaluation dev mode does not show warning when no code uses eval", "Edge route usage of dynamic code evaluation dev mode does not show warning when no code uses eval",
"Middleware usage of dynamic code evaluation dev mode does not show a warning when running WebAssembly.instantiate with a module parameter", "Middleware usage of dynamic code evaluation dev mode does not show a warning when running WebAssembly.instantiate with a module parameter",
"Middleware usage of dynamic code evaluation dev mode does not show warning when no code uses eval", "Middleware usage of dynamic code evaluation dev mode does not show warning when no code uses eval",
"Page using eval in dev mode does issue dynamic code evaluation warnings" "Page using eval in dev mode does issue dynamic code evaluation warnings",
],
"failed": [
"Edge route usage of dynamic code evaluation dev mode shows a warning when running WebAssembly.compile", "Edge route usage of dynamic code evaluation dev mode shows a warning when running WebAssembly.compile",
"Edge route usage of dynamic code evaluation dev mode shows a warning when running WebAssembly.instantiate with a buffer parameter", "Edge route usage of dynamic code evaluation dev mode shows a warning when running WebAssembly.instantiate with a buffer parameter",
"Edge route usage of dynamic code evaluation dev mode shows a warning when running code with eval", "Edge route usage of dynamic code evaluation dev mode shows a warning when running code with eval",
...@@ -9523,6 +9521,7 @@ ...@@ -9523,6 +9521,7 @@
"Middleware usage of dynamic code evaluation dev mode shows a warning when running WebAssembly.instantiate with a buffer parameter", "Middleware usage of dynamic code evaluation dev mode shows a warning when running WebAssembly.instantiate with a buffer parameter",
"Middleware usage of dynamic code evaluation dev mode shows a warning when running code with eval" "Middleware usage of dynamic code evaluation dev mode shows a warning when running code with eval"
], ],
"failed": [],
"pending": [ "pending": [
"Edge route usage of dynamic code evaluation production mode should have middleware warning during build", "Edge route usage of dynamic code evaluation production mode should have middleware warning during build",
"Middleware usage of dynamic code evaluation production mode should have middleware warning during build" "Middleware usage of dynamic code evaluation production mode should have middleware warning during build"
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment