本文主要研究一下dubbo-go-proxy的authorityFilter

authorityFilter

dubbo-go-proxy/pkg/filter/authority/authority.go

func Init() {
    extension.SetFilterFunc(constant.HTTPAuthorityFilter, authorityFilterFunc())
}

func authorityFilterFunc() context.FilterFunc {
    return New().Do()
}

// authorityFilter is a filter for blacklist/whitelist.
type authorityFilter struct {
}

// New create blacklist/whitelist filter.
func New() filter.Filter {
    return &authorityFilter{}
}
authorityFilter往extension设置了名为dgp.filters.http.authority_filter的authorityFilterFunc;该func执行的是authorityFilter.Do方法

Do

dubbo-go-proxy/pkg/filter/authority/authority.go

// Do execute blacklist/whitelist filter logic.
func (f authorityFilter) Do() context.FilterFunc {
    return func(c context.Context) {
        f.doAuthorityFilter(c.(*http.HttpContext))
    }
}
Do方法执行的是doAuthorityFilter方法

doAuthorityFilter

dubbo-go-proxy/pkg/filter/authority/authority.go

func (f authorityFilter) doAuthorityFilter(c *http.HttpContext) {
    for _, r := range c.HttpConnectionManager.AuthorityConfig.Rules {
        item := c.GetClientIP()
        if r.Limit == model.App {
            item = c.GetApplicationName()
        }

        result := passCheck(item, r)
        if !result {
            c.WriteWithStatus(nh.StatusForbidden, constant.Default403Body)
            c.Abort()
            return
        }
    }

    c.Next()
}
doAuthorityFilter方法遍历AuthorityConfig的Rules,挨个执行passCheck判断

passCheck

dubbo-go-proxy/pkg/filter/authority/authority.go

func passCheck(item string, rule model.AuthorityRule) bool {
    result := false
    for _, it := range rule.Items {
        if it == item {
            result = true
            break
        }
    }

    if (rule.Strategy == model.Blacklist && result == true) || (rule.Strategy == model.Whitelist && result == false) {
        return false
    }

    return true
}
passCheck方法遍历rule.Items,挨个根据Blacklist或者Whitelist判断clientIP是否命中

小结

dubbo-go-proxy的authorityFilter遍历AuthorityConfig的Rules,挨个根据Blacklist或者Whitelist判断clientIP是否命中,命中则无法通过,返回StatusForbidden。

doc


codecraft
11.9k 声望2k 粉丝

当一个代码的工匠回首往事时,不因虚度年华而悔恨,也不因碌碌无为而羞愧,这样,当他老的时候,可以很自豪告诉世人,我曾经将代码注入生命去打造互联网的浪潮之巅,那是个很疯狂的时代,我在一波波的浪潮上留下...