From 3cbbd1b62e22bb2d3964282fa3f27a6880a33875 Mon Sep 17 00:00:00 2001 From: WeidiDeng Date: Mon, 10 Jul 2023 11:20:29 +0800 Subject: [PATCH] fix: unwrap adapter modules to get underlying modules --- caddyconfig/configadapters.go | 7 +++++++ cmd/packagesfuncs.go | 18 +++++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/caddyconfig/configadapters.go b/caddyconfig/configadapters.go index 0ca3c3af..9288132a 100644 --- a/caddyconfig/configadapters.go +++ b/caddyconfig/configadapters.go @@ -135,4 +135,11 @@ func (am adapterModule) CaddyModule() caddy.ModuleInfo { } } +// UnwrapAdapter return the original Adapter, this method must be exported +// to be type-assertable 🤷 +// hack, https://github.com/caddyserver/caddy/issues/5621 +func (am adapterModule) UnwrapAdapter() any { + return am.Adapter +} + var configAdapters = make(map[string]Adapter) diff --git a/cmd/packagesfuncs.go b/cmd/packagesfuncs.go index 3aed0e8c..6d08ecf1 100644 --- a/cmd/packagesfuncs.go +++ b/cmd/packagesfuncs.go @@ -174,6 +174,13 @@ func upgradeBuild(pluginPkgs map[string]struct{}, fl Flags) (int, error) { return caddy.ExitCodeSuccess, nil } +func getModPkgPath(iface any) string { + if rv := reflect.ValueOf(iface); rv.Kind() == reflect.Ptr { + iface = reflect.New(reflect.TypeOf(iface).Elem()).Elem().Interface() + } + return reflect.TypeOf(iface).PkgPath() +} + func getModules() (standard, nonstandard, unknown []moduleInfo, err error) { bi, ok := debug.ReadBuildInfo() if !ok { @@ -195,10 +202,15 @@ func getModules() (standard, nonstandard, unknown []moduleInfo, err error) { // not sure why), and since New() should return a pointer // value, we need to dereference it first iface := any(modInfo.New()) - if rv := reflect.ValueOf(iface); rv.Kind() == reflect.Ptr { - iface = reflect.New(reflect.TypeOf(iface).Elem()).Elem().Interface() + modPkgPath := getModPkgPath(iface) + + // Unwrap config adapters to get the underlying adapter modules, as config adapter modules are hacks anyway. https://github.com/caddyserver/caddy/issues/5621 + // this method will only be called if it's from the built-in module to prevent abuse + if strings.HasPrefix(modPkgPath, caddy.ImportPath) { + if unwrapper, ok := iface.(interface{ UnwrapAdapter() any }); ok { + modPkgPath = getModPkgPath(unwrapper.UnwrapAdapter()) + } } - modPkgPath := reflect.TypeOf(iface).PkgPath() // now we find the Go module that the Caddy module's package // belongs to; we assume the Caddy module package path will