聊聊dubbo-go-proxy的authorityFilter

盖嘉珍
2023-12-01

本文主要研究一下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

 类似资料: