repo
stringlengths
6
47
file_url
stringlengths
77
269
file_path
stringlengths
5
186
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-07 08:35:43
2026-01-07 08:55:24
truncated
bool
2 classes
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/TreeNode_test.go
structures/TreeNode_test.go
package structures import ( "reflect" "testing" "github.com/stretchr/testify/assert" ) var ( // 同一个 TreeNode 的不同表达方式 // 1 // / \ // 2 3 // / \ / \ // 4 5 6 7 LeetCodeOrder = []int{1, 2, 3, 4, 5, 6, 7} preOrder = []int{1, 2, 4, 5, 3, 6, 7} inOrder = []int{4, 2, 5, 1, 6, 3, 7} postOrder = []int{4, 5, 2, 6, 7, 3, 1} ) func Test_Ints2TreeNode(t *testing.T) { ast := assert.New(t) expected := PreIn2Tree(preOrder, inOrder) actual := Ints2TreeNode(LeetCodeOrder) ast.Equal(expected, actual) actual = Ints2TreeNode([]int{}) ast.Nil(actual) } func Test_preIn2Tree(t *testing.T) { ast := assert.New(t) actual := Tree2Postorder(PreIn2Tree(preOrder, inOrder)) expected := postOrder ast.Equal(expected, actual) ast.Panics(func() { PreIn2Tree([]int{1}, []int{}) }) ast.Nil(PreIn2Tree([]int{}, []int{})) } func Test_inPost2Tree(t *testing.T) { ast := assert.New(t) actual := Tree2Preorder(InPost2Tree(inOrder, postOrder)) expected := preOrder ast.Equal(expected, actual) ast.Panics(func() { InPost2Tree([]int{1}, []int{}) }) ast.Nil(InPost2Tree([]int{}, []int{})) } func Test_tree2Ints(t *testing.T) { ast := assert.New(t) root := PreIn2Tree(preOrder, inOrder) ast.Equal(preOrder, Tree2Preorder(root)) ast.Nil(Tree2Preorder(nil)) ast.Equal(inOrder, Tree2Inorder(root)) ast.Nil(Tree2Inorder(nil)) ast.Equal(postOrder, Tree2Postorder(root)) ast.Nil(Tree2Postorder(nil)) } func Test_indexOf(t *testing.T) { ast := assert.New(t) ast.Equal(1, indexOf(1, []int{0, 1, 2, 3})) ast.Panics(func() { indexOf(0, []int{1, 2, 3}) }) } func Test_TreeNode_Equal(t *testing.T) { type args struct { a *TreeNode } tests := []struct { name string fields args args args want bool }{ { "相等", args{Ints2TreeNode([]int{1, 2, 3, 4, 5})}, args{Ints2TreeNode([]int{1, 2, 3, 4, 5})}, true, }, { "不相等", args{Ints2TreeNode([]int{1, 2, 3, 4, 5})}, args{Ints2TreeNode([]int{1, 2, 3, NULL, 5})}, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tn := tt.fields.a if got := tn.Equal(tt.args.a); got != tt.want { t.Errorf("TreeNode.Equal() = %v, want %v", got, tt.want) } }) } } func Test_GetTargetNode(t *testing.T) { ints := []int{3, 5, 1, 6, 2, 0, 8, NULL, NULL, 7, 4} root := Ints2TreeNode(ints) type args struct { root *TreeNode target int } tests := []struct { name string args args want *TreeNode }{ { "找到 root.Right.Right", args{ root: root, target: 8, }, root.Right.Right, }, { "找到 root.Left.Left", args{ root: root, target: 6, }, root.Left.Left, }, // } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if got := GetTargetNode(tt.args.root, tt.args.target); !reflect.DeepEqual(got, tt.want) { t.Errorf("GetTargetNode() = %v, want %v", got, tt.want) } }) } } func Test_Tree2ints(t *testing.T) { ast := assert.New(t) root := PreIn2Tree(preOrder, inOrder) actual := LeetCodeOrder expected := Tree2ints(root) ast.Equal(expected, actual) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/Stack.go
structures/Stack.go
package structures // Stack 是用于存放 int 的 栈 type Stack struct { nums []int } // NewStack 返回 *kit.Stack func NewStack() *Stack { return &Stack{nums: []int{}} } // Push 把 n 放入 栈 func (s *Stack) Push(n int) { s.nums = append(s.nums, n) } // Pop 从 s 中取出最后放入 栈 的值 func (s *Stack) Pop() int { res := s.nums[len(s.nums)-1] s.nums = s.nums[:len(s.nums)-1] return res } // Len 返回 s 的长度 func (s *Stack) Len() int { return len(s.nums) } // IsEmpty 反馈 s 是否为空 func (s *Stack) IsEmpty() bool { return s.Len() == 0 }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/PriorityQueue.go
structures/PriorityQueue.go
package structures // This example demonstrates a priority queue built using the heap interface. import ( "container/heap" ) // entry 是 priorityQueue 中的元素 type entry struct { key string priority int // index 是 entry 在 heap 中的索引号 // entry 加入 Priority Queue 后, Priority 会变化时,很有用 // 如果 entry.priority 一直不变的话,可以删除 index index int } // PQ implements heap.Interface and holds entries. type PQ []*entry func (pq PQ) Len() int { return len(pq) } func (pq PQ) Less(i, j int) bool { return pq[i].priority < pq[j].priority } func (pq PQ) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] pq[i].index = i pq[j].index = j } // Push 往 pq 中放 entry func (pq *PQ) Push(x interface{}) { temp := x.(*entry) temp.index = len(*pq) *pq = append(*pq, temp) } // Pop 从 pq 中取出最优先的 entry func (pq *PQ) Pop() interface{} { temp := (*pq)[len(*pq)-1] temp.index = -1 // for safety *pq = (*pq)[0 : len(*pq)-1] return temp } // update modifies the priority and value of an entry in the queue. func (pq *PQ) update(entry *entry, value string, priority int) { entry.key = value entry.priority = priority heap.Fix(pq, entry.index) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/PriorityQueue_test.go
structures/PriorityQueue_test.go
package structures import ( "container/heap" "testing" "github.com/stretchr/testify/assert" ) func Test_priorityQueue(t *testing.T) { ast := assert.New(t) // Some items and their priorities. items := map[string]int{ "banana": 2, "apple": 1, "pear": 3, } // Create a priority queue, put the items in it, and // establish the priority queue (heap) invariants. pq := make(PQ, len(items)) i := 0 for value, priority := range items { pq[i] = &entry{ key: value, priority: priority, index: i, } i++ } heap.Init(&pq) // Insert a new item and then modify its priority. it := &entry{ key: "orange", priority: 5, } heap.Push(&pq, it) pq.update(it, it.key, 0) // Some items and their priorities. expected := []string{ "orange", "apple", "banana", "pear", } // Take the items out; they arrive in decreasing priority order. for pq.Len() > 0 { it := heap.Pop(&pq).(*entry) ast.Equal(expected[it.priority], it.key) } }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/Heap_test.go
structures/Heap_test.go
package structures import ( "container/heap" "fmt" "testing" "github.com/stretchr/testify/assert" ) func Test_intHeap(t *testing.T) { ast := assert.New(t) ih := new(intHeap) heap.Init(ih) heap.Push(ih, 1) heap.Pop(ih) begin, end := 0, 10 for i := begin; i < end; i++ { heap.Push(ih, i) ast.Equal(0, (*ih)[0], "插入 %d 后的最小值却是 %d, ih=%v", i, (*ih)[0], (*ih)) } for i := begin; i < end; i++ { fmt.Println(i, *ih) ast.Equal(i, heap.Pop(ih), "Pop 后 ih=%v", (*ih)) } }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/structures/NestedInteger.go
structures/NestedInteger.go
package structures // NestedInteger is the interface that allows for creating nested lists. // You should not implement it, or speculate about its implementation type NestedInteger struct { Num int Ns []*NestedInteger } // IsInteger Return true if this NestedInteger holds a single integer, rather than a nested list. func (n NestedInteger) IsInteger() bool { return n.Ns == nil } // GetInteger Return the single integer that this NestedInteger holds, if it holds a single integer // The result is undefined if this NestedInteger holds a nested list // So before calling this method, you should have a check func (n NestedInteger) GetInteger() int { return n.Num } // SetInteger Set this NestedInteger to hold a single integer. func (n *NestedInteger) SetInteger(value int) { n.Num = value } // Add Set this NestedInteger to hold a nested list and adds a nested integer to it. func (n *NestedInteger) Add(elem NestedInteger) { n.Ns = append(n.Ns, &elem) } // GetList Return the nested list that this NestedInteger holds, if it holds a nested list // The list length is zero if this NestedInteger holds a single integer // You can access NestedInteger's List element directly if you want to modify it func (n NestedInteger) GetList() []*NestedInteger { return n.Ns }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/request.go
ctl/request.go
package main import ( "bytes" "fmt" "io/ioutil" "net/http" "github.com/mozillazg/request" ) const ( // AllProblemURL define AllProblemURL = "https://leetcode.com/api/problems/all/" // QraphqlURL define QraphqlURL = "https://leetcode.com/graphql" // LoginPageURL define LoginPageURL = "https://leetcode.com/accounts/login/" // AlgorithmsURL define AlgorithmsURL = "https://leetcode.com/api/problems/Algorithms/" // ArrayProblemURL define ArrayProblemURL = "https://leetcode.com/tag/array/" ) var req *request.Request func newReq() *request.Request { if req == nil { req = signin() } return req } func signin() *request.Request { cfg := getConfig() req := request.NewRequest(new(http.Client)) req.Headers = map[string]string{ "Content-Type": "application/json", "Accept-Encoding": "", "cookie": cfg.Cookie, "x-csrftoken": cfg.CSRFtoken, "Referer": "https://leetcode.com/accounts/login/", "origin": "https://leetcode.com", } return req } func getRaw(URL string) []byte { req := newReq() resp, err := req.Get(URL) if err != nil { fmt.Printf("getRaw: Get Error: " + err.Error()) return []byte{} } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("getRaw: Read Error: " + err.Error()) return []byte{} } if resp.StatusCode == 200 { fmt.Println("Get problem Success!") } return body } func getProblemAllList() []byte { return getRaw(AllProblemURL) } // Variables define type Variables struct { slug string } func getQraphql(payload string) []byte { req := newReq() resp, err := req.PostForm(QraphqlURL, bytes.NewBuffer([]byte(payload))) if err != nil { fmt.Printf("getRaw: Get Error: " + err.Error()) return []byte{} } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { fmt.Printf("getRaw: Read Error: " + err.Error()) return []byte{} } if resp.StatusCode == 200 { fmt.Println("Get problem Success!") } return body } func getTopicTag(variable string) string { return fmt.Sprintf(`{ "operationName": "getTopicTag", "variables": { "slug": "%s" }, "query": "query getTopicTag($slug: String!) { topicTag(slug: $slug) { name translatedName slug questions { status questionId questionFrontendId title titleSlug translatedTitle stats difficulty isPaidOnly topicTags { name translatedName slug __typename } companyTags { name translatedName slug __typename } __typename } frequencies __typename } favoritesLists { publicFavorites { ...favoriteFields __typename } privateFavorites { ...favoriteFields __typename } __typename }}fragment favoriteFields on FavoriteNode { idHash id name isPublicFavorite viewCount creator isWatched questions { questionId title titleSlug __typename } __typename}" }`, variable) } func getTagProblemList(tag string) []byte { return getQraphql(getTopicTag(tag)) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/error.go
ctl/error.go
package main import ( "fmt" "os" ) const ( // ExitSuccess define ExitSuccess = iota // ExitError define ExitError // ExitBadArgs define ExitBadArgs ) // ExitWithError define func ExitWithError(code int, err error) { fmt.Fprintln(os.Stderr, "Error: ", err) os.Exit(code) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/template_render.go
ctl/template_render.go
package main import ( "bytes" "fmt" "html/template" "io/ioutil" "os" m "github.com/halfrost/LeetCode-Go/ctl/models" "github.com/halfrost/LeetCode-Go/ctl/util" ) func makeReadmeFile(mdrows m.Mdrows) { file := "./README.md" os.Remove(file) var b bytes.Buffer tmpl := template.Must(template.New("readme").Parse(readTMPL("template.markdown"))) err := tmpl.Execute(&b, mdrows) if err != nil { fmt.Println(err) } // 保存 README.md 文件 util.WriteFile(file, b.Bytes()) } func readTMPL(path string) string { file, err := os.Open(path) if err != nil { fmt.Println(err) } defer file.Close() data, err := ioutil.ReadAll(file) if err != nil { fmt.Println(err) } return string(data) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/render.go
ctl/render.go
package main import ( "bufio" "encoding/json" "fmt" "io" "os" "regexp" "sort" "strconv" "strings" m "github.com/halfrost/LeetCode-Go/ctl/models" "github.com/halfrost/LeetCode-Go/ctl/util" "github.com/spf13/cobra" ) var ( chapterTwoList = []string{"Array", "String", "Two Pointers", "Linked List", "Stack", "Tree", "Dynamic Programming", "Backtracking", "Depth First Search", "Breadth First Search", "Binary Search", "Math", "Hash Table", "Sorting", "Bit Manipulation", "Union Find", "Sliding Window", "Segment Tree", "Binary Indexed Tree"} chapterTwoFileName = []string{"Array", "String", "Two_Pointers", "Linked_List", "Stack", "Tree", "Dynamic_Programming", "Backtracking", "Depth_First_Search", "Breadth_First_Search", "Binary_Search", "Math", "Hash_Table", "Sorting", "Bit_Manipulation", "Union_Find", "Sliding_Window", "Segment_Tree", "Binary_Indexed_Tree"} chapterTwoSlug = []string{"array", "string", "two-pointers", "linked-list", "stack", "tree", "dynamic-programming", "backtracking", "depth-first-search", "breadth-first-search", "binary-search", "math", "hash-table", "sorting", "bit-manipulation", "union-find", "sliding-window", "segment-tree", "binary-indexed-tree"} ) func newBuildCommand() *cobra.Command { mc := &cobra.Command{ Use: "build <subcommand>", Short: "Build doc related commands", } //mc.PersistentFlags().StringVar(&logicEndpoint, "endpoint", "localhost:5880", "endpoint of logic service") mc.AddCommand( newBuildREADME(), newBuildChapterTwo(), // newBuildMenu(), ) return mc } func newBuildREADME() *cobra.Command { cmd := &cobra.Command{ Use: "readme", Short: "Build readme.md commands", Run: func(cmd *cobra.Command, args []string) { buildREADME() }, } // cmd.Flags().StringVar(&alias, "alias", "", "alias") // cmd.Flags().StringVar(&appId, "appid", "", "appid") return cmd } func newBuildChapterTwo() *cobra.Command { cmd := &cobra.Command{ Use: "chapter-two", Short: "Build Chapter Two commands", Run: func(cmd *cobra.Command, args []string) { buildChapterTwo(true) }, } // cmd.Flags().StringVar(&alias, "alias", "", "alias") // cmd.Flags().StringVar(&appId, "appid", "", "appid") return cmd } func newBuildMenu() *cobra.Command { cmd := &cobra.Command{ Use: "menu", Short: "Build Menu commands", Run: func(cmd *cobra.Command, args []string) { buildBookMenu() }, } // cmd.Flags().StringVar(&alias, "alias", "", "alias") // cmd.Flags().StringVar(&appId, "appid", "", "appid") return cmd } func buildREADME() { var ( problems []m.StatStatusPairs lpa m.LeetCodeProblemAll info m.UserInfo ) // 请求所有题目信息 body := getProblemAllList() problemsMap, optimizingIds := map[int]m.StatStatusPairs{}, []int{} err := json.Unmarshal(body, &lpa) if err != nil { fmt.Println(err) return } //writeFile("leetcode_problem.json", body) // 拼凑 README 需要渲染的数据 problems = lpa.StatStatusPairs info = m.ConvertUserInfoModel(lpa) for _, v := range problems { problemsMap[int(v.Stat.FrontendQuestionID)] = v } mdrows := m.ConvertMdModelFromSsp(problems) sort.Sort(m.SortByQuestionID(mdrows)) solutionIds, _, try := util.LoadSolutionsDir() m.GenerateMdRows(solutionIds, mdrows) info.EasyTotal, info.MediumTotal, info.HardTotal, info.OptimizingEasy, info.OptimizingMedium, info.OptimizingHard, optimizingIds = statisticalData(problemsMap, solutionIds) omdrows := m.ConvertMdModelFromIds(problemsMap, optimizingIds) sort.Sort(m.SortByQuestionID(omdrows)) // 按照模板渲染 README res, err := renderReadme("./template/template.markdown", len(solutionIds), try, m.Mdrows{Mdrows: mdrows}, m.Mdrows{Mdrows: omdrows}, info) if err != nil { fmt.Println(err) return } util.WriteFile("../README.md", res) fmt.Println("write file successful") //makeReadmeFile(mds) } func renderReadme(filePath string, total, try int, mdrows, omdrows m.Mdrows, user m.UserInfo) ([]byte, error) { f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) if err != nil { return nil, err } defer f.Close() reader, output := bufio.NewReader(f), []byte{} for { line, _, err := reader.ReadLine() if err != nil { if err == io.EOF { return output, nil } return nil, err } if ok, _ := regexp.Match("{{.AvailableTable}}", line); ok { reg := regexp.MustCompile("{{.AvailableTable}}") newByte := reg.ReplaceAll(line, []byte(mdrows.AvailableTable())) output = append(output, newByte...) output = append(output, []byte("\n")...) } else if ok, _ := regexp.Match("{{.TotalNum}}", line); ok { reg := regexp.MustCompile("{{.TotalNum}}") newByte := reg.ReplaceAll(line, []byte(fmt.Sprintf("以下已经收录了 %v 道题的题解,还有 %v 道题在尝试优化到 beats 100%%", total, try))) output = append(output, newByte...) output = append(output, []byte("\n")...) } else if ok, _ := regexp.Match("{{.PersonalData}}", line); ok { reg := regexp.MustCompile("{{.PersonalData}}") newByte := reg.ReplaceAll(line, []byte(user.PersonalData())) output = append(output, newByte...) output = append(output, []byte("\n")...) } else if ok, _ := regexp.Match("{{.OptimizingTable}}", line); ok { reg := regexp.MustCompile("{{.OptimizingTable}}") newByte := reg.ReplaceAll(line, []byte(fmt.Sprintf("以下 %v 道题还需要优化到 100%% 的题目列表\n\n%v", (user.OptimizingEasy+user.OptimizingMedium+user.OptimizingHard), omdrows.AvailableTable()))) output = append(output, newByte...) output = append(output, []byte("\n")...) } else { output = append(output, line...) output = append(output, []byte("\n")...) } } } // internal: true 渲染的链接都是 hugo 内部链接,用户生成 hugo web // // false 渲染的链接是外部 HTTPS 链接,用于生成 PDF func buildChapterTwo(internal bool) { var ( gr m.GraphQLResp questions []m.Question count int ) for index, tag := range chapterTwoSlug { body := getTagProblemList(tag) // fmt.Printf("%v\n", string(body)) err := json.Unmarshal(body, &gr) if err != nil { fmt.Println(err) return } questions = gr.Data.TopicTag.Questions mdrows := m.ConvertMdModelFromQuestions(questions) sort.Sort(m.SortByQuestionID(mdrows)) solutionIds, _, _ := util.LoadSolutionsDir() tl, err := loadMetaData(fmt.Sprintf("./meta/%v", chapterTwoFileName[index])) if err != nil { fmt.Printf("err = %v\n", err) } tls := m.GenerateTagMdRows(solutionIds, tl, mdrows, internal) //fmt.Printf("tls = %v\n", tls) // 按照模板渲染 README res, err := renderChapterTwo(fmt.Sprintf("./template/%v.md", chapterTwoFileName[index]), m.TagLists{TagLists: tls}) if err != nil { fmt.Println(err) return } if internal { util.WriteFile(fmt.Sprintf("../website/content/ChapterTwo/%v.md", chapterTwoFileName[index]), res) } else { util.WriteFile(fmt.Sprintf("./pdftemp/ChapterTwo/%v.md", chapterTwoFileName[index]), res) } count++ } fmt.Printf("write %v files successful", count) } func loadMetaData(filePath string) (map[int]m.TagList, error) { f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) if err != nil { return nil, err } defer f.Close() reader, metaMap := bufio.NewReader(f), map[int]m.TagList{} for { line, _, err := reader.ReadLine() if err != nil { if err == io.EOF { return metaMap, nil } return nil, err } s := strings.Split(string(line), "|") v, _ := strconv.Atoi(strings.Split(s[1], ".")[0]) // v[0] 是题号,s[4] time, s[5] space, s[6] favorite metaMap[v] = m.TagList{ FrontendQuestionID: int32(v), Acceptance: "", Difficulty: "", TimeComplexity: s[4], SpaceComplexity: s[5], Favorite: s[6], } } } func renderChapterTwo(filePath string, tls m.TagLists) ([]byte, error) { f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) if err != nil { return nil, err } defer f.Close() reader, output := bufio.NewReader(f), []byte{} for { line, _, err := reader.ReadLine() if err != nil { if err == io.EOF { return output, nil } return nil, err } if ok, _ := regexp.Match("{{.AvailableTagTable}}", line); ok { reg := regexp.MustCompile("{{.AvailableTagTable}}") newByte := reg.ReplaceAll(line, []byte(tls.AvailableTagTable())) output = append(output, newByte...) output = append(output, []byte("\n")...) } else { output = append(output, line...) output = append(output, []byte("\n")...) } } } func buildBookMenu() { copyLackFile() // 按照模板重新渲染 Menu res, err := renderBookMenu("./template/menu.md") if err != nil { fmt.Println(err) return } util.WriteFile("../website/content/menu/index.md", res) fmt.Println("generate Menu successful") } // 拷贝 leetcode 目录下的题解 README 文件至第四章对应文件夹中 func copyLackFile() { solutionIds, soName, _ := util.LoadSolutionsDir() _, ch4Ids := util.LoadChapterFourDir() needCopy := []string{} for i := 0; i < len(solutionIds); i++ { if util.BinarySearch(ch4Ids, solutionIds[i]) == -1 { needCopy = append(needCopy, soName[i]) } } if len(needCopy) > 0 { fmt.Printf("有 %v 道题需要拷贝到第四章中\n", len(needCopy)) for i := 0; i < len(needCopy); i++ { if needCopy[i][4] == '.' { tmp, err := strconv.Atoi(needCopy[i][:4]) if err != nil { fmt.Println(err) } err = os.MkdirAll(fmt.Sprintf("../website/content/ChapterFour/%v", util.GetChpaterFourFileNum(tmp)), os.ModePerm) if err != nil { fmt.Println(err) } util.CopyFile(fmt.Sprintf("../website/content/ChapterFour/%v/%v.md", util.GetChpaterFourFileNum(tmp), needCopy[i]), fmt.Sprintf("../leetcode/%v/README.md", needCopy[i])) util.CopyFile(fmt.Sprintf("../website/content/ChapterFour/%v/_index.md", util.GetChpaterFourFileNum(tmp)), "./template/collapseSection.md") } } } else { fmt.Printf("【第四章没有需要添加的题解,已经完整了】\n") } } func generateMenu() string { res := "" res += menuLine(chapterOneMenuOrder, "ChapterOne") res += menuLine(chapterTwoFileOrder, "ChapterTwo") res += menuLine(chapterThreeFileOrder, "ChapterThree") chapterFourFileOrder, _ := getChapterFourFileOrder() res += menuLine(chapterFourFileOrder, "ChapterFour") return res } func menuLine(order []string, chapter string) string { res := "" for i := 0; i < len(order); i++ { if i == 1 && chapter == "ChapterOne" { res += fmt.Sprintf(" - [%v]({{< relref \"/%v/%v\" >}})\n", chapterMap[chapter][order[i]], chapter, order[i]) continue } if i == 0 { res += fmt.Sprintf("- [%v]({{< relref \"/%v/%v.md\" >}})\n", chapterMap[chapter][order[i]], chapter, order[i]) } else { if chapter == "ChapterFour" { res += fmt.Sprintf(" - [%v]({{< relref \"/%v/%v.md\" >}})\n", order[i], chapter, order[i]) } else { res += fmt.Sprintf(" - [%v]({{< relref \"/%v/%v.md\" >}})\n", chapterMap[chapter][order[i]], chapter, order[i]) } } } return res } func renderBookMenu(filePath string) ([]byte, error) { f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) if err != nil { return nil, err } defer f.Close() reader, output := bufio.NewReader(f), []byte{} for { line, _, err := reader.ReadLine() if err != nil { if err == io.EOF { return output, nil } return nil, err } if ok, _ := regexp.Match("{{.BookMenu}}", line); ok { reg := regexp.MustCompile("{{.BookMenu}}") newByte := reg.ReplaceAll(line, []byte(generateMenu())) output = append(output, newByte...) output = append(output, []byte("\n")...) } else { output = append(output, line...) output = append(output, []byte("\n")...) } } }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/config.go
ctl/config.go
package main import ( "fmt" "log" "github.com/BurntSushi/toml" ) const ( configTOML = "config.toml" ) type config struct { Username string Password string Cookie string CSRFtoken string } func (c config) String() string { return fmt.Sprintf("Username: %s, Password: %s", c.Username, c.Password) } func getConfig() *config { cfg := new(config) if _, err := toml.DecodeFile(configTOML, &cfg); err != nil { log.Panicf(err.Error()) } // log.Printf("get config: %s", cfg) return cfg }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/rangking.go
ctl/rangking.go
package main import ( "fmt" "strconv" "strings" ) // getRanking 让这个方法优雅一点 func getRanking() int { // 获取网页数据 URL := fmt.Sprintf("https://leetcode.com/%s/", getConfig().Username) data := getRaw(URL) str := string(data) // 通过不断裁剪 str 获取排名信息 fmt.Println(str) i := strings.Index(str, "ng-init") j := i + strings.Index(str[i:], "ng-cloak") str = str[i:j] i = strings.Index(str, "(") j = strings.Index(str, ")") str = str[i:j] // fmt.Println("2\n", str) strs := strings.Split(str, ",") str = strs[6] // fmt.Println("1\n", str) i = strings.Index(str, "'") j = 2 + strings.Index(str[2:], "'") // fmt.Println("0\n", str) str = str[i+1 : j] r, err := strconv.Atoi(str) if err != nil { fmt.Printf("无法把 %s 转换成数字Ranking", str) } return r }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/refresh.go
ctl/refresh.go
package main import ( "github.com/spf13/cobra" ) func newRefresh() *cobra.Command { cmd := &cobra.Command{ Use: "refresh", Short: "Refresh all document", Run: func(cmd *cobra.Command, args []string) { refresh() }, } // cmd.Flags().StringVar(&alias, "alias", "", "alias") // cmd.Flags().StringVar(&appId, "appid", "", "appid") return cmd } func refresh() { //buildBookMenu() copyLackFile() delPreNext() buildREADME() buildChapterTwo(true) addPreNext() }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/pdf.go
ctl/pdf.go
package main import ( "bufio" "fmt" "io" "io/ioutil" "os" "regexp" "strconv" "strings" "github.com/halfrost/LeetCode-Go/ctl/util" "github.com/spf13/cobra" ) var ( cleanString1 = "{{< columns >}}" cleanString2 = "<--->" cleanString3 = "{{< /columns >}}" cleanString4 = "<img src=\"https://books.halfrost.com/leetcode/logo.png\" alt=\"logo\" height=\"600\" align=\"right\" style=\"padding-left: 30px;\"/>" pdfPreface = `<img src="https://books.halfrost.com/leetcode/logo.png" alt="logo" heigth="1300px" align="center"/> # 说明 此版本是 https://books.halfrost.com/leetcode 网页的离线版,由于网页版实时会更新,所以此 PDF 版难免会有一些排版或者错别字。如果读者遇到了,可以到网页版相应页面,点击页面 edit 按钮,提交 pr 进行更改。此 PDF 版本号是 V%v.%v.%v。PDF 永久更新地址是 https://github.com/halfrost/leetcode-go/releases/,以版本号区分不同版本。笔者还是强烈推荐看在线版,有任何错误都会立即更新。如果觉得此书对刷题有一点点帮助,可以给此书点一个 star,鼓励一下笔者早点更新更多题解。 > 版本号说明,V%v.%v.%v,%v 是大版本号,%v 代表当前题解中有几百题,目前是 %v 题,所以第二个版本号是 %v,%v 代表当前题解中有几十题,目前是 %v 题,所以第三个版本号是 %v 。 # 目录 [toc] ` majorVersion = 1 midVersion = 0 lastVersion = 0 totalSolutions = 0 ) func newPDFCommand() *cobra.Command { cmd := &cobra.Command{ Use: "pdf", Short: "PDF related commands", Run: func(cmd *cobra.Command, args []string) { generatePDF() }, } // cmd.Flags().StringVar(&alias, "alias", "", "alias") // cmd.Flags().StringVar(&appId, "appid", "", "appid") return cmd } func generatePDF() { var ( pdf, tmp []byte err error ) // 先删除 pre-next delPreNext() chapterFourFileOrder, _ := util.LoadChapterFourDir() totalSolutions = len(chapterFourFileOrder) midVersion = totalSolutions / 100 lastVersion = totalSolutions % 100 fmt.Printf("[当前的版本号是 V%v.%v.%v]\n", majorVersion, midVersion, lastVersion) // 删除原始文档中的头部,并创建临时文件夹 prepare(fmt.Sprintf("../PDF v%v.%v.%v.md", majorVersion, midVersion, lastVersion)) // PDF 前言 pdf = append(pdf, []byte(fmt.Sprintf(pdfPreface, majorVersion, midVersion, lastVersion, majorVersion, midVersion, lastVersion, majorVersion, midVersion, totalSolutions, midVersion, lastVersion, totalSolutions, lastVersion))...) // PDF 第一章 tmp, err = loadChapter(chapterOneFileOrder, "./pdftemp", "ChapterOne") pdf = append(pdf, tmp...) // PDF 第二章 tmp, err = loadChapter(chapterTwoFileOrder, "./pdftemp", "ChapterTwo") pdf = append(pdf, tmp...) // PDF 第三章 tmp, err = loadChapter(chapterThreeFileOrder, "./pdftemp", "ChapterThree") pdf = append(pdf, tmp...) // PDF 第四章 tmp, err = util.LoadFile("./pdftemp/ChapterFour/_index.md") pdf = append(pdf, tmp...) tmp, err = loadChapter(chapterFourFileOrder, "../website/content", "ChapterFour") pdf = append(pdf, tmp...) if err != nil { fmt.Println(err) } // 生成 PDF util.WriteFile(fmt.Sprintf("../PDF v%v.%v.%v.md", majorVersion, midVersion, lastVersion), pdf) // 还原现场 addPreNext() util.DestoryDir("./pdftemp") } func loadChapter(order []string, path, chapter string) ([]byte, error) { var ( res, tmp []byte err error ) for index, v := range order { if chapter == "ChapterOne" && index == 0 { // 清理不支持的特殊 MarkDown 语法 tmp, err = clean(fmt.Sprintf("%v/%v/%v.md", path, chapter, v)) } else { if chapter == "ChapterFour" { if v[4] == '.' { num, err := strconv.Atoi(v[:4]) if err != nil { fmt.Println(err) } tmp, err = util.LoadFile(fmt.Sprintf("%v/%v/%v/%v.md", path, chapter, util.GetChpaterFourFileNum(num), v)) } } else { tmp, err = util.LoadFile(fmt.Sprintf("%v/%v/%v.md", path, chapter, v)) } } if err != nil { fmt.Println(err) return []byte{}, err } res = append(res, tmp...) } return res, err } func prepare(path string) { err := os.Remove(path) if err != nil { fmt.Println("pdf 还没有创建") fmt.Println(err) } fmt.Println("pdf 删除成功,开始构建全新版本") err = os.MkdirAll("./pdftemp/ChapterOne", os.ModePerm) if err != nil { fmt.Println(err) } for _, v := range chapterOneFileOrder { removeHeader(fmt.Sprintf("../website/content/ChapterOne/%v.md", v), fmt.Sprintf("./pdftemp/ChapterOne/%v.md", v), 5) } err = os.MkdirAll("./pdftemp/ChapterTwo", os.ModePerm) if err != nil { fmt.Println(err) } // 生成外部链接的 ChapterTwo buildChapterTwo(false) util.CopyFile("./pdftemp/ChapterTwo/_index.md", "../website/content/ChapterTwo/_index.md") for _, v := range chapterTwoFileOrder { removeHeader(fmt.Sprintf("./pdftemp/ChapterTwo/%v.md", v), fmt.Sprintf("./pdftemp/ChapterTwo/%v.md", v), 5) } err = os.MkdirAll("./pdftemp/ChapterThree", os.ModePerm) if err != nil { fmt.Println(err) } for _, v := range chapterThreeFileOrder { removeHeader(fmt.Sprintf("../website/content/ChapterThree/%v.md", v), fmt.Sprintf("./pdftemp/ChapterThree/%v.md", v), 5) } err = os.MkdirAll("./pdftemp/ChapterFour", os.ModePerm) if err != nil { fmt.Println(err) } removeHeader(fmt.Sprintf("../website/content/ChapterFour/_index.md"), fmt.Sprintf("./pdftemp/ChapterFour/_index.md"), 5) } func clean(filePath string) ([]byte, error) { f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) if err != nil { return nil, err } defer f.Close() reader, output := bufio.NewReader(f), []byte{} for { line, _, err := reader.ReadLine() if err != nil { if err == io.EOF { return output, nil } return nil, err } if ok, _ := regexp.Match(cleanString1, line); ok { reg := regexp.MustCompile(cleanString1) newByte := reg.ReplaceAll(line, []byte("")) output = append(output, newByte...) output = append(output, []byte("\n")...) } else if ok, _ := regexp.Match(cleanString2, line); ok { reg := regexp.MustCompile(cleanString2) newByte := reg.ReplaceAll(line, []byte("")) output = append(output, newByte...) output = append(output, []byte("\n")...) } else if ok, _ := regexp.Match(cleanString3, line); ok { reg := regexp.MustCompile(cleanString3) newByte := reg.ReplaceAll(line, []byte("")) output = append(output, newByte...) output = append(output, []byte("\n")...) } else if ok, _ := regexp.Match(cleanString4, line); ok { reg := regexp.MustCompile(cleanString4) newByte := reg.ReplaceAll(line, []byte("")) output = append(output, newByte...) output = append(output, []byte("\n")...) } else { output = append(output, line...) output = append(output, []byte("\n")...) } } } func removeHeader(path, newPath string, lineNumber int) { file, err := ioutil.ReadFile(path) if err != nil { panic(err) } info, _ := os.Stat(path) mode := info.Mode() array := strings.Split(string(file), "\n") array = array[lineNumber:] ioutil.WriteFile(newPath, []byte(strings.Join(array, "\n")), mode) //fmt.Println("remove line successful") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/statistic.go
ctl/statistic.go
package main import ( "sort" m "github.com/halfrost/LeetCode-Go/ctl/models" "github.com/halfrost/LeetCode-Go/ctl/util" ) func statisticalData(problemsMap map[int]m.StatStatusPairs, solutionIds []int) (easyTotal, mediumTotal, hardTotal, optimizingEasy, optimizingMedium, optimizingHard int32, optimizingIds []int) { easyTotal, mediumTotal, hardTotal, optimizingEasy, optimizingMedium, optimizingHard, optimizingIds = 0, 0, 0, 0, 0, 0, []int{} for _, v := range problemsMap { switch m.DifficultyMap[v.Difficulty.Level] { case "Easy": { easyTotal++ if v.Status == "ac" && util.BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 { optimizingEasy++ optimizingIds = append(optimizingIds, int(v.Stat.FrontendQuestionID)) } } case "Medium": { mediumTotal++ if v.Status == "ac" && util.BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 { optimizingMedium++ optimizingIds = append(optimizingIds, int(v.Stat.FrontendQuestionID)) } } case "Hard": { hardTotal++ if v.Status == "ac" && util.BinarySearch(solutionIds, int(v.Stat.FrontendQuestionID)) == -1 { optimizingHard++ optimizingIds = append(optimizingIds, int(v.Stat.FrontendQuestionID)) } } } } sort.Ints(optimizingIds) return easyTotal, mediumTotal, hardTotal, optimizingEasy, optimizingMedium, optimizingHard, optimizingIds }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/version.go
ctl/version.go
package main import ( "fmt" "github.com/spf13/cobra" ) var ( version = "v1.0" versionCmd = &cobra.Command{ Use: "version", Short: "Prints the version of tacoctl", Run: func(cmd *cobra.Command, args []string) { fmt.Println("tacoctl version:", version) }, } )
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/command.go
ctl/command.go
package main import ( "fmt" "os" "github.com/spf13/cobra" ) var rootCmd = &cobra.Command{ Use: "leetcode-go", Short: "A simple command line client for leetcode-go.", } func execute() { if err := rootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(-1) } } func init() { rootCmd.AddCommand( versionCmd, newBuildCommand(), newLabelCommand(), newPDFCommand(), newRefresh(), ) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/main.go
ctl/main.go
package main func main() { execute() }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/label.go
ctl/label.go
package main import ( "bufio" "errors" "fmt" "io" "io/ioutil" "os" "regexp" "strings" "github.com/halfrost/LeetCode-Go/ctl/util" "github.com/spf13/cobra" ) var ( chapterOneFileOrder = []string{"_index", "Data_Structure", "Algorithm", "Time_Complexity"} chapterOneMenuOrder = []string{"_index", "#关于作者", "Data_Structure", "Algorithm", "Time_Complexity"} chapterTwoFileOrder = []string{"_index", "Array", "String", "Two_Pointers", "Linked_List", "Stack", "Tree", "Dynamic_Programming", "Backtracking", "Depth_First_Search", "Breadth_First_Search", "Binary_Search", "Math", "Hash_Table", "Sorting", "Bit_Manipulation", "Union_Find", "Sliding_Window", "Segment_Tree", "Binary_Indexed_Tree"} chapterThreeFileOrder = []string{"_index", "Segment_Tree", "UnionFind", "LRUCache", "LFUCache"} preNextHeader = "----------------------------------------------\n<div style=\"display: flex;justify-content: space-between;align-items: center;\">\n" preNextFotter = "</div>" delLine = "----------------------------------------------\n" delHeader = "<div style=\"display: flex;justify-content: space-between;align-items: center;\">" delLabel = "<[a-zA-Z]+.*?>([\\s\\S]*?)</[a-zA-Z]*?>" delFooter = "</div>" //ErrNoFilename is thrown when the path the the file to tail was not given ErrNoFilename = errors.New("You must provide the path to a file in the \"-file\" flag.") //ErrInvalidLineCount is thrown when the user provided 0 (zero) as the value for number of lines to tail ErrInvalidLineCount = errors.New("You cannot tail zero lines.") chapterMap = map[string]map[string]string{ "ChapterOne": { "_index": "第一章 序章", "Data_Structure": "1.1 数据结构知识", "Algorithm": "1.2 算法知识", "Time_Complexity": "1.3 时间复杂度", }, "ChapterTwo": { "_index": "第二章 算法专题", "Array": "2.01 Array", "String": "2.02 String", "Two_Pointers": "2.03 ✅ Two Pointers", "Linked_List": "2.04 ✅ Linked List", "Stack": "2.05 ✅ Stack", "Tree": "2.06 Tree", "Dynamic_Programming": "2.07 Dynamic Programming", "Backtracking": "2.08 ✅ Backtracking", "Depth_First_Search": "2.09 Depth First Search", "Breadth_First_Search": "2.10 Breadth First Search", "Binary_Search": "2.11 Binary Search", "Math": "2.12 Math", "Hash_Table": "2.13 Hash Table", "Sorting": "2.14 ✅ Sorting", "Bit_Manipulation": "2.15 ✅ Bit Manipulation", "Union_Find": "2.16 ✅ Union Find", "Sliding_Window": "2.17 ✅ Sliding Window", "Segment_Tree": "2.18 ✅ Segment Tree", "Binary_Indexed_Tree": "2.19 ✅ Binary Indexed Tree", }, "ChapterThree": { "_index": "第三章 一些模板", "Segment_Tree": "3.1 Segment Tree", "UnionFind": "3.2 UnionFind", "LRUCache": "3.3 LRUCache", "LFUCache": "3.4 LFUCache", }, "ChapterFour": { "_index": "第四章 Leetcode 题解", }, } ) func getChapterFourFileOrder() ([]string, []int) { solutions, solutionIds := util.LoadChapterFourDir() chapterFourFileOrder := []string{"_index"} chapterFourFileOrder = append(chapterFourFileOrder, solutions...) fmt.Printf("ChapterFour 中包括 _index 有 %v 个文件, len(id) = %v\n", len(chapterFourFileOrder), len(solutionIds)) return chapterFourFileOrder, solutionIds } func newLabelCommand() *cobra.Command { mc := &cobra.Command{ Use: "label <subcommand>", Short: "Label related commands", } //mc.PersistentFlags().StringVar(&logicEndpoint, "endpoint", "localhost:5880", "endpoint of logic service") mc.AddCommand( newAddPreNext(), newDeletePreNext(), ) return mc } func newAddPreNext() *cobra.Command { cmd := &cobra.Command{ Use: "add-pre-next", Short: "Add pre-next label", Run: func(cmd *cobra.Command, args []string) { addPreNext() }, } // cmd.Flags().StringVar(&alias, "alias", "", "alias") // cmd.Flags().StringVar(&appId, "appid", "", "appid") return cmd } func newDeletePreNext() *cobra.Command { cmd := &cobra.Command{ Use: "del-pre-next", Short: "Delete pre-next label", Run: func(cmd *cobra.Command, args []string) { delPreNext() }, } // cmd.Flags().StringVar(&alias, "alias", "", "alias") // cmd.Flags().StringVar(&appId, "appid", "", "appid") return cmd } func addPreNext() { // Chpater one add pre-next addPreNextLabel(chapterOneFileOrder, []string{}, []int{}, "", "ChapterOne", "ChapterTwo") // Chpater two add pre-next addPreNextLabel(chapterTwoFileOrder, chapterOneFileOrder, []int{}, "ChapterOne", "ChapterTwo", "ChapterThree") // Chpater three add pre-next addPreNextLabel(chapterThreeFileOrder, chapterTwoFileOrder, []int{}, "ChapterTwo", "ChapterThree", "ChapterFour") // Chpater four add pre-next //fmt.Printf("%v\n", getChapterFourFileOrder()) chapterFourFileOrder, solutionIds := getChapterFourFileOrder() addPreNextLabel(chapterFourFileOrder, chapterThreeFileOrder, solutionIds, "ChapterThree", "ChapterFour", "") } func addPreNextLabel(order, preOrder []string, chapterFourIds []int, preChapter, chapter, nextChapter string) { var ( exist bool err error res []byte count int ) for index, path := range order { tmp := "" if index == 0 { if chapter == "ChapterOne" { // 第一页不需要“上一章” tmp = "\n\n" + delLine + fmt.Sprintf("<p align = \"right\"><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">下一页➡️</a></p>\n", chapter, order[index+1]) } else { if chapter == "ChapterFour" { tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">⬅️上一章</a></p>\n", preChapter, preOrder[len(preOrder)-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">下一页➡️</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)+1]), order[index+1]) + preNextFotter } else { tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">⬅️上一章</a></p>\n", preChapter, preOrder[len(preOrder)-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">下一页➡️</a></p>\n", chapter, order[index+1]) + preNextFotter } } } else if index == len(order)-1 { if chapter == "ChapterFour" { // 最后一页不需要“下一页” tmp = "\n\n" + delLine + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">⬅️上一页</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)-1]), order[index-1]) } else { tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">⬅️上一页</a></p>\n", chapter, order[index-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/\">下一章➡️</a></p>\n", nextChapter) + preNextFotter } } else if index == 1 { if chapter == "ChapterFour" { tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/\">⬅️上一页</a></p>\n", chapter) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">下一页➡️</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)+1]), order[index+1]) + preNextFotter } else { tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/\">⬅️上一页</a></p>\n", chapter) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">下一页➡️</a></p>\n", chapter, order[index+1]) + preNextFotter } } else { if chapter == "ChapterFour" { tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">⬅️上一页</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)-1]), order[index-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/%v/\">下一页➡️</a></p>\n", chapter, util.GetChpaterFourFileNum(chapterFourIds[(index-1)+1]), order[index+1]) + preNextFotter } else { tmp = "\n\n" + preNextHeader + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">⬅️上一页</a></p>\n", chapter, order[index-1]) + fmt.Sprintf("<p><a href=\"https://books.halfrost.com/leetcode/%v/%v/\">下一页➡️</a></p>\n", chapter, order[index+1]) + preNextFotter } } if chapter == "ChapterFour" && index > 0 { path = fmt.Sprintf("%v/%v", util.GetChpaterFourFileNum(chapterFourIds[(index-1)]), path) } exist, err = needAdd(fmt.Sprintf("../website/content/%v/%v.md", chapter, path)) if err != nil { fmt.Println(err) return } // 当前没有上一页和下一页,才添加 if !exist && err == nil { res, err = eofAdd(fmt.Sprintf("../website/content/%v/%v.md", chapter, path), tmp) if err != nil { fmt.Println(err) return } util.WriteFile(fmt.Sprintf("../website/content/%v/%v.md", chapter, path), res) count++ } } fmt.Printf("添加了 %v 个文件的 pre-next\n", count) } func eofAdd(filePath string, labelString string) ([]byte, error) { f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) if err != nil { return nil, err } defer f.Close() reader, output := bufio.NewReader(f), []byte{} for { line, _, err := reader.ReadLine() if err != nil { if err == io.EOF { output = append(output, []byte(labelString)...) output = append(output, []byte("\n")...) return output, nil } return nil, err } output = append(output, line...) output = append(output, []byte("\n")...) } } func delPreNext() { // Chpater one del pre-next delPreNextLabel(chapterOneFileOrder, []int{}, "ChapterOne") // Chpater two del pre-next delPreNextLabel(chapterTwoFileOrder, []int{}, "ChapterTwo") // Chpater three del pre-next delPreNextLabel(chapterThreeFileOrder, []int{}, "ChapterThree") // Chpater four del pre-next chapterFourFileOrder, solutionIds := getChapterFourFileOrder() delPreNextLabel(chapterFourFileOrder, solutionIds, "ChapterFour") } func delPreNextLabel(order []string, chapterFourIds []int, chapter string) { count := 0 for index, path := range order { lineNum := 5 if index == 0 && chapter == "ChapterOne" || index == len(order)-1 && chapter == "ChapterFour" { lineNum = 3 } if chapter == "ChapterFour" && index > 0 { path = fmt.Sprintf("%v/%v", util.GetChpaterFourFileNum(chapterFourIds[(index-1)]), path) } exist, err := needAdd(fmt.Sprintf("../website/content/%v/%v.md", chapter, path)) if err != nil { fmt.Println(err) return } // 存在才删除 if exist && err == nil { removeLine(fmt.Sprintf("../website/content/%v/%v.md", chapter, path), lineNum+1) count++ } } fmt.Printf("删除了 %v 个文件的 pre-next\n", count) // 另外一种删除方法 // res, err := eofDel(fmt.Sprintf("../website/content/ChapterOne/%v.md", v)) // if err != nil { // fmt.Println(err) // return // } // util.WriteFile(fmt.Sprintf("../website/content/ChapterOne/%v.md", v), res) } func needAdd(filePath string) (bool, error) { f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) if err != nil { return false, err } defer f.Close() reader, output := bufio.NewReader(f), []byte{} for { line, _, err := reader.ReadLine() if err != nil { if err == io.EOF { return false, nil } return false, err } if ok, _ := regexp.Match(delHeader, line); ok { return true, nil } else if ok, _ := regexp.Match(delLabel, line); ok { return true, nil } else { output = append(output, line...) output = append(output, []byte("\n")...) } } } func eofDel(filePath string) ([]byte, error) { f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) if err != nil { return nil, err } defer f.Close() reader, output := bufio.NewReader(f), []byte{} for { line, _, err := reader.ReadLine() if err != nil { if err == io.EOF { return output, nil } return nil, err } if ok, _ := regexp.Match(delLine, line); ok { reg := regexp.MustCompile(delLine) newByte := reg.ReplaceAll(line, []byte("")) output = append(output, newByte...) output = append(output, []byte("\n")...) } else if ok, _ := regexp.Match(delHeader, line); ok { reg := regexp.MustCompile(delHeader) newByte := reg.ReplaceAll(line, []byte("")) output = append(output, newByte...) output = append(output, []byte("\n")...) } else if ok, _ := regexp.Match(delLabel, line); ok { reg := regexp.MustCompile(delLabel) newByte := reg.ReplaceAll(line, []byte("")) output = append(output, newByte...) output = append(output, []byte("\n")...) } else if ok, _ := regexp.Match(delFooter, line); ok { reg := regexp.MustCompile(delFooter) newByte := reg.ReplaceAll(line, []byte("")) output = append(output, newByte...) output = append(output, []byte("\n")...) } else { output = append(output, line...) output = append(output, []byte("\n")...) } } } func removeLine(path string, lineNumber int) { file, err := ioutil.ReadFile(path) if err != nil { panic(err) } info, _ := os.Stat(path) mode := info.Mode() array := strings.Split(string(file), "\n") array = array[:len(array)-lineNumber-1] ioutil.WriteFile(path, []byte(strings.Join(array, "\n")), mode) //fmt.Println("remove line successful") }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/util/util.go
ctl/util/util.go
package util import ( "bufio" "fmt" "io" "io/ioutil" "os" "path/filepath" "sort" "strconv" "strings" ) // LoadSolutionsDir define func LoadSolutionsDir() ([]int, []string, int) { solutionIds, soNames, total := loadFile("../leetcode/") fmt.Printf("读取了 %v 道题的题解,当前目录下有 %v 个文件(可能包含 .DS_Store),目录中有 %v 道题在尝试中\n", len(solutionIds), total, total-len(solutionIds)) return solutionIds, soNames, total - len(solutionIds) } func loadFile(path string) ([]int, []string, int) { files, err := ioutil.ReadDir(path) if err != nil { fmt.Println(err) } solutionIds, soNames, solutionsMap := []int{}, []string{}, map[int]string{} for _, f := range files { if f.Name()[4] == '.' { tmp, err := strconv.Atoi(f.Name()[:4]) if err != nil { fmt.Println(err) } solutionIds = append(solutionIds, tmp) solutionsMap[tmp] = f.Name() } } sort.Ints(solutionIds) for _, v := range solutionIds { if name, ok := solutionsMap[v]; ok { soNames = append(soNames, name) } } return solutionIds, soNames, len(files) } // GetAllFile define func GetAllFile(pathname string, fileList *[]string) ([]string, error) { rd, err := ioutil.ReadDir(pathname) for _, fi := range rd { if fi.IsDir() { //fmt.Printf("[%s]\n", pathname+"\\"+fi.Name()) GetAllFile(pathname+fi.Name()+"/", fileList) } else { //fmt.Println(fi.Name()) *fileList = append(*fileList, fi.Name()) } } return *fileList, err } // LoadChapterFourDir define func LoadChapterFourDir() ([]string, []int) { files, err := GetAllFile("../website/content/ChapterFour/", &[]string{}) // files, err := ioutil.ReadDir("../website/content/ChapterFour/") if err != nil { fmt.Println(err) } solutions, solutionIds, solutionsMap := []string{}, []int{}, map[int]string{} for _, f := range files { if f[4] == '.' { tmp, err := strconv.Atoi(f[:4]) if err != nil { fmt.Println(err) } solutionIds = append(solutionIds, tmp) // len(f.Name())-3 = 文件名去掉 .md 后缀 solutionsMap[tmp] = f[:len(f)-3] } } sort.Ints(solutionIds) fmt.Printf("读取了第四章的 %v 道题的题解\n", len(solutionIds)) for _, v := range solutionIds { if name, ok := solutionsMap[v]; ok { solutions = append(solutions, name) } } return solutions, solutionIds } // WriteFile define func WriteFile(fileName string, content []byte) { file, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0777) if err != nil { fmt.Println(err) } defer file.Close() _, err = file.Write(content) if err != nil { fmt.Println(err) } //fmt.Println("write file successful") } // LoadFile define func LoadFile(filePath string) ([]byte, error) { f, err := os.OpenFile(filePath, os.O_RDONLY, 0644) if err != nil { return nil, err } defer f.Close() reader, output := bufio.NewReader(f), []byte{} for { line, _, err := reader.ReadLine() if err != nil { if err == io.EOF { return output, nil } return nil, err } output = append(output, line...) output = append(output, []byte("\n")...) } } // DestoryDir define func DestoryDir(path string) { filepath.Walk(path, func(path string, fi os.FileInfo, err error) error { if nil == fi { return err } if !fi.IsDir() { return nil } name := fi.Name() if strings.Contains(name, "temp") { fmt.Println("temp file name:", path) err := os.RemoveAll(path) if err != nil { fmt.Println("delet dir error:", err) } } return nil }) } // CopyFile define func CopyFile(dstName, srcName string) (written int64, err error) { src, err := os.Open(srcName) if err != nil { return } defer src.Close() dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644) if err != nil { return } defer dst.Close() return io.Copy(dst, src) } // BinarySearch define func BinarySearch(nums []int, target int) int { low, high := 0, len(nums)-1 for low <= high { mid := low + (high-low)>>1 if nums[mid] == target { return mid } else if nums[mid] > target { high = mid - 1 } else { low = mid + 1 } } return -1 } // GetChpaterFourFileNum define func GetChpaterFourFileNum(num int) string { if num < 100 { return fmt.Sprintf("%04d~%04d", (num/100)*100+1, (num/100)*100+99) } return fmt.Sprintf("%04d~%04d", (num/100)*100, (num/100)*100+99) }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/models/tagproblem.go
ctl/models/tagproblem.go
package models import ( "encoding/json" "fmt" "strconv" "strings" "github.com/halfrost/LeetCode-Go/ctl/util" ) // Graphql define type Graphql struct { OperationName string `json:"operationName"` Variables struct { TitleSlug string `json:"titleSlug"` } `json:"variables"` Query string `json:"query"` } // GraphQLResp define type GraphQLResp struct { Data struct { TopicTag TopicTag `json:"topicTag"` FavoritesLists FavoritesLists `json:"favoritesLists"` } `json:"data"` } // TopicTag define type TopicTag struct { Name string `json:"name"` TranslatedName string `json:"translatedName"` Slug string `json:"slug"` Questions []Question `json:"questions"` Frequencies string `json:"frequencies"` Typename string `json:"__typename"` } // Question define type Question struct { Status string `json:"status"` QuestionID string `json:"questionId"` QuestionFrontendID string `json:"questionFrontendId"` Title string `json:"title"` TitleSlug string `json:"titleSlug"` TranslatedTitle string `json:"translatedTitle"` Stats string `json:"stats"` Difficulty string `json:"difficulty"` TopicTags []TopicTags `json:"topicTags"` CompanyTags interface{} `json:"companyTags"` Typename string `json:"__typename"` } // TopicTags define type TopicTags struct { Name string `json:"name"` TranslatedName string `json:"translatedName"` Slug string `json:"slug"` Typename string `json:"__typename"` } func (q Question) generateTagStatus() (TagStatus, error) { var ts TagStatus err := json.Unmarshal([]byte(q.Stats), &ts) if err != nil { fmt.Println(err) return ts, err } return ts, nil } // TagStatus define type TagStatus struct { TotalAccepted string `json:"totalAccepted"` TotalSubmission string `json:"totalSubmission"` TotalAcceptedRaw int32 `json:"totalAcceptedRaw"` TotalSubmissionRaw int32 `json:"totalSubmissionRaw"` AcRate string `json:"acRate"` } // ConvertMdModelFromQuestions define func ConvertMdModelFromQuestions(questions []Question) []Mdrow { mdrows := []Mdrow{} for _, question := range questions { res := Mdrow{} v, _ := strconv.Atoi(question.QuestionFrontendID) res.FrontendQuestionID = int32(v) res.QuestionTitle = strings.TrimSpace(question.Title) res.QuestionTitleSlug = strings.TrimSpace(question.TitleSlug) q, err := question.generateTagStatus() if err != nil { fmt.Println(err) } res.Acceptance = q.AcRate res.Difficulty = question.Difficulty mdrows = append(mdrows, res) } return mdrows } // TagList define type TagList struct { FrontendQuestionID int32 `json:"question_id"` QuestionTitle string `json:"question__title"` SolutionPath string `json:"solution_path"` Acceptance string `json:"acceptance"` Difficulty string `json:"difficulty"` TimeComplexity string `json:"time_complexity"` SpaceComplexity string `json:"space_complexity"` Favorite string `json:"favorite"` } // | 0001 | Two Sum | [Go]({{< relref "/ChapterFour/0001.Two-Sum.md" >}})| Easy | O(n)| O(n)|❤️|50%| func (t TagList) tableLine() string { return fmt.Sprintf("|%04d|%v|%v|%v|%v|%v|%v|%v|\n", t.FrontendQuestionID, t.QuestionTitle, t.SolutionPath, t.Difficulty, t.TimeComplexity, t.SpaceComplexity, t.Favorite, t.Acceptance) } func standardizedTitle(orig string, frontendQuestionID int32) string { s0 := strings.TrimSpace(orig) s1 := strings.Replace(s0, " ", "-", -1) s2 := strings.Replace(s1, "'", "", -1) s3 := strings.Replace(s2, "%", "", -1) s4 := strings.Replace(s3, "(", "", -1) s5 := strings.Replace(s4, ")", "", -1) s6 := strings.Replace(s5, ",", "", -1) s7 := strings.Replace(s6, "?", "", -1) count := 0 // 去掉 --- 这种情况,这种情况是由于题目标题中包含 - ,左右有空格,左右一填充,造成了 ---,3 个 - for i := 0; i < len(s7)-2; i++ { if s7[i] == '-' && s7[i+1] == '-' && s7[i+2] == '-' { fmt.Printf("【需要修正 --- 的标题是 %v】\n", fmt.Sprintf("%04d.%v", int(frontendQuestionID), s7)) s7 = s7[:i+1] + s7[i+3:] count++ } } if count > 0 { fmt.Printf("总共修正了 %v 个标题\n", count) } // 去掉 -- 这种情况,这种情况是由于题目标题中包含负号 - for i := 0; i < len(s7)-2; i++ { if s7[i] == '-' && s7[i+1] == '-' { fmt.Printf("【需要修正 -- 的标题是 %v】\n", fmt.Sprintf("%04d.%v", int(frontendQuestionID), s7)) s7 = s7[:i+1] + s7[i+2:] count++ } } if count > 0 { fmt.Printf("总共修正了 %v 个标题\n", count) } return s7 } // GenerateTagMdRows define func GenerateTagMdRows(solutionIds []int, metaMap map[int]TagList, mdrows []Mdrow, internal bool) []TagList { tl := []TagList{} for _, row := range mdrows { if util.BinarySearch(solutionIds, int(row.FrontendQuestionID)) != -1 { tmp := TagList{} tmp.FrontendQuestionID = row.FrontendQuestionID tmp.QuestionTitle = strings.TrimSpace(row.QuestionTitle) s7 := standardizedTitle(row.QuestionTitle, row.FrontendQuestionID) if internal { tmp.SolutionPath = fmt.Sprintf("[Go]({{< relref \"/ChapterFour/%v/%v.md\" >}})", util.GetChpaterFourFileNum(int(row.FrontendQuestionID)), fmt.Sprintf("%04d.%v", int(row.FrontendQuestionID), s7)) } else { tmp.SolutionPath = fmt.Sprintf("[Go](https://books.halfrost.com/leetcode/ChapterFour/%v/%v)", util.GetChpaterFourFileNum(int(row.FrontendQuestionID)), fmt.Sprintf("%04d.%v", int(row.FrontendQuestionID), s7)) } tmp.Acceptance = row.Acceptance tmp.Difficulty = row.Difficulty tmp.TimeComplexity = metaMap[int(row.FrontendQuestionID)].TimeComplexity tmp.SpaceComplexity = metaMap[int(row.FrontendQuestionID)].SpaceComplexity tmp.Favorite = metaMap[int(row.FrontendQuestionID)].Favorite tl = append(tl, tmp) } } return tl } // TagLists define type TagLists struct { TagLists []TagList } // | No. | Title | Solution | Difficulty | TimeComplexity | SpaceComplexity |Favorite| Acceptance | // |:--------:|:------- | :--------: | :----------: | :----: | :-----: | :-----: |:-----: | func (tls TagLists) table() string { res := "| No. | Title | Solution | Difficulty | TimeComplexity | SpaceComplexity |Favorite| Acceptance |\n" res += "|:--------:|:------- | :--------: | :----------: | :----: | :-----: | :-----: |:-----: |\n" for _, p := range tls.TagLists { res += p.tableLine() } // 加这一行是为了撑开整个表格 res += "|------------|-------------------------------------------------------|-------| ----------------| ---------------|-------------|-------------|-------------|" return res } // AvailableTagTable define func (tls TagLists) AvailableTagTable() string { return tls.table() } // FavoritesLists define type FavoritesLists struct { PublicFavorites []int `json:"publicFavorites"` PrivateFavorites []struct { IDHash string `json:"idHash"` ID string `json:"id"` Name string `json:"name"` IsPublicFavorite bool `json:"isPublicFavorite"` ViewCount int `json:"viewCount"` Creator string `json:"creator"` IsWatched bool `json:"isWatched"` Questions []struct { QuestionID string `json:"questionId"` Title string `json:"title"` TitleSlug string `json:"titleSlug"` Typename string `json:"__typename"` } `json:"questions"` Typename string `json:"__typename"` } `json:"privateFavorites"` Typename string `json:"__typename"` } // Gproblem define type Gproblem struct { QuestionID string `json:"questionId"` QuestionFrontendID string `json:"questionFrontendId"` BoundTopicID int `json:"boundTopicId"` Title string `json:"title"` TitleSlug string `json:"titleSlug"` Content string `json:"content"` TranslatedTitle string `json:"translatedTitle"` TranslatedContent string `json:"translatedContent"` IsPaidOnly bool `json:"isPaidOnly"` Difficulty string `json:"difficulty"` Likes int `json:"likes"` Dislikes int `json:"dislikes"` IsLiked interface{} `json:"isLiked"` SimilarQuestions string `json:"similarQuestions"` Contributors []interface{} `json:"contributors"` LangToValidPlayground string `json:"langToValidPlayground"` TopicTags []struct { Name string `json:"name"` Slug string `json:"slug"` TranslatedName string `json:"translatedName"` Typename string `json:"__typename"` } `json:"topicTags"` CompanyTagStats interface{} `json:"companyTagStats"` CodeSnippets []GcodeSnippet `json:"codeSnippets"` Stats string `json:"stats"` Hints []interface{} `json:"hints"` Solution interface{} `json:"solution"` Status interface{} `json:"status"` SampleTestCase string `json:"sampleTestCase"` MetaData string `json:"metaData"` JudgerAvailable bool `json:"judgerAvailable"` JudgeType string `json:"judgeType"` MysqlSchemas []interface{} `json:"mysqlSchemas"` EnableRunCode bool `json:"enableRunCode"` EnableTestMode bool `json:"enableTestMode"` EnvInfo string `json:"envInfo"` Typename string `json:"__typename"` } // Gstat define type Gstat struct { TotalAcs int `json:"total_acs"` QuestionTitle string `json:"question__title"` IsNewQuestion bool `json:"is_new_question"` QuestionArticleSlug string `json:"question__article__slug"` TotalSubmitted int `json:"total_submitted"` FrontendQuestionID int `json:"frontend_question_id"` QuestionTitleSlug string `json:"question__title_slug"` QuestionArticleLive bool `json:"question__article__live"` QuestionHide bool `json:"question__hide"` QuestionID int `json:"question_id"` } // GcodeSnippet define type GcodeSnippet struct { Lang string `json:"lang"` LangSlug string `json:"langSlug"` Code string `json:"code"` Typename string `json:"__typename"` }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/models/lcproblems.go
ctl/models/lcproblems.go
package models import ( "fmt" "strings" ) // LeetCodeProblemAll define type LeetCodeProblemAll struct { UserName string `json:"user_name"` NumSolved int32 `json:"num_solved"` NumTotal int32 `json:"num_total"` AcEasy int32 `json:"ac_easy"` AcMedium int32 `json:"ac_medium"` AcHard int32 `json:"ac_hard"` StatStatusPairs []StatStatusPairs `json:"stat_status_pairs"` FrequencyHigh float64 `json:"frequency_high"` FrequencyMid float64 `json:"frequency_mid"` CategorySlug string `json:"category_slug"` AcEasyTotal int32 AcMediumTotal int32 AcHardTotal int32 } // ConvertUserInfoModel define func ConvertUserInfoModel(lpa LeetCodeProblemAll) UserInfo { info := UserInfo{} info.UserName = lpa.UserName info.NumSolved = lpa.NumSolved info.NumTotal = lpa.NumTotal info.AcEasy = lpa.AcEasy info.AcMedium = lpa.AcMedium info.AcHard = lpa.AcHard info.FrequencyHigh = lpa.FrequencyHigh info.FrequencyMid = lpa.FrequencyMid info.CategorySlug = lpa.CategorySlug return info } // StatStatusPairs define type StatStatusPairs struct { Stat Stat `json:"stat"` Status string `json:"status"` Difficulty Difficulty `json:"difficulty"` PaidOnly bool `json:"paid_only"` IsFavor bool `json:"is_favor"` Frequency float64 `json:"frequency"` Progress float64 `json:"progress"` } // ConvertMdModelFromSsp define func ConvertMdModelFromSsp(problems []StatStatusPairs) []Mdrow { mdrows := []Mdrow{} for _, problem := range problems { res := Mdrow{} res.FrontendQuestionID = problem.Stat.FrontendQuestionID res.QuestionTitle = strings.TrimSpace(problem.Stat.QuestionTitle) res.QuestionTitleSlug = strings.TrimSpace(problem.Stat.QuestionTitleSlug) res.Acceptance = fmt.Sprintf("%.1f%%", (problem.Stat.TotalAcs/problem.Stat.TotalSubmitted)*100) res.Difficulty = DifficultyMap[problem.Difficulty.Level] res.Frequency = fmt.Sprintf("%f", problem.Frequency) mdrows = append(mdrows, res) } return mdrows } // ConvertMdModelFromIds define func ConvertMdModelFromIds(problemsMap map[int]StatStatusPairs, ids []int) []Mdrow { mdrows := []Mdrow{} for _, v := range ids { res, problem := Mdrow{}, problemsMap[v] res.FrontendQuestionID = problem.Stat.FrontendQuestionID res.QuestionTitle = strings.TrimSpace(problem.Stat.QuestionTitle) res.QuestionTitleSlug = strings.TrimSpace(problem.Stat.QuestionTitleSlug) res.Acceptance = fmt.Sprintf("%.1f%%", (problem.Stat.TotalAcs/problem.Stat.TotalSubmitted)*100) res.Difficulty = DifficultyMap[problem.Difficulty.Level] res.Frequency = fmt.Sprintf("%f", problem.Frequency) mdrows = append(mdrows, res) } return mdrows } // Stat define type Stat struct { QuestionTitle string `json:"question__title"` QuestionTitleSlug string `json:"question__title_slug"` TotalAcs float64 `json:"total_acs"` TotalSubmitted float64 `json:"total_submitted"` Acceptance string Difficulty string FrontendQuestionID int32 `json:"frontend_question_id"` } // Difficulty define type Difficulty struct { Level int32 `json:"level"` } // DifficultyMap define var DifficultyMap = map[int32]string{ 1: "Easy", 2: "Medium", 3: "Hard", }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/models/user.go
ctl/models/user.go
package models import ( "fmt" ) // UserInfo define type UserInfo struct { UserName string `json:"user_name"` NumSolved int32 `json:"num_solved"` NumTotal int32 `json:"num_total"` AcEasy int32 `json:"ac_easy"` AcMedium int32 `json:"ac_medium"` AcHard int32 `json:"ac_hard"` EasyTotal int32 MediumTotal int32 HardTotal int32 OptimizingEasy int32 OptimizingMedium int32 OptimizingHard int32 FrequencyHigh float64 `json:"frequency_high"` FrequencyMid float64 `json:"frequency_mid"` CategorySlug string `json:"category_slug"` } // | | Easy | Medium | Hard | Total | optimizing | // |:--------:|:--------------------------------------------------------------|:--------:|:--------:|:--------:|:--------:| func (ui UserInfo) table() string { res := "| | Easy | Medium | Hard | Total |\n" res += "|:--------:|:--------:|:--------:|:--------:|:--------:|\n" res += fmt.Sprintf("|Optimizing|%v|%v|%v|%v|\n", ui.OptimizingEasy, ui.OptimizingMedium, ui.OptimizingHard, ui.OptimizingEasy+ui.OptimizingMedium+ui.OptimizingHard) res += fmt.Sprintf("|Accepted|**%v**|**%v**|**%v**|**%v**|\n", ui.AcEasy, ui.AcMedium, ui.AcHard, ui.AcEasy+ui.AcMedium+ui.AcHard) res += fmt.Sprintf("|Total|%v|%v|%v|%v|\n", ui.EasyTotal, ui.MediumTotal, ui.HardTotal, ui.EasyTotal+ui.MediumTotal+ui.HardTotal) res += fmt.Sprintf("|Perfection Rate|%.1f%%|%.1f%%|%.1f%%|%.1f%%|\n", (1-float64(ui.OptimizingEasy)/float64(ui.AcEasy))*100, (1-float64(ui.OptimizingMedium)/float64(ui.AcMedium))*100, (1-float64(ui.OptimizingHard)/float64(ui.AcHard))*100, (1-float64(ui.OptimizingEasy+ui.OptimizingMedium+ui.OptimizingHard)/float64(ui.AcEasy+ui.AcMedium+ui.AcHard))*100) res += fmt.Sprintf("|Completion Rate|%.1f%%|%.1f%%|%.1f%%|%.1f%%|\n", float64(ui.AcEasy)/float64(ui.EasyTotal)*100, float64(ui.AcMedium)/float64(ui.MediumTotal)*100, float64(ui.AcHard)/float64(ui.HardTotal)*100, float64(ui.AcEasy+ui.AcMedium+ui.AcHard)/float64(ui.EasyTotal+ui.MediumTotal+ui.HardTotal)*100) // 加这一行是为了撑开整个表格 res += "|------------|----------------------------|----------------------------|----------------------------|----------------------------|" return res } // PersonalData define func (ui UserInfo) PersonalData() string { return ui.table() }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/ctl/models/mdrow.go
ctl/models/mdrow.go
package models import ( "fmt" "strings" ) // Mdrow define type Mdrow struct { FrontendQuestionID int32 `json:"question_id"` QuestionTitle string `json:"question__title"` QuestionTitleSlug string `json:"question__title_slug"` SolutionPath string `json:"solution_path"` Acceptance string `json:"acceptance"` Difficulty string `json:"difficulty"` Frequency string `json:"frequency"` } // GenerateMdRows define func GenerateMdRows(solutionIds []int, mdrows []Mdrow) { mdMap := map[int]Mdrow{} for _, row := range mdrows { mdMap[int(row.FrontendQuestionID)] = row } for i := 0; i < len(solutionIds); i++ { if row, ok := mdMap[solutionIds[i]]; ok { s7 := standardizedTitle(row.QuestionTitle, row.FrontendQuestionID) mdMap[solutionIds[i]] = Mdrow{ FrontendQuestionID: row.FrontendQuestionID, QuestionTitle: strings.TrimSpace(row.QuestionTitle), QuestionTitleSlug: row.QuestionTitleSlug, SolutionPath: fmt.Sprintf("[Go](https://github.com/halfrost/leetcode-go/tree/master/leetcode/%v)", fmt.Sprintf("%04d.%v", solutionIds[i], s7)), Acceptance: row.Acceptance, Difficulty: row.Difficulty, Frequency: row.Frequency, } } else { fmt.Printf("序号不存在 len(solutionIds) = %v len(mdrows) = %v len(solutionIds) = %v solutionIds[i] = %v QuestionTitle = %v\n", len(solutionIds), len(mdrows), len(solutionIds), solutionIds[i], mdrows[solutionIds[i]-1].QuestionTitle) } } for i := range mdrows { mdrows[i] = Mdrow{ FrontendQuestionID: mdrows[i].FrontendQuestionID, QuestionTitle: strings.TrimSpace(mdrows[i].QuestionTitle), QuestionTitleSlug: mdrows[i].QuestionTitleSlug, SolutionPath: mdMap[int(mdrows[i].FrontendQuestionID)].SolutionPath, Acceptance: mdrows[i].Acceptance, Difficulty: mdrows[i].Difficulty, Frequency: mdrows[i].Frequency, } } // fmt.Printf("mdrows = %v\n\n", mdrows) } // | 0001 | Two Sum | [Go](https://github.com/halfrost/leetcode-go/tree/master/leetcode/0001.Two-Sum)| 45.6% | Easy | | func (m Mdrow) tableLine() string { return fmt.Sprintf("|%04d|%v|%v|%v|%v||\n", m.FrontendQuestionID, m.QuestionTitle, m.SolutionPath, m.Acceptance, m.Difficulty) } // SortByQuestionID define type SortByQuestionID []Mdrow func (a SortByQuestionID) Len() int { return len(a) } func (a SortByQuestionID) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a SortByQuestionID) Less(i, j int) bool { return a[i].FrontendQuestionID < a[j].FrontendQuestionID } // Mdrows define type Mdrows struct { Mdrows []Mdrow } // | No. | Title | Solution | Acceptance | Difficulty | Frequency | // |:--------:|:--------------------------------------------------------------|:--------:|:--------:|:--------:|:--------:| func (mds Mdrows) table() string { res := "| No. | Title | Solution | Acceptance | Difficulty | Frequency |\n" res += "|:--------:|:--------------------------------------------------------------|:--------:|:--------:|:--------:|:--------:|\n" for _, p := range mds.Mdrows { res += p.tableLine() } // 加这一行是为了撑开整个表格 res += "|------------|-------------------------------------------------------|-------| ----------------| ---------------|-------------|" return res } // AvailableTable define func (mds Mdrows) AvailableTable() string { return mds.table() }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/template/BIT.go
template/BIT.go
package template // BinaryIndexedTree define type BinaryIndexedTree struct { tree []int capacity int } // Init define func (bit *BinaryIndexedTree) Init(capacity int) { bit.tree, bit.capacity = make([]int, capacity+1), capacity } // Add define func (bit *BinaryIndexedTree) Add(index int, val int) { for ; index <= bit.capacity; index += index & -index { bit.tree[index] += val } } // Query define func (bit *BinaryIndexedTree) Query(index int) int { sum := 0 for ; index > 0; index -= index & -index { sum += bit.tree[index] } return sum } // InitWithNums define func (bit *BinaryIndexedTree) InitWithNums(nums []int) { bit.tree, bit.capacity = make([]int, len(nums)+1), len(nums) for i := 1; i <= len(nums); i++ { bit.tree[i] += nums[i-1] for j := i - 2; j >= i-lowbit(i); j-- { bit.tree[i] += nums[j] } } } func lowbit(x int) int { return x & -x } // BinaryIndexedTree2D define type BinaryIndexedTree2D struct { tree [][]int row int col int } // Add define func (bit2 *BinaryIndexedTree2D) Add(i, j int, val int) { for i <= bit2.row { k := j for k <= bit2.col { bit2.tree[i][k] += val k += lowbit(k) } i += lowbit(i) } } // Query define func (bit2 *BinaryIndexedTree2D) Query(i, j int) int { sum := 0 for i >= 1 { k := j for k >= 1 { sum += bit2.tree[i][k] k -= lowbit(k) } i -= lowbit(i) } return sum }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/template/CLRUCache_test.go
template/CLRUCache_test.go
package template import ( "container/list" "math/rand" "strconv" "sync" "testing" "time" "github.com/stretchr/testify/assert" ) func Test_CLRUCache(t *testing.T) { obj := New(2) time.Sleep(150 * time.Millisecond) obj.Put("1", 1) time.Sleep(150 * time.Millisecond) obj.Put("2", 2) time.Sleep(150 * time.Millisecond) param1 := obj.Get("1") time.Sleep(150 * time.Millisecond) assert.Equal(t, 1, param1) obj.Put("3", 3) time.Sleep(150 * time.Millisecond) param1 = obj.Get("2") assert.Equal(t, nil, param1) obj.Put("4", 4) time.Sleep(150 * time.Millisecond) param1 = obj.Get("1") time.Sleep(150 * time.Millisecond) assert.Equal(t, nil, param1) param1 = obj.Get("3") time.Sleep(150 * time.Millisecond) assert.Equal(t, 3, param1) param1 = obj.Get("4") time.Sleep(150 * time.Millisecond) assert.Equal(t, 4, param1) } func MList2Ints(lru *CLRUCache) [][]interface{} { res := [][]interface{}{} for head := lru.list.Front(); head != nil; head = head.Next() { tmp := []interface{}{head.Value.(Pair).key, head.Value.(Pair).value} res = append(res, tmp) } return res } func BenchmarkGetAndPut1(b *testing.B) { b.ResetTimer() obj := New(128) wg := sync.WaitGroup{} wg.Add(b.N * 2) for i := 0; i < b.N; i++ { go func() { defer wg.Done() obj.Get(strconv.Itoa(rand.Intn(200))) }() go func() { defer wg.Done() obj.Put(strconv.Itoa(rand.Intn(200)), strconv.Itoa(rand.Intn(200))) }() } wg.Wait() } type Cache struct { sync.RWMutex Cap int Keys map[string]*list.Element List *list.List } type pair struct { K, V string } func NewLRUCache(capacity int) Cache { return Cache{ Cap: capacity, Keys: make(map[string]*list.Element), List: list.New(), } } func (c *Cache) Get(key string) interface{} { c.Lock() if el, ok := c.Keys[key]; ok { c.List.MoveToFront(el) return el.Value.(pair).V } c.Unlock() return nil } func (c *Cache) Put(key string, value string) { c.Lock() if el, ok := c.Keys[key]; ok { el.Value = pair{K: key, V: value} c.List.MoveToFront(el) } else { el := c.List.PushFront(pair{K: key, V: value}) c.Keys[key] = el } if c.List.Len() > c.Cap { el := c.List.Back() c.List.Remove(el) delete(c.Keys, el.Value.(pair).K) } c.Unlock() } func BenchmarkGetAndPut2(b *testing.B) { b.ResetTimer() obj := NewLRUCache(128) wg := sync.WaitGroup{} wg.Add(b.N * 2) for i := 0; i < b.N; i++ { go func() { defer wg.Done() obj.Get(strconv.Itoa(rand.Intn(200))) }() go func() { defer wg.Done() obj.Put(strconv.Itoa(rand.Intn(200)), strconv.Itoa(rand.Intn(200))) }() } wg.Wait() }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/template/LFUCache.go
template/LFUCache.go
package template import "container/list" // LFUCache define type LFUCache struct { nodes map[int]*list.Element lists map[int]*list.List capacity int min int } type node struct { key int value int frequency int } // Constructor define func Constructor(capacity int) LFUCache { return LFUCache{nodes: make(map[int]*list.Element), lists: make(map[int]*list.List), capacity: capacity, min: 0, } } // Get define func (lfuCache *LFUCache) Get(key int) int { value, ok := lfuCache.nodes[key] if !ok { return -1 } currentNode := value.Value.(*node) lfuCache.lists[currentNode.frequency].Remove(value) currentNode.frequency++ if _, ok := lfuCache.lists[currentNode.frequency]; !ok { lfuCache.lists[currentNode.frequency] = list.New() } newList := lfuCache.lists[currentNode.frequency] newNode := newList.PushFront(currentNode) lfuCache.nodes[key] = newNode if currentNode.frequency-1 == lfuCache.min && lfuCache.lists[currentNode.frequency-1].Len() == 0 { lfuCache.min++ } return currentNode.value } // Put define func (lfuCache *LFUCache) Put(key int, value int) { if lfuCache.capacity == 0 { return } if currentValue, ok := lfuCache.nodes[key]; ok { currentNode := currentValue.Value.(*node) currentNode.value = value lfuCache.Get(key) return } if lfuCache.capacity == len(lfuCache.nodes) { currentList := lfuCache.lists[lfuCache.min] backNode := currentList.Back() delete(lfuCache.nodes, backNode.Value.(*node).key) currentList.Remove(backNode) } lfuCache.min = 1 currentNode := &node{ key: key, value: value, frequency: 1, } if _, ok := lfuCache.lists[1]; !ok { lfuCache.lists[1] = list.New() } newList := lfuCache.lists[1] newNode := newList.PushFront(currentNode) lfuCache.nodes[key] = newNode } /** * Your LFUCache object will be instantiated and called as such: * obj := Constructor(capacity); * param_1 := obj.Get(key); * obj.Put(key,value); */ // Index Priority Queue // import "container/heap" // type LFUCache struct { // capacity int // pq PriorityQueue // hash map[int]*Item // counter int // } // func Constructor(capacity int) LFUCache { // lfu := LFUCache{ // pq: PriorityQueue{}, // hash: make(map[int]*Item, capacity), // capacity: capacity, // } // return lfu // } // func (this *LFUCache) Get(key int) int { // if this.capacity == 0 { // return -1 // } // if item, ok := this.hash[key]; ok { // this.counter++ // this.pq.update(item, item.value, item.frequency+1, this.counter) // return item.value // } // return -1 // } // func (this *LFUCache) Put(key int, value int) { // if this.capacity == 0 { // return // } // // fmt.Printf("Put %d\n", key) // this.counter++ // // 如果存在,增加 frequency,再调整堆 // if item, ok := this.hash[key]; ok { // this.pq.update(item, value, item.frequency+1, this.counter) // return // } // // 如果不存在且缓存满了,需要删除。在 hashmap 和 pq 中删除。 // if len(this.pq) == this.capacity { // item := heap.Pop(&this.pq).(*Item) // delete(this.hash, item.key) // } // // 新建结点,在 hashmap 和 pq 中添加。 // item := &Item{ // value: value, // key: key, // count: this.counter, // } // heap.Push(&this.pq, item) // this.hash[key] = item // } // // An Item is something we manage in a priority queue. // type Item struct { // value int // The value of the item; arbitrary. // key int // frequency int // The priority of the item in the queue. // count int // use for evicting the oldest element // // The index is needed by update and is maintained by the heap.Interface methods. // index int // The index of the item in the heap. // } // // A PriorityQueue implements heap.Interface and holds Items. // type PriorityQueue []*Item // func (pq PriorityQueue) Len() int { return len(pq) } // func (pq PriorityQueue) Less(i, j int) bool { // // We want Pop to give us the highest, not lowest, priority so we use greater than here. // if pq[i].frequency == pq[j].frequency { // return pq[i].count < pq[j].count // } // return pq[i].frequency < pq[j].frequency // } // func (pq PriorityQueue) Swap(i, j int) { // pq[i], pq[j] = pq[j], pq[i] // pq[i].index = i // pq[j].index = j // } // func (pq *PriorityQueue) Push(x interface{}) { // n := len(*pq) // item := x.(*Item) // item.index = n // *pq = append(*pq, item) // } // func (pq *PriorityQueue) Pop() interface{} { // old := *pq // n := len(old) // item := old[n-1] // old[n-1] = nil // avoid memory leak // item.index = -1 // for safety // *pq = old[0 : n-1] // return item // } // // update modifies the priority and value of an Item in the queue. // func (pq *PriorityQueue) update(item *Item, value int, frequency int, count int) { // item.value = value // item.count = count // item.frequency = frequency // heap.Fix(pq, item.index) // }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/template/bucket.go
template/bucket.go
package template import ( "container/list" "sync" ) type bucket struct { sync.RWMutex keys map[string]*list.Element } func (b *bucket) pairCount() int { b.RLock() defer b.RUnlock() return len(b.keys) } func (b *bucket) get(key string) *list.Element { b.RLock() defer b.RUnlock() if el, ok := b.keys[key]; ok { return el } return nil } func (b *bucket) set(key string, value interface{}) (*list.Element, *list.Element) { el := &list.Element{Value: Pair{key: key, value: value, cmd: PushFront}} b.Lock() exist := b.keys[key] b.keys[key] = el b.Unlock() return el, exist } func (b *bucket) update(key string, el *list.Element) { b.Lock() b.keys[key] = el b.Unlock() } func (b *bucket) delete(key string) *list.Element { b.Lock() el := b.keys[key] delete(b.keys, key) b.Unlock() return el } func (b *bucket) clear() { b.Lock() b.keys = make(map[string]*list.Element) b.Unlock() }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/template/LRUCache.go
template/LRUCache.go
package template // LRUCache define type LRUCache struct { head, tail *Node keys map[int]*Node capacity int } // Node define type Node struct { key, val int prev, next *Node } // ConstructorLRU define func ConstructorLRU(capacity int) LRUCache { return LRUCache{keys: make(map[int]*Node), capacity: capacity} } // Get define func (lruCache *LRUCache) Get(key int) int { if node, ok := lruCache.keys[key]; ok { lruCache.Remove(node) lruCache.Add(node) return node.val } return -1 } // Put define func (lruCache *LRUCache) Put(key int, value int) { node, ok := lruCache.keys[key] if ok { node.val = value lruCache.Remove(node) lruCache.Add(node) return } node = &Node{key: key, val: value} lruCache.keys[key] = node lruCache.Add(node) if len(lruCache.keys) > lruCache.capacity { delete(lruCache.keys, lruCache.tail.key) lruCache.Remove(lruCache.tail) } } // Add define func (lruCache *LRUCache) Add(node *Node) { node.prev = nil node.next = lruCache.head if lruCache.head != nil { lruCache.head.prev = node } lruCache.head = node if lruCache.tail == nil { lruCache.tail = node lruCache.tail.next = nil } } // Remove define func (lruCache *LRUCache) Remove(node *Node) { if node == lruCache.head { lruCache.head = node.next if node.next != nil { node.next.prev = nil } node.next = nil return } if node == lruCache.tail { lruCache.tail = node.prev node.prev.next = nil node.prev = nil return } node.prev.next = node.next node.next.prev = node.prev } /** * Your LRUCache object will be instantiated and called as such: * obj := Constructor(capacity); * param_1 := obj.Get(key); * obj.Put(key,value); */ // 22% // import "container/list" // type LRUCache struct { // Cap int // Keys map[int]*list.Element // List *list.List // } // type pair struct { // K, V int // } // func Constructor(capacity int) LRUCache { // return LRUCache{ // Cap: capacity, // Keys: make(map[int]*list.Element), // List: list.New(), // } // } // func (c *LRUCache) Get(key int) int { // if el, ok := c.Keys[key]; ok { // c.List.MoveToFront(el) // return el.Value.(pair).V // } // return -1 // } // func (c *LRUCache) Put(key int, value int) { // if el, ok := c.Keys[key]; ok { // el.Value = pair{K: key, V: value} // c.List.MoveToFront(el) // } else { // el := c.List.PushFront(pair{K: key, V: value}) // c.Keys[key] = el // } // if c.List.Len() > c.Cap { // el := c.List.Back() // c.List.Remove(el) // delete(c.Keys, el.Value.(pair).K) // } // } /** * Your LRUCache object will be instantiated and called as such: * obj := Constructor(capacity); * param_1 := obj.Get(key); * obj.Put(key,value); */
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/template/UnionFind.go
template/UnionFind.go
package template // UnionFind defind // 路径压缩 + 秩优化 type UnionFind struct { parent, rank []int count int } // Init define func (uf *UnionFind) Init(n int) { uf.count = n uf.parent = make([]int, n) uf.rank = make([]int, n) for i := range uf.parent { uf.parent[i] = i } } // Find define func (uf *UnionFind) Find(p int) int { root := p for root != uf.parent[root] { root = uf.parent[root] } // compress path for p != uf.parent[p] { tmp := uf.parent[p] uf.parent[p] = root p = tmp } return root } // Union define func (uf *UnionFind) Union(p, q int) { proot := uf.Find(p) qroot := uf.Find(q) if proot == qroot { return } if uf.rank[qroot] > uf.rank[proot] { uf.parent[proot] = qroot } else { uf.parent[qroot] = proot if uf.rank[proot] == uf.rank[qroot] { uf.rank[proot]++ } } uf.count-- } // TotalCount define func (uf *UnionFind) TotalCount() int { return uf.count } // UnionFindCount define // 计算每个集合中元素的个数 + 最大集合元素个数 type UnionFindCount struct { parent, count []int maxUnionCount int } // Init define func (uf *UnionFindCount) Init(n int) { uf.parent = make([]int, n) uf.count = make([]int, n) for i := range uf.parent { uf.parent[i] = i uf.count[i] = 1 } } // Find define func (uf *UnionFindCount) Find(p int) int { root := p for root != uf.parent[root] { root = uf.parent[root] } return root } // 不进行秩压缩,时间复杂度爆炸,太高了 // func (uf *UnionFindCount) union(p, q int) { // proot := uf.find(p) // qroot := uf.find(q) // if proot == qroot { // return // } // if proot != qroot { // uf.parent[proot] = qroot // uf.count[qroot] += uf.count[proot] // } // } // Union define func (uf *UnionFindCount) Union(p, q int) { proot := uf.Find(p) qroot := uf.Find(q) if proot == qroot { return } if proot == len(uf.parent)-1 { //proot is root } else if qroot == len(uf.parent)-1 { // qroot is root, always attach to root proot, qroot = qroot, proot } else if uf.count[qroot] > uf.count[proot] { proot, qroot = qroot, proot } //set relation[0] as parent uf.maxUnionCount = max(uf.maxUnionCount, (uf.count[proot] + uf.count[qroot])) uf.parent[qroot] = proot uf.count[proot] += uf.count[qroot] } // Count define func (uf *UnionFindCount) Count() []int { return uf.count } // MaxUnionCount define func (uf *UnionFindCount) MaxUnionCount() int { return uf.maxUnionCount } func max(a int, b int) int { if a > b { return a } return b }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/template/BIT_test.go
template/BIT_test.go
package template import ( "fmt" "testing" ) func Test_BIT(t *testing.T) { nums, bit := []int{1, 2, 3, 4, 5, 6, 7, 8}, BinaryIndexedTree{} bit.Init(8) fmt.Printf("nums = %v bit = %v\n", nums, bit.tree) // [0 1 3 3 10 5 11 7 36] }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/template/CLRUCache.go
template/CLRUCache.go
package template import ( "container/list" "hash/fnv" "sync" ) type command int const ( // MoveToFront define MoveToFront command = iota // PushFront define PushFront // Delete define Delete ) type clear struct { done chan struct{} } // CLRUCache define: High Concurrency LRUCache type CLRUCache struct { sync.RWMutex cap int list *list.List buckets []*bucket bucketMask uint32 deletePairs chan *list.Element movePairs chan *list.Element control chan interface{} } // Pair define type Pair struct { key string value interface{} cmd command } // New define func New(capacity int) *CLRUCache { c := &CLRUCache{ cap: capacity, list: list.New(), bucketMask: uint32(1024) - 1, buckets: make([]*bucket, 1024), } for i := 0; i < 1024; i++ { c.buckets[i] = &bucket{ keys: make(map[string]*list.Element), } } c.restart() return c } // Get define func (c *CLRUCache) Get(key string) interface{} { el := c.bucket(key).get(key) if el == nil { return nil } c.move(el) return el.Value.(Pair).value } // Put define func (c *CLRUCache) Put(key string, value interface{}) { el, exist := c.bucket(key).set(key, value) if exist != nil { c.deletePairs <- exist } c.move(el) } func (c *CLRUCache) move(el *list.Element) { select { case c.movePairs <- el: default: } } // Delete define func (c *CLRUCache) Delete(key string) bool { el := c.bucket(key).delete(key) if el != nil { c.deletePairs <- el return true } return false } // Clear define func (c *CLRUCache) Clear() { done := make(chan struct{}) c.control <- clear{done: done} <-done } // Count define func (c *CLRUCache) Count() int { count := 0 for _, b := range c.buckets { count += b.pairCount() } return count } func (c *CLRUCache) bucket(key string) *bucket { h := fnv.New32a() h.Write([]byte(key)) return c.buckets[h.Sum32()&c.bucketMask] } func (c *CLRUCache) stop() { close(c.movePairs) <-c.control } func (c *CLRUCache) restart() { c.deletePairs = make(chan *list.Element, 128) c.movePairs = make(chan *list.Element, 128) c.control = make(chan interface{}) go c.worker() } func (c *CLRUCache) worker() { defer close(c.control) for { select { case el, ok := <-c.movePairs: if !ok { goto clean } if c.doMove(el) && c.list.Len() > c.cap { el := c.list.Back() c.list.Remove(el) c.bucket(el.Value.(Pair).key).delete(el.Value.(Pair).key) } case el := <-c.deletePairs: c.list.Remove(el) case control := <-c.control: switch msg := control.(type) { case clear: for _, bucket := range c.buckets { bucket.clear() } c.list = list.New() msg.done <- struct{}{} } } } clean: for { select { case el := <-c.deletePairs: c.list.Remove(el) default: close(c.deletePairs) return } } } func (c *CLRUCache) doMove(el *list.Element) bool { if el.Value.(Pair).cmd == MoveToFront { c.list.MoveToFront(el) return false } newel := c.list.PushFront(el.Value.(Pair)) c.bucket(el.Value.(Pair).key).update(el.Value.(Pair).key, newel) return true }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
halfrost/LeetCode-Go
https://github.com/halfrost/LeetCode-Go/blob/d78a9e0927a302038992428433d2eb450efd93a2/template/SegmentTree.go
template/SegmentTree.go
package template // SegmentTree define type SegmentTree struct { data, tree, lazy []int left, right int merge func(i, j int) int } // Init define func (st *SegmentTree) Init(nums []int, oper func(i, j int) int) { st.merge = oper data, tree, lazy := make([]int, len(nums)), make([]int, 4*len(nums)), make([]int, 4*len(nums)) for i := 0; i < len(nums); i++ { data[i] = nums[i] } st.data, st.tree, st.lazy = data, tree, lazy if len(nums) > 0 { st.buildSegmentTree(0, 0, len(nums)-1) } } // 在 treeIndex 的位置创建 [left....right] 区间的线段树 func (st *SegmentTree) buildSegmentTree(treeIndex, left, right int) { if left == right { st.tree[treeIndex] = st.data[left] return } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) st.buildSegmentTree(leftTreeIndex, left, midTreeIndex) st.buildSegmentTree(rightTreeIndex, midTreeIndex+1, right) st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) } func (st *SegmentTree) leftChild(index int) int { return 2*index + 1 } func (st *SegmentTree) rightChild(index int) int { return 2*index + 2 } // 查询 [left....right] 区间内的值 // Query define func (st *SegmentTree) Query(left, right int) int { if len(st.data) > 0 { return st.queryInTree(0, 0, len(st.data)-1, left, right) } return 0 } // 在以 treeIndex 为根的线段树中 [left...right] 的范围里,搜索区间 [queryLeft...queryRight] 的值 func (st *SegmentTree) queryInTree(treeIndex, left, right, queryLeft, queryRight int) int { if left == queryLeft && right == queryRight { return st.tree[treeIndex] } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) if queryLeft > midTreeIndex { return st.queryInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight) } else if queryRight <= midTreeIndex { return st.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) } return st.merge(st.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, midTreeIndex), st.queryInTree(rightTreeIndex, midTreeIndex+1, right, midTreeIndex+1, queryRight)) } // 查询 [left....right] 区间内的值 // QueryLazy define func (st *SegmentTree) QueryLazy(left, right int) int { if len(st.data) > 0 { return st.queryLazyInTree(0, 0, len(st.data)-1, left, right) } return 0 } func (st *SegmentTree) queryLazyInTree(treeIndex, left, right, queryLeft, queryRight int) int { midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) if left > queryRight || right < queryLeft { // segment completely outside range return 0 // represents a null node } if st.lazy[treeIndex] != 0 { // this node is lazy for i := 0; i < right-left+1; i++ { st.tree[treeIndex] = st.merge(st.tree[treeIndex], st.lazy[treeIndex]) // st.tree[treeIndex] += (right - left + 1) * st.lazy[treeIndex] // normalize current node by removing lazinesss } if left != right { // update lazy[] for children nodes st.lazy[leftTreeIndex] = st.merge(st.lazy[leftTreeIndex], st.lazy[treeIndex]) st.lazy[rightTreeIndex] = st.merge(st.lazy[rightTreeIndex], st.lazy[treeIndex]) // st.lazy[leftTreeIndex] += st.lazy[treeIndex] // st.lazy[rightTreeIndex] += st.lazy[treeIndex] } st.lazy[treeIndex] = 0 // current node processed. No longer lazy } if queryLeft <= left && queryRight >= right { // segment completely inside range return st.tree[treeIndex] } if queryLeft > midTreeIndex { return st.queryLazyInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight) } else if queryRight <= midTreeIndex { return st.queryLazyInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) } // merge query results return st.merge(st.queryLazyInTree(leftTreeIndex, left, midTreeIndex, queryLeft, midTreeIndex), st.queryLazyInTree(rightTreeIndex, midTreeIndex+1, right, midTreeIndex+1, queryRight)) } // 更新 index 位置的值 // Update define func (st *SegmentTree) Update(index, val int) { if len(st.data) > 0 { st.updateInTree(0, 0, len(st.data)-1, index, val) } } // 以 treeIndex 为根,更新 index 位置上的值为 val func (st *SegmentTree) updateInTree(treeIndex, left, right, index, val int) { if left == right { st.tree[treeIndex] = val return } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) if index > midTreeIndex { st.updateInTree(rightTreeIndex, midTreeIndex+1, right, index, val) } else { st.updateInTree(leftTreeIndex, left, midTreeIndex, index, val) } st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) } // 更新 [updateLeft....updateRight] 位置的值 // 注意这里的更新值是在原来值的基础上增加或者减少,而不是把这个区间内的值都赋值为 x,区间更新和单点更新不同 // 这里的区间更新关注的是变化,单点更新关注的是定值 // 当然区间更新也可以都更新成定值,如果只区间更新成定值,那么 lazy 更新策略需要变化,merge 策略也需要变化,这里暂不详细讨论 // UpdateLazy define func (st *SegmentTree) UpdateLazy(updateLeft, updateRight, val int) { if len(st.data) > 0 { st.updateLazyInTree(0, 0, len(st.data)-1, updateLeft, updateRight, val) } } func (st *SegmentTree) updateLazyInTree(treeIndex, left, right, updateLeft, updateRight, val int) { midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) if st.lazy[treeIndex] != 0 { // this node is lazy for i := 0; i < right-left+1; i++ { st.tree[treeIndex] = st.merge(st.tree[treeIndex], st.lazy[treeIndex]) //st.tree[treeIndex] += (right - left + 1) * st.lazy[treeIndex] // normalize current node by removing laziness } if left != right { // update lazy[] for children nodes st.lazy[leftTreeIndex] = st.merge(st.lazy[leftTreeIndex], st.lazy[treeIndex]) st.lazy[rightTreeIndex] = st.merge(st.lazy[rightTreeIndex], st.lazy[treeIndex]) // st.lazy[leftTreeIndex] += st.lazy[treeIndex] // st.lazy[rightTreeIndex] += st.lazy[treeIndex] } st.lazy[treeIndex] = 0 // current node processed. No longer lazy } if left > right || left > updateRight || right < updateLeft { return // out of range. escape. } if updateLeft <= left && right <= updateRight { // segment is fully within update range for i := 0; i < right-left+1; i++ { st.tree[treeIndex] = st.merge(st.tree[treeIndex], val) //st.tree[treeIndex] += (right - left + 1) * val // update segment } if left != right { // update lazy[] for children st.lazy[leftTreeIndex] = st.merge(st.lazy[leftTreeIndex], val) st.lazy[rightTreeIndex] = st.merge(st.lazy[rightTreeIndex], val) // st.lazy[leftTreeIndex] += val // st.lazy[rightTreeIndex] += val } return } st.updateLazyInTree(leftTreeIndex, left, midTreeIndex, updateLeft, updateRight, val) st.updateLazyInTree(rightTreeIndex, midTreeIndex+1, right, updateLeft, updateRight, val) // merge updates st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) } // SegmentCountTree define type SegmentCountTree struct { data, tree []int left, right int merge func(i, j int) int } // Init define func (st *SegmentCountTree) Init(nums []int, oper func(i, j int) int) { st.merge = oper data, tree := make([]int, len(nums)), make([]int, 4*len(nums)) for i := 0; i < len(nums); i++ { data[i] = nums[i] } st.data, st.tree = data, tree } // 在 treeIndex 的位置创建 [left....right] 区间的线段树 func (st *SegmentCountTree) buildSegmentTree(treeIndex, left, right int) { if left == right { st.tree[treeIndex] = st.data[left] return } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) st.buildSegmentTree(leftTreeIndex, left, midTreeIndex) st.buildSegmentTree(rightTreeIndex, midTreeIndex+1, right) st.tree[treeIndex] = st.merge(st.tree[leftTreeIndex], st.tree[rightTreeIndex]) } func (st *SegmentCountTree) leftChild(index int) int { return 2*index + 1 } func (st *SegmentCountTree) rightChild(index int) int { return 2*index + 2 } // 查询 [left....right] 区间内的值 // Query define func (st *SegmentCountTree) Query(left, right int) int { if len(st.data) > 0 { return st.queryInTree(0, 0, len(st.data)-1, left, right) } return 0 } // 在以 treeIndex 为根的线段树中 [left...right] 的范围里,搜索区间 [queryLeft...queryRight] 的值,值是计数值 func (st *SegmentCountTree) queryInTree(treeIndex, left, right, queryLeft, queryRight int) int { if queryRight < st.data[left] || queryLeft > st.data[right] { return 0 } if queryLeft <= st.data[left] && queryRight >= st.data[right] || left == right { return st.tree[treeIndex] } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) return st.queryInTree(rightTreeIndex, midTreeIndex+1, right, queryLeft, queryRight) + st.queryInTree(leftTreeIndex, left, midTreeIndex, queryLeft, queryRight) } // 更新计数 // UpdateCount define func (st *SegmentCountTree) UpdateCount(val int) { if len(st.data) > 0 { st.updateCountInTree(0, 0, len(st.data)-1, val) } } // 以 treeIndex 为根,更新 [left...right] 区间内的计数 func (st *SegmentCountTree) updateCountInTree(treeIndex, left, right, val int) { if val >= st.data[left] && val <= st.data[right] { st.tree[treeIndex]++ if left == right { return } midTreeIndex, leftTreeIndex, rightTreeIndex := left+(right-left)>>1, st.leftChild(treeIndex), st.rightChild(treeIndex) st.updateCountInTree(rightTreeIndex, midTreeIndex+1, right, val) st.updateCountInTree(leftTreeIndex, left, midTreeIndex, val) } }
go
MIT
d78a9e0927a302038992428433d2eb450efd93a2
2026-01-07T08:36:06.754118Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/generate.go
generate.go
//go:generate go run ./internal/ package main func main() {}
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/collector/collector_test.go
pkg/collector/collector_test.go
package collector import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/collector/hydratation" "github.com/traefik/traefik/v3/pkg/config/static" ) func Test_createBody(t *testing.T) { var staticConfiguration static.Configuration err := hydratation.Hydrate(&staticConfiguration) require.NoError(t, err) buffer, err := createBody(&staticConfiguration) require.NoError(t, err) assert.NotEmpty(t, buffer) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/collector/collector.go
pkg/collector/collector.go
package collector import ( "bytes" "encoding/base64" "encoding/json" "net" "net/http" "strconv" "time" "github.com/mitchellh/hashstructure" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/redactor" "github.com/traefik/traefik/v3/pkg/version" ) // collectorURL URL where the stats are sent. const collectorURL = "https://collect.traefik.io/yYaUej3P42cziRVzv6T5w2aYy9po2Mrn" // Collected data. type data struct { Version string `json:"version"` Codename string `json:"codename"` BuildDate string `json:"buildDate"` Configuration string `json:"configuration"` Hash string `json:"hash"` } // Collect anonymous data. func Collect(staticConfiguration *static.Configuration) error { buf, err := createBody(staticConfiguration) if err != nil { return err } resp, err := makeHTTPClient().Post(collectorURL, "application/json; charset=utf-8", buf) if resp != nil { _ = resp.Body.Close() } return err } func createBody(staticConfiguration *static.Configuration) (*bytes.Buffer, error) { anonConfig, err := redactor.Anonymize(staticConfiguration) if err != nil { return nil, err } log.Debug().Msgf("Anonymous stats sent to %s: %s", collectorURL, anonConfig) hashConf, err := hashstructure.Hash(staticConfiguration, nil) if err != nil { return nil, err } data := &data{ Version: version.Version, Codename: version.Codename, BuildDate: version.BuildDate, Hash: strconv.FormatUint(hashConf, 10), Configuration: base64.StdEncoding.EncodeToString([]byte(anonConfig)), } buf := new(bytes.Buffer) err = json.NewEncoder(buf).Encode(data) if err != nil { return nil, err } return buf, err } func makeHTTPClient() *http.Client { dialer := &net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, } transport := &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: dialer.DialContext, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, } return &http.Client{Transport: transport} }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/collector/hydratation/hydration.go
pkg/collector/hydratation/hydration.go
package hydratation import ( "fmt" "reflect" "time" "github.com/traefik/paerser/types" ) const ( sliceItemNumber = 2 mapItemNumber = 2 defaultString = "foobar" defaultNumber = 42 defaultBool = true defaultMapKeyPrefix = "name" ) // Hydrate hydrates a configuration. func Hydrate(element interface{}) error { field := reflect.ValueOf(element) return fill(field) } func fill(field reflect.Value) error { switch field.Kind() { case reflect.Struct: if err := setStruct(field); err != nil { return err } case reflect.Ptr: if err := setPointer(field); err != nil { return err } case reflect.Slice: if err := setSlice(field); err != nil { return err } case reflect.Map: if err := setMap(field); err != nil { return err } case reflect.Interface: setTyped(field, defaultString) case reflect.String: setTyped(field, defaultString) case reflect.Int: setTyped(field, defaultNumber) case reflect.Int8: setTyped(field, int8(defaultNumber)) case reflect.Int16: setTyped(field, int16(defaultNumber)) case reflect.Int32: setTyped(field, int32(defaultNumber)) case reflect.Int64: switch field.Type() { case reflect.TypeFor[types.Duration](): setTyped(field, types.Duration(defaultNumber*time.Second)) default: setTyped(field, int64(defaultNumber)) } case reflect.Uint: setTyped(field, uint(defaultNumber)) case reflect.Uint8: setTyped(field, uint8(defaultNumber)) case reflect.Uint16: setTyped(field, uint16(defaultNumber)) case reflect.Uint32: setTyped(field, uint32(defaultNumber)) case reflect.Uint64: setTyped(field, uint64(defaultNumber)) case reflect.Bool: setTyped(field, defaultBool) case reflect.Float32: setTyped(field, float32(defaultNumber)) case reflect.Float64: setTyped(field, float64(defaultNumber)) } return nil } func setTyped(field reflect.Value, i interface{}) { baseValue := reflect.ValueOf(i) if field.Kind().String() == field.Type().String() { field.Set(baseValue) } else { field.Set(baseValue.Convert(field.Type())) } } func setMap(field reflect.Value) error { field.Set(reflect.MakeMap(field.Type())) for i := range mapItemNumber { baseKeyName := makeKeyName(field.Type().Elem()) key := reflect.ValueOf(fmt.Sprintf("%s%d", baseKeyName, i)) // generate value ptrType := reflect.PointerTo(field.Type().Elem()) ptrValue := reflect.New(ptrType) if err := fill(ptrValue); err != nil { return err } value := ptrValue.Elem().Elem() field.SetMapIndex(key, value) } return nil } func makeKeyName(typ reflect.Type) string { switch typ.Kind() { case reflect.Ptr: return typ.Elem().Name() case reflect.String, reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Bool, reflect.Float32, reflect.Float64, reflect.Interface: return defaultMapKeyPrefix default: return typ.Name() } } func setStruct(field reflect.Value) error { for i := range field.NumField() { fld := field.Field(i) stFld := field.Type().Field(i) if !stFld.IsExported() || fld.Kind() == reflect.Func { continue } if err := fill(fld); err != nil { return err } } return nil } func setSlice(field reflect.Value) error { field.Set(reflect.MakeSlice(field.Type(), sliceItemNumber, sliceItemNumber)) for j := range field.Len() { if err := fill(field.Index(j)); err != nil { return err } } return nil } func setPointer(field reflect.Value) error { if field.IsNil() { field.Set(reflect.New(field.Type().Elem())) if err := fill(field.Elem()); err != nil { return err } } else { if err := fill(field.Elem()); err != nil { return err } } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/tcp/matcher_test.go
pkg/muxer/tcp/matcher_test.go
package tcp import ( "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/tcp" ) func Test_HostSNICatchAll(t *testing.T) { testCases := []struct { desc string rule string isCatchAll bool }{ { desc: "HostSNI(`example.com`) is not catchAll", rule: "HostSNI(`example.com`)", }, { desc: "HostSNI(`*`) is catchAll", rule: "HostSNI(`*`)", isCatchAll: true, }, { desc: "HostSNIRegexp(`^.*$`) is not catchAll", rule: "HostSNIRegexp(`.*`)", isCatchAll: false, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() muxer, err := NewMuxer() require.NoError(t, err) err = muxer.AddRoute(test.rule, "", 0, tcp.HandlerFunc(func(conn tcp.WriteCloser) {})) require.NoError(t, err) handler, catchAll := muxer.Match(ConnData{ serverName: "example.com", }) require.NotNil(t, handler) assert.Equal(t, test.isCatchAll, catchAll) }) } } func Test_HostSNI(t *testing.T) { testCases := []struct { desc string rule string serverName string buildErr bool match bool }{ { desc: "Empty", buildErr: true, }, { desc: "Invalid HostSNI matcher (empty host)", rule: "HostSNI(``)", buildErr: true, }, { desc: "Invalid HostSNI matcher (too many parameters)", rule: "HostSNI(`example.com`, `example.org`)", buildErr: true, }, { desc: "Invalid HostSNI matcher (globing sub domain)", rule: "HostSNI(`*.com`)", buildErr: true, }, { desc: "Invalid HostSNI matcher (non ASCII host)", rule: "HostSNI(`🦭.com`)", buildErr: true, }, { desc: "Valid HostSNI matcher - puny-coded emoji", rule: "HostSNI(`xn--9t9h.com`)", serverName: "xn--9t9h.com", match: true, }, { desc: "Valid HostSNI matcher - puny-coded emoji but emoji in server name", rule: "HostSNI(`xn--9t9h.com`)", serverName: "🦭.com", }, { desc: "Matching hosts", rule: "HostSNI(`example.com`)", serverName: "example.com", match: true, }, { desc: "No matching hosts", rule: "HostSNI(`example.com`)", serverName: "example.org", }, { desc: "Matching globing host `*`", rule: "HostSNI(`*`)", serverName: "example.com", match: true, }, { desc: "Matching globing host `*` and empty server name", rule: "HostSNI(`*`)", serverName: "", match: true, }, { desc: "Matching host with trailing dot", rule: "HostSNI(`example.com.`)", serverName: "example.com.", match: true, }, { desc: "Matching host with trailing dot but not in server name", rule: "HostSNI(`example.com.`)", serverName: "example.com", match: true, }, { desc: "Matching hosts with subdomains", rule: "HostSNI(`foo.example.com`)", serverName: "foo.example.com", match: true, }, { desc: "Matching hosts with subdomains with _", rule: "HostSNI(`foo_bar.example.com`)", serverName: "foo_bar.example.com", match: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() muxer, err := NewMuxer() require.NoError(t, err) err = muxer.AddRoute(test.rule, "", 0, tcp.HandlerFunc(func(conn tcp.WriteCloser) {})) if test.buildErr { require.Error(t, err) return } require.NoError(t, err) meta := ConnData{ serverName: test.serverName, } handler, _ := muxer.Match(meta) require.Equal(t, test.match, handler != nil) }) } } func Test_HostSNIRegexp(t *testing.T) { testCases := []struct { desc string rule string expected map[string]bool buildErr bool match bool }{ { desc: "Empty", buildErr: true, }, { desc: "Invalid HostSNIRegexp matcher (empty host)", rule: "HostSNIRegexp(``)", buildErr: true, }, { desc: "Invalid HostSNIRegexp matcher (non ASCII host)", rule: "HostSNIRegexp(`🦭.com`)", buildErr: true, }, { desc: "Invalid HostSNIRegexp matcher (invalid regexp)", rule: "HostSNIRegexp(`(example.com`)", buildErr: true, }, { desc: "Invalid HostSNIRegexp matcher (too many parameters)", rule: "HostSNIRegexp(`example.com`, `example.org`)", buildErr: true, }, { desc: "valid HostSNIRegexp matcher", rule: "HostSNIRegexp(`^example\\.(com|org)$`)", expected: map[string]bool{ "example.com": true, "example.com.": false, "EXAMPLE.com": false, "example.org": true, "exampleuorg": false, "": false, }, }, { desc: "valid HostSNIRegexp matcher with Traefik v2 syntax", rule: "HostSNIRegexp(`example.{tld:(com|org)}`)", expected: map[string]bool{ "example.com": false, "example.com.": false, "EXAMPLE.com": false, "example.org": false, "exampleuorg": false, "": false, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() muxer, err := NewMuxer() require.NoError(t, err) err = muxer.AddRoute(test.rule, "", 0, tcp.HandlerFunc(func(conn tcp.WriteCloser) {})) if test.buildErr { require.Error(t, err) return } require.NoError(t, err) for serverName, match := range test.expected { meta := ConnData{ serverName: serverName, } handler, _ := muxer.Match(meta) assert.Equal(t, match, handler != nil, serverName) } }) } } func Test_ClientIP(t *testing.T) { testCases := []struct { desc string rule string expected map[string]bool buildErr bool }{ { desc: "Empty", buildErr: true, }, { desc: "Invalid ClientIP matcher (empty host)", rule: "ClientIP(``)", buildErr: true, }, { desc: "Invalid ClientIP matcher (non ASCII host)", rule: "ClientIP(`🦭/32`)", buildErr: true, }, { desc: "Invalid ClientIP matcher (too many parameters)", rule: "ClientIP(`127.0.0.1`, `127.0.0.2`)", buildErr: true, }, { desc: "valid ClientIP matcher", rule: "ClientIP(`20.20.20.20`)", expected: map[string]bool{ "20.20.20.20": true, "10.10.10.10": false, }, }, { desc: "valid ClientIP matcher with CIDR", rule: "ClientIP(`20.20.20.20/24`)", expected: map[string]bool{ "20.20.20.20": true, "20.20.20.40": true, "10.10.10.10": false, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() muxer, err := NewMuxer() require.NoError(t, err) err = muxer.AddRoute(test.rule, "", 0, tcp.HandlerFunc(func(conn tcp.WriteCloser) {})) if test.buildErr { require.Error(t, err) return } require.NoError(t, err) for remoteIP, match := range test.expected { meta := ConnData{ remoteIP: remoteIP, } handler, _ := muxer.Match(meta) assert.Equal(t, match, handler != nil, remoteIP) } }) } } func Test_ALPN(t *testing.T) { testCases := []struct { desc string rule string expected map[string]bool buildErr bool }{ { desc: "Empty", buildErr: true, }, { desc: "Invalid ALPN matcher (TLS proto)", rule: "ALPN(`acme-tls/1`)", buildErr: true, }, { desc: "Invalid ALPN matcher (empty parameters)", rule: "ALPN(``)", buildErr: true, }, { desc: "Invalid ALPN matcher (too many parameters)", rule: "ALPN(`h2`, `mqtt`)", buildErr: true, }, { desc: "Valid ALPN matcher", rule: "ALPN(`h2`)", expected: map[string]bool{ "h2": true, "mqtt": false, "": false, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() muxer, err := NewMuxer() require.NoError(t, err) err = muxer.AddRoute(test.rule, "", 0, tcp.HandlerFunc(func(conn tcp.WriteCloser) {})) if test.buildErr { require.Error(t, err) return } require.NoError(t, err) for proto, match := range test.expected { meta := ConnData{ alpnProtos: []string{proto}, } handler, _ := muxer.Match(meta) assert.Equal(t, match, handler != nil, proto) } }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/tcp/matcher_v2.go
pkg/muxer/tcp/matcher_v2.go
package tcp import ( "bytes" "errors" "fmt" "regexp" "strconv" "strings" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/ip" ) var tcpFuncsV2 = map[string]func(*matchersTree, ...string) error{ "ALPN": alpnV2, "ClientIP": clientIPV2, "HostSNI": hostSNIV2, "HostSNIRegexp": hostSNIRegexpV2, } func clientIPV2(tree *matchersTree, clientIPs ...string) error { checker, err := ip.NewChecker(clientIPs) if err != nil { return fmt.Errorf("could not initialize IP Checker for \"ClientIP\" matcher: %w", err) } tree.matcher = func(meta ConnData) bool { if meta.remoteIP == "" { return false } ok, err := checker.Contains(meta.remoteIP) if err != nil { log.Warn().Err(err).Msg("ClientIP matcher: could not match remote address") return false } return ok } return nil } // alpnV2 checks if any of the connection ALPN protocols matches one of the matcher protocols. func alpnV2(tree *matchersTree, protos ...string) error { if len(protos) == 0 { return errors.New("empty value for \"ALPN\" matcher is not allowed") } for _, proto := range protos { if proto == tlsalpn01.ACMETLS1Protocol { return fmt.Errorf("invalid protocol value for \"ALPN\" matcher, %q is not allowed", proto) } } tree.matcher = func(meta ConnData) bool { for _, proto := range meta.alpnProtos { for _, filter := range protos { if proto == filter { return true } } } return false } return nil } // hostSNIV2 checks if the SNI Host of the connection match the matcher host. func hostSNIV2(tree *matchersTree, hosts ...string) error { if len(hosts) == 0 { return errors.New("empty value for \"HostSNI\" matcher is not allowed") } for i, host := range hosts { // Special case to allow global wildcard if host == "*" { continue } if !hostOrIP.MatchString(host) { return fmt.Errorf("invalid value for \"HostSNI\" matcher, %q is not a valid hostname or IP", host) } hosts[i] = strings.ToLower(host) } tree.matcher = func(meta ConnData) bool { // Since a HostSNI(`*`) rule has been provided as catchAll for non-TLS TCP, // it allows matching with an empty serverName. // Which is why we make sure to take that case into account before // checking meta.serverName. if hosts[0] == "*" { return true } if meta.serverName == "" { return false } for _, host := range hosts { if host == "*" { return true } if host == meta.serverName { return true } // trim trailing period in case of FQDN host = strings.TrimSuffix(host, ".") if host == meta.serverName { return true } } return false } return nil } // hostSNIRegexpV2 checks if the SNI Host of the connection matches the matcher host regexp. func hostSNIRegexpV2(tree *matchersTree, templates ...string) error { if len(templates) == 0 { return errors.New("empty value for \"HostSNIRegexp\" matcher is not allowed") } var regexps []*regexp.Regexp for _, template := range templates { preparedPattern, err := preparePattern(template) if err != nil { return fmt.Errorf("invalid pattern value for \"HostSNIRegexp\" matcher, %q is not a valid pattern: %w", template, err) } regexp, err := regexp.Compile(preparedPattern) if err != nil { return err } regexps = append(regexps, regexp) } tree.matcher = func(meta ConnData) bool { for _, regexp := range regexps { if regexp.MatchString(meta.serverName) { return true } } return false } return nil } // preparePattern builds a regexp pattern from the initial user defined expression. // This function reuses the code dedicated to host matching of the newRouteRegexp func from the gorilla/mux library. // https://github.com/containous/mux/tree/8ffa4f6d063c1e2b834a73be6a1515cca3992618. func preparePattern(template string) (string, error) { // Check if it is well-formed. idxs, errBraces := braceIndices(template) if errBraces != nil { return "", errBraces } defaultPattern := "[^.]+" pattern := bytes.NewBufferString("") // Host SNI matching is case-insensitive _, _ = fmt.Fprint(pattern, "(?i)") pattern.WriteByte('^') var end int for i := 0; i < len(idxs); i += 2 { // Set all values we are interested in. raw := template[end:idxs[i]] end = idxs[i+1] parts := strings.SplitN(template[idxs[i]+1:end-1], ":", 2) name := parts[0] patt := defaultPattern if len(parts) == 2 { patt = parts[1] } // Name or pattern can't be empty. if name == "" || patt == "" { return "", fmt.Errorf("mux: missing name or pattern in %q", template[idxs[i]:end]) } // Build the regexp pattern. _, _ = fmt.Fprintf(pattern, "%s(?P<%s>%s)", regexp.QuoteMeta(raw), varGroupName(i/2), patt) } // Add the remaining. raw := template[end:] pattern.WriteString(regexp.QuoteMeta(raw)) pattern.WriteByte('$') return pattern.String(), nil } // varGroupName builds a capturing group name for the indexed variable. // This function is a copy of varGroupName func from the gorilla/mux library. // https://github.com/containous/mux/tree/8ffa4f6d063c1e2b834a73be6a1515cca3992618. func varGroupName(idx int) string { return "v" + strconv.Itoa(idx) } // braceIndices returns the first level curly brace indices from a string. // This function is a copy of braceIndices func from the gorilla/mux library. // https://github.com/containous/mux/tree/8ffa4f6d063c1e2b834a73be6a1515cca3992618. func braceIndices(s string) ([]int, error) { var level, idx int var idxs []int for i := range len(s) { switch s[i] { case '{': if level++; level == 1 { idx = i } case '}': if level--; level == 0 { idxs = append(idxs, idx, i+1) } else if level < 0 { return nil, fmt.Errorf("mux: unbalanced braces in %q", s) } } } if level != 0 { return nil, fmt.Errorf("mux: unbalanced braces in %q", s) } return idxs, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/tcp/mux_test.go
pkg/muxer/tcp/mux_test.go
package tcp import ( "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/tcp" ) func Test_addTCPRoute(t *testing.T) { testCases := []struct { desc string rule string serverName string remoteAddr string protos []string routeErr bool matchErr bool }{ { desc: "no tree", routeErr: true, }, { desc: "Rule with no matcher", rule: "rulewithnotmatcher", routeErr: true, }, { desc: "Empty HostSNI rule", rule: "HostSNI(``)", serverName: "example.org", routeErr: true, }, { desc: "Valid HostSNI rule matching", rule: "HostSNI(`example.org`)", serverName: "example.org", }, { desc: "Valid negative HostSNI rule matching", rule: "!HostSNI(`example.com`)", serverName: "example.org", }, { desc: "Valid HostSNI rule matching with alternative case", rule: "hostsni(`example.org`)", serverName: "example.org", }, { desc: "Valid HostSNI rule matching with alternative case", rule: "HOSTSNI(`example.org`)", serverName: "example.org", }, { desc: "Valid HostSNI rule not matching", rule: "HostSNI(`example.org`)", serverName: "example.com", matchErr: true, }, { desc: "Valid negative HostSNI rule not matching", rule: "!HostSNI(`example.com`)", serverName: "example.com", matchErr: true, }, { desc: "Valid HostSNI and ClientIP rule matching", rule: "HostSNI(`example.org`) && ClientIP(`10.0.0.1`)", serverName: "example.org", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI and ClientIP rule matching", rule: "!HostSNI(`example.com`) && ClientIP(`10.0.0.1`)", serverName: "example.org", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI and negative ClientIP rule matching", rule: "HostSNI(`example.org`) && !ClientIP(`10.0.0.2`)", serverName: "example.org", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!HostSNI(`example.com`) && !ClientIP(`10.0.0.2`)", serverName: "example.org", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI or negative ClientIP rule matching", rule: "!(HostSNI(`example.com`) || ClientIP(`10.0.0.2`))", serverName: "example.org", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!(HostSNI(`example.com`) && ClientIP(`10.0.0.2`))", serverName: "example.org", remoteAddr: "10.0.0.2:80", }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!(HostSNI(`example.com`) && ClientIP(`10.0.0.2`))", serverName: "example.com", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!(HostSNI(`example.com`) && ClientIP(`10.0.0.2`))", serverName: "example.com", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!(HostSNI(`example.com`) && ClientIP(`10.0.0.2`))", serverName: "example.org", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI and ClientIP rule not matching", rule: "HostSNI(`example.org`) && ClientIP(`10.0.0.1`)", serverName: "example.com", remoteAddr: "10.0.0.1:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP rule not matching", rule: "HostSNI(`example.org`) && ClientIP(`10.0.0.1`)", serverName: "example.org", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid HostSNI or ClientIP rule matching", rule: "HostSNI(`example.org`) || ClientIP(`10.0.0.1`)", serverName: "example.org", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI or ClientIP rule matching", rule: "HostSNI(`example.org`) || ClientIP(`10.0.0.1`)", serverName: "example.com", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI or ClientIP rule matching", rule: "HostSNI(`example.org`) || ClientIP(`10.0.0.1`)", serverName: "example.org", remoteAddr: "10.0.0.2:80", }, { desc: "Valid HostSNI or ClientIP rule not matching", rule: "HostSNI(`example.org`) || ClientIP(`10.0.0.1`)", serverName: "example.com", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid HostSNI x 3 OR rule matching", rule: "HostSNI(`example.org`) || HostSNI(`example.eu`) || HostSNI(`example.com`)", serverName: "example.org", }, { desc: "Valid HostSNI x 3 OR rule not matching", rule: "HostSNI(`example.org`) || HostSNI(`example.eu`) || HostSNI(`example.com`)", serverName: "baz", matchErr: true, }, { desc: "Valid HostSNI and ClientIP Combined rule matching", rule: "HostSNI(`example.org`) || HostSNI(`example.com`) && ClientIP(`10.0.0.1`)", serverName: "example.org", remoteAddr: "10.0.0.2:80", }, { desc: "Valid HostSNI and ClientIP Combined rule matching", rule: "HostSNI(`example.org`) || HostSNI(`example.com`) && ClientIP(`10.0.0.1`)", serverName: "example.com", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI and ClientIP Combined rule not matching", rule: "HostSNI(`example.org`) || HostSNI(`example.com`) && ClientIP(`10.0.0.1`)", serverName: "example.com", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP Combined rule not matching", rule: "HostSNI(`example.org`) || HostSNI(`example.com`) && ClientIP(`10.0.0.1`)", serverName: "baz", remoteAddr: "10.0.0.1:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP complex combined rule matching", rule: "(HostSNI(`example.org`) || HostSNI(`example.com`)) && (ClientIP(`10.0.0.1`) || ClientIP(`10.0.0.2`))", serverName: "example.com", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI and ClientIP complex combined rule not matching", rule: "(HostSNI(`example.org`) || HostSNI(`example.com`)) && (ClientIP(`10.0.0.1`) || ClientIP(`10.0.0.2`))", serverName: "baz", remoteAddr: "10.0.0.1:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP complex combined rule not matching", rule: "(HostSNI(`example.org`) || HostSNI(`example.com`)) && (ClientIP(`10.0.0.1`) || ClientIP(`10.0.0.2`))", serverName: "example.com", remoteAddr: "10.0.0.3:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP more complex (but absurd) combined rule matching", rule: "(HostSNI(`example.org`) || (HostSNI(`example.com`) && !HostSNI(`example.org`))) && ((ClientIP(`10.0.0.1`) && !ClientIP(`10.0.0.2`)) || ClientIP(`10.0.0.2`)) ", serverName: "example.com", remoteAddr: "10.0.0.1:80", }, { desc: "Valid complex alternative case ALPN and HostSNI rule", rule: "ALPN(`h2c`) && (!ALPN(`h2`) || HostSNI(`example.eu`))", protos: []string{"h2c", "mqtt"}, serverName: "example.eu", }, { desc: "Valid complex alternative case ALPN and HostSNI rule not matching by SNI", rule: "ALPN(`h2c`) && (!ALPN(`h2`) || HostSNI(`example.eu`))", protos: []string{"h2c", "http/1.1", "h2"}, serverName: "example.com", matchErr: true, }, { desc: "Valid complex alternative case ALPN and HostSNI rule matching by ALPN", rule: "ALPN(`h2c`) && (!ALPN(`h2`) || HostSNI(`example.eu`))", protos: []string{"h2c", "http/1.1"}, serverName: "example.com", }, { desc: "Valid complex alternative case ALPN and HostSNI rule not matching by protos", rule: "ALPN(`h2c`) && (!ALPN(`h2`) || HostSNI(`example.eu`))", protos: []string{"http/1.1", "mqtt"}, serverName: "example.com", matchErr: true, }, { desc: "Matching IPv4", rule: "HostSNI(`127.0.0.1`)", serverName: "127.0.0.1", }, { desc: "Matching IPv6", rule: "HostSNI(`10::10`)", serverName: "10::10", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() msg := "BYTES" handler := tcp.HandlerFunc(func(conn tcp.WriteCloser) { _, err := conn.Write([]byte(msg)) require.NoError(t, err) }) router, err := NewMuxer() require.NoError(t, err) err = router.AddRoute(test.rule, "", 0, handler) if test.routeErr { require.Error(t, err) return } require.NoError(t, err) addr := "0.0.0.0:0" if test.remoteAddr != "" { addr = test.remoteAddr } conn := &fakeConn{ call: map[string]int{}, remoteAddr: fakeAddr{addr: addr}, } connData, err := NewConnData(test.serverName, conn, test.protos) require.NoError(t, err) matchingHandler, _ := router.Match(connData) if test.matchErr { require.Nil(t, matchingHandler) return } require.NotNil(t, matchingHandler) matchingHandler.ServeTCP(conn) n, ok := conn.call[msg] assert.Equal(t, 1, n) assert.True(t, ok) }) } } func TestParseHostSNI(t *testing.T) { testCases := []struct { desc string expression string domain []string errorExpected bool }{ { desc: "Unknown rule", expression: "Unknown(`example.com`)", errorExpected: true, }, { desc: "HostSNI rule", expression: "HostSNI(`example.com`)", domain: []string{"example.com"}, }, { desc: "HostSNI rule upper", expression: "HOSTSNI(`example.com`)", domain: []string{"example.com"}, }, { desc: "HostSNI rule lower", expression: "hostsni(`example.com`)", domain: []string{"example.com"}, }, { desc: "HostSNI IPv4", expression: "HostSNI(`127.0.0.1`)", domain: []string{"127.0.0.1"}, }, { desc: "HostSNI IPv6", expression: "HostSNI(`10::10`)", domain: []string{"10::10"}, }, { desc: "No hostSNI rule", expression: "ClientIP(`10.1`)", }, { desc: "HostSNI rule and another rule", expression: "HostSNI(`example.com`) && ClientIP(`10.1`)", domain: []string{"example.com"}, }, { desc: "HostSNI rule to lower and another rule", expression: "HostSNI(`example.com`) && ClientIP(`10.1`)", domain: []string{"example.com"}, }, { desc: "HostSNI rule with no domain", expression: "HostSNI() && ClientIP(`10.1`)", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() domains, err := ParseHostSNI(test.expression) if test.errorExpected { require.Errorf(t, err, "unable to parse correctly the domains in the HostSNI rule from %q", test.expression) } else { require.NoError(t, err, "%s: Error while parsing domain.", test.expression) } assert.Equal(t, test.domain, domains, "%s: Error parsing domains from expression.", test.expression) }) } } func Test_Priority(t *testing.T) { testCases := []struct { desc string rules map[string]int serverName string expectedRule string }{ { desc: "One matching rule, calculated priority", rules: map[string]int{ "HostSNI(`example.com`)": 0, "HostSNI(`example.org`)": 0, }, expectedRule: "HostSNI(`example.com`)", serverName: "example.com", }, { desc: "One matching rule, custom priority", rules: map[string]int{ "HostSNI(`example.org`)": 0, "HostSNI(`example.com`)": 10000, }, expectedRule: "HostSNI(`example.org`)", serverName: "example.org", }, { desc: "Two matching rules, calculated priority", rules: map[string]int{ "HostSNI(`example.org`)": 0, "HostSNI(`example.com`)": 0, }, expectedRule: "HostSNI(`example.org`)", serverName: "example.org", }, { desc: "Two matching rules, custom priority", rules: map[string]int{ "HostSNI(`example.com`)": 10000, "HostSNI(`example.org`)": 0, }, expectedRule: "HostSNI(`example.com`)", serverName: "example.com", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() muxer, err := NewMuxer() require.NoError(t, err) matchedRule := "" for rule, priority := range test.rules { err := muxer.AddRoute(rule, "", priority, tcp.HandlerFunc(func(conn tcp.WriteCloser) { matchedRule = rule })) require.NoError(t, err) } handler, _ := muxer.Match(ConnData{ serverName: test.serverName, }) require.NotNil(t, handler) handler.ServeTCP(nil) assert.Equal(t, test.expectedRule, matchedRule) }) } } func TestGetRulePriority(t *testing.T) { testCases := []struct { desc string rule string expected int }{ { desc: "simple rule", rule: "HostSNI(`example.org`)", expected: 22, }, { desc: "HostSNI(`*`) rule", rule: "HostSNI(`*`)", expected: -1, }, { desc: "strange HostSNI(`*`) rule", rule: " HostSNI ( `*` ) ", expected: -1, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() assert.Equal(t, test.expected, GetRulePriority(test.rule)) }) } } type fakeConn struct { call map[string]int remoteAddr net.Addr } func (f *fakeConn) Read(b []byte) (n int, err error) { panic("implement me") } func (f *fakeConn) Write(b []byte) (n int, err error) { f.call[string(b)]++ return len(b), nil } func (f *fakeConn) Close() error { panic("implement me") } func (f *fakeConn) LocalAddr() net.Addr { panic("implement me") } func (f *fakeConn) RemoteAddr() net.Addr { return f.remoteAddr } func (f *fakeConn) SetDeadline(t time.Time) error { panic("implement me") } func (f *fakeConn) SetReadDeadline(t time.Time) error { panic("implement me") } func (f *fakeConn) SetWriteDeadline(t time.Time) error { panic("implement me") } func (f *fakeConn) CloseWrite() error { panic("implement me") } type fakeAddr struct { addr string } func (f fakeAddr) String() string { return f.addr } func (f fakeAddr) Network() string { panic("Implement me") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/tcp/matcher.go
pkg/muxer/tcp/matcher.go
package tcp import ( "fmt" "regexp" "strings" "unicode/utf8" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/ip" ) var tcpFuncs = map[string]func(*matchersTree, ...string) error{ "ALPN": expect1Parameter(alpn), "ClientIP": expect1Parameter(clientIP), "HostSNI": expect1Parameter(hostSNI), "HostSNIRegexp": expect1Parameter(hostSNIRegexp), } func expect1Parameter(fn func(*matchersTree, ...string) error) func(*matchersTree, ...string) error { return func(route *matchersTree, s ...string) error { if len(s) != 1 { return fmt.Errorf("unexpected number of parameters; got %d, expected 1", len(s)) } return fn(route, s...) } } // alpn checks if any of the connection ALPN protocols matches one of the matcher protocols. func alpn(tree *matchersTree, protos ...string) error { proto := protos[0] if proto == tlsalpn01.ACMETLS1Protocol { return fmt.Errorf("invalid protocol value for ALPN matcher, %q is not allowed", proto) } tree.matcher = func(meta ConnData) bool { for _, alpnProto := range meta.alpnProtos { if alpnProto == proto { return true } } return false } return nil } func clientIP(tree *matchersTree, clientIP ...string) error { checker, err := ip.NewChecker(clientIP) if err != nil { return fmt.Errorf("initializing IP checker for ClientIP matcher: %w", err) } tree.matcher = func(meta ConnData) bool { ok, err := checker.Contains(meta.remoteIP) if err != nil { log.Warn().Err(err).Msg("ClientIP matcher: could not match remote address") return false } return ok } return nil } var hostOrIP = regexp.MustCompile(`^[[:word:]\.\-\:]+$`) // hostSNI checks if the SNI Host of the connection match the matcher host. func hostSNI(tree *matchersTree, hosts ...string) error { host := hosts[0] if host == "*" { // Since a HostSNI(`*`) rule has been provided as catchAll for non-TLS TCP, // it allows matching with an empty serverName. tree.matcher = func(meta ConnData) bool { return true } return nil } if !hostOrIP.MatchString(host) { return fmt.Errorf("invalid value for HostSNI matcher, %q is not a valid hostname", host) } tree.matcher = func(meta ConnData) bool { if meta.serverName == "" { return false } if host == meta.serverName { return true } // trim trailing period in case of FQDN host = strings.TrimSuffix(host, ".") return host == meta.serverName } return nil } // hostSNIRegexp checks if the SNI Host of the connection matches the matcher host regexp. func hostSNIRegexp(tree *matchersTree, templates ...string) error { template := templates[0] if !isASCII(template) { return fmt.Errorf("invalid value for HostSNIRegexp matcher, %q is not a valid hostname", template) } re, err := regexp.Compile(template) if err != nil { return fmt.Errorf("compiling HostSNIRegexp matcher: %w", err) } tree.matcher = func(meta ConnData) bool { return re.MatchString(meta.serverName) } return nil } // isASCII checks if the given string contains only ASCII characters. func isASCII(s string) bool { for i := range len(s) { if s[i] >= utf8.RuneSelf { return false } } return true }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/tcp/matcher_v2_test.go
pkg/muxer/tcp/matcher_v2_test.go
package tcp import ( "fmt" "testing" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/tcp" ) // All the tests in the suite are a copy of tcp muxer tests on branch v2. // Only the test for route priority has not been copied here, // because the priority computation is no longer done when calling the muxer AddRoute method. func Test_addTCPRouteV2(t *testing.T) { testCases := []struct { desc string rule string serverName string remoteAddr string protos []string routeErr bool matchErr bool }{ { desc: "no tree", routeErr: true, }, { desc: "Rule with no matcher", rule: "rulewithnotmatcher", routeErr: true, }, { desc: "Empty HostSNI rule", rule: "HostSNI()", serverName: "foobar", routeErr: true, }, { desc: "Empty HostSNI rule", rule: "HostSNI(``)", serverName: "foobar", routeErr: true, }, { desc: "Valid HostSNI rule matching", rule: "HostSNI(`foobar`)", serverName: "foobar", }, { desc: "Valid negative HostSNI rule matching", rule: "!HostSNI(`bar`)", serverName: "foobar", }, { desc: "Valid HostSNI rule matching with alternative case", rule: "hostsni(`foobar`)", serverName: "foobar", }, { desc: "Valid HostSNI rule matching with alternative case", rule: "HOSTSNI(`foobar`)", serverName: "foobar", }, { desc: "Valid HostSNI rule not matching", rule: "HostSNI(`foobar`)", serverName: "bar", matchErr: true, }, { desc: "Empty HostSNIRegexp rule", rule: "HostSNIRegexp()", serverName: "foobar", routeErr: true, }, { desc: "Empty HostSNIRegexp rule", rule: "HostSNIRegexp(``)", serverName: "foobar", routeErr: true, }, { desc: "Valid HostSNIRegexp rule matching", rule: "HostSNIRegexp(`{subdomain:[a-z]+}.foobar`)", serverName: "sub.foobar", }, { desc: "Valid negative HostSNIRegexp rule matching", rule: "!HostSNIRegexp(`bar`)", serverName: "foobar", }, { desc: "Valid HostSNIRegexp rule matching with alternative case", rule: "hostsniregexp(`foobar`)", serverName: "foobar", }, { desc: "Valid HostSNIRegexp rule matching with alternative case", rule: "HOSTSNIREGEXP(`foobar`)", serverName: "foobar", }, { desc: "Valid HostSNIRegexp rule not matching", rule: "HostSNIRegexp(`foobar`)", serverName: "bar", matchErr: true, }, { desc: "Valid negative HostSNI rule not matching", rule: "!HostSNI(`bar`)", serverName: "bar", matchErr: true, }, { desc: "Valid HostSNIRegexp rule matching empty servername", rule: "HostSNIRegexp(`{subdomain:[a-z]*}`)", serverName: "", }, { desc: "Valid HostSNIRegexp rule with one name", rule: "HostSNIRegexp(`{dummy}`)", serverName: "toto", }, { desc: "Valid HostSNIRegexp rule with one name 2", rule: "HostSNIRegexp(`{dummy}`)", serverName: "toto.com", matchErr: true, }, { desc: "Empty ClientIP rule", rule: "ClientIP()", routeErr: true, }, { desc: "Empty ClientIP rule", rule: "ClientIP(``)", routeErr: true, }, { desc: "Invalid ClientIP", rule: "ClientIP(`invalid`)", routeErr: true, }, { desc: "Invalid remoteAddr", rule: "ClientIP(`10.0.0.1`)", remoteAddr: "not.an.IP:80", matchErr: true, }, { desc: "Valid ClientIP rule matching", rule: "ClientIP(`10.0.0.1`)", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative ClientIP rule matching", rule: "!ClientIP(`20.0.0.1`)", remoteAddr: "10.0.0.1:80", }, { desc: "Valid ClientIP rule matching with alternative case", rule: "clientip(`10.0.0.1`)", remoteAddr: "10.0.0.1:80", }, { desc: "Valid ClientIP rule matching with alternative case", rule: "CLIENTIP(`10.0.0.1`)", remoteAddr: "10.0.0.1:80", }, { desc: "Valid ClientIP rule not matching", rule: "ClientIP(`10.0.0.1`)", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid negative ClientIP rule not matching", rule: "!ClientIP(`10.0.0.2`)", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid ClientIP rule matching IPv6", rule: "ClientIP(`10::10`)", remoteAddr: "[10::10]:80", }, { desc: "Valid negative ClientIP rule matching IPv6", rule: "!ClientIP(`10::10`)", remoteAddr: "[::1]:80", }, { desc: "Valid ClientIP rule not matching IPv6", rule: "ClientIP(`10::10`)", remoteAddr: "[::1]:80", matchErr: true, }, { desc: "Valid ClientIP rule matching multiple IPs", rule: "ClientIP(`10.0.0.1`, `10.0.0.0`)", remoteAddr: "10.0.0.0:80", }, { desc: "Valid ClientIP rule matching CIDR", rule: "ClientIP(`11.0.0.0/24`)", remoteAddr: "11.0.0.0:80", }, { desc: "Valid ClientIP rule not matching CIDR", rule: "ClientIP(`11.0.0.0/24`)", remoteAddr: "10.0.0.0:80", matchErr: true, }, { desc: "Valid ClientIP rule matching CIDR IPv6", rule: "ClientIP(`11::/16`)", remoteAddr: "[11::]:80", }, { desc: "Valid ClientIP rule not matching CIDR IPv6", rule: "ClientIP(`11::/16`)", remoteAddr: "[10::]:80", matchErr: true, }, { desc: "Valid ClientIP rule matching multiple CIDR", rule: "ClientIP(`11.0.0.0/16`, `10.0.0.0/16`)", remoteAddr: "10.0.0.0:80", }, { desc: "Valid ClientIP rule not matching CIDR and matching IP", rule: "ClientIP(`11.0.0.0/16`, `10.0.0.0`)", remoteAddr: "10.0.0.0:80", }, { desc: "Valid ClientIP rule matching CIDR and not matching IP", rule: "ClientIP(`11.0.0.0`, `10.0.0.0/16`)", remoteAddr: "10.0.0.0:80", }, { desc: "Valid HostSNI and ClientIP rule matching", rule: "HostSNI(`foobar`) && ClientIP(`10.0.0.1`)", serverName: "foobar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI and ClientIP rule matching", rule: "!HostSNI(`bar`) && ClientIP(`10.0.0.1`)", serverName: "foobar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI and negative ClientIP rule matching", rule: "HostSNI(`foobar`) && !ClientIP(`10.0.0.2`)", serverName: "foobar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!HostSNI(`bar`) && !ClientIP(`10.0.0.2`)", serverName: "foobar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI or negative ClientIP rule matching", rule: "!(HostSNI(`bar`) || ClientIP(`10.0.0.2`))", serverName: "foobar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!(HostSNI(`bar`) && ClientIP(`10.0.0.2`))", serverName: "foobar", remoteAddr: "10.0.0.2:80", }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!(HostSNI(`bar`) && ClientIP(`10.0.0.2`))", serverName: "bar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!(HostSNI(`bar`) && ClientIP(`10.0.0.2`))", serverName: "bar", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid negative HostSNI and negative ClientIP rule matching", rule: "!(HostSNI(`bar`) && ClientIP(`10.0.0.2`))", serverName: "foobar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI and ClientIP rule not matching", rule: "HostSNI(`foobar`) && ClientIP(`10.0.0.1`)", serverName: "bar", remoteAddr: "10.0.0.1:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP rule not matching", rule: "HostSNI(`foobar`) && ClientIP(`10.0.0.1`)", serverName: "foobar", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid HostSNI or ClientIP rule matching", rule: "HostSNI(`foobar`) || ClientIP(`10.0.0.1`)", serverName: "foobar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI or ClientIP rule matching", rule: "HostSNI(`foobar`) || ClientIP(`10.0.0.1`)", serverName: "bar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI or ClientIP rule matching", rule: "HostSNI(`foobar`) || ClientIP(`10.0.0.1`)", serverName: "foobar", remoteAddr: "10.0.0.2:80", }, { desc: "Valid HostSNI or ClientIP rule not matching", rule: "HostSNI(`foobar`) || ClientIP(`10.0.0.1`)", serverName: "bar", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid HostSNI x 3 OR rule matching", rule: "HostSNI(`foobar`) || HostSNI(`foo`) || HostSNI(`bar`)", serverName: "foobar", }, { desc: "Valid HostSNI x 3 OR rule not matching", rule: "HostSNI(`foobar`) || HostSNI(`foo`) || HostSNI(`bar`)", serverName: "baz", matchErr: true, }, { desc: "Valid HostSNI and ClientIP Combined rule matching", rule: "HostSNI(`foobar`) || HostSNI(`bar`) && ClientIP(`10.0.0.1`)", serverName: "foobar", remoteAddr: "10.0.0.2:80", }, { desc: "Valid HostSNI and ClientIP Combined rule matching", rule: "HostSNI(`foobar`) || HostSNI(`bar`) && ClientIP(`10.0.0.1`)", serverName: "bar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI and ClientIP Combined rule not matching", rule: "HostSNI(`foobar`) || HostSNI(`bar`) && ClientIP(`10.0.0.1`)", serverName: "bar", remoteAddr: "10.0.0.2:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP Combined rule not matching", rule: "HostSNI(`foobar`) || HostSNI(`bar`) && ClientIP(`10.0.0.1`)", serverName: "baz", remoteAddr: "10.0.0.1:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP complex combined rule matching", rule: "(HostSNI(`foobar`) || HostSNI(`bar`)) && (ClientIP(`10.0.0.1`) || ClientIP(`10.0.0.2`))", serverName: "bar", remoteAddr: "10.0.0.1:80", }, { desc: "Valid HostSNI and ClientIP complex combined rule not matching", rule: "(HostSNI(`foobar`) || HostSNI(`bar`)) && (ClientIP(`10.0.0.1`) || ClientIP(`10.0.0.2`))", serverName: "baz", remoteAddr: "10.0.0.1:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP complex combined rule not matching", rule: "(HostSNI(`foobar`) || HostSNI(`bar`)) && (ClientIP(`10.0.0.1`) || ClientIP(`10.0.0.2`))", serverName: "bar", remoteAddr: "10.0.0.3:80", matchErr: true, }, { desc: "Valid HostSNI and ClientIP more complex (but absurd) combined rule matching", rule: "(HostSNI(`foobar`) || (HostSNI(`bar`) && !HostSNI(`foobar`))) && ((ClientIP(`10.0.0.1`) && !ClientIP(`10.0.0.2`)) || ClientIP(`10.0.0.2`)) ", serverName: "bar", remoteAddr: "10.0.0.1:80", }, { desc: "Invalid ALPN rule matching ACME-TLS/1", rule: fmt.Sprintf("ALPN(`%s`)", tlsalpn01.ACMETLS1Protocol), protos: []string{"foo"}, routeErr: true, }, { desc: "Valid ALPN rule matching single protocol", rule: "ALPN(`foo`)", protos: []string{"foo"}, }, { desc: "Valid ALPN rule matching ACME-TLS/1 protocol", rule: "ALPN(`foo`)", protos: []string{tlsalpn01.ACMETLS1Protocol}, matchErr: true, }, { desc: "Valid ALPN rule not matching single protocol", rule: "ALPN(`foo`)", protos: []string{"bar"}, matchErr: true, }, { desc: "Valid alternative case ALPN rule matching single protocol without another being supported", rule: "ALPN(`foo`) && !alpn(`h2`)", protos: []string{"foo", "bar"}, }, { desc: "Valid alternative case ALPN rule not matching single protocol because of another being supported", rule: "ALPN(`foo`) && !alpn(`h2`)", protos: []string{"foo", "h2", "bar"}, matchErr: true, }, { desc: "Valid complex alternative case ALPN and HostSNI rule", rule: "ALPN(`foo`) && (!alpn(`h2`) || hostsni(`foo`))", protos: []string{"foo", "bar"}, serverName: "foo", }, { desc: "Valid complex alternative case ALPN and HostSNI rule not matching by SNI", rule: "ALPN(`foo`) && (!alpn(`h2`) || hostsni(`foo`))", protos: []string{"foo", "bar", "h2"}, serverName: "bar", matchErr: true, }, { desc: "Valid complex alternative case ALPN and HostSNI rule matching by ALPN", rule: "ALPN(`foo`) && (!alpn(`h2`) || hostsni(`foo`))", protos: []string{"foo", "bar"}, serverName: "bar", }, { desc: "Valid complex alternative case ALPN and HostSNI rule not matching by protos", rule: "ALPN(`foo`) && (!alpn(`h2`) || hostsni(`foo`))", protos: []string{"h2", "bar"}, serverName: "bar", matchErr: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() msg := "BYTES" handler := tcp.HandlerFunc(func(conn tcp.WriteCloser) { _, err := conn.Write([]byte(msg)) require.NoError(t, err) }) router, err := NewMuxer() require.NoError(t, err) err = router.AddRoute(test.rule, "v2", 0, handler) if test.routeErr { require.Error(t, err) return } require.NoError(t, err) addr := "0.0.0.0:0" if test.remoteAddr != "" { addr = test.remoteAddr } conn := &fakeConn{ call: map[string]int{}, remoteAddr: fakeAddr{addr: addr}, } connData, err := NewConnData(test.serverName, conn, test.protos) require.NoError(t, err) matchingHandler, _ := router.Match(connData) if test.matchErr { require.Nil(t, matchingHandler) return } require.NotNil(t, matchingHandler) matchingHandler.ServeTCP(conn) n, ok := conn.call[msg] assert.Equal(t, 1, n) assert.True(t, ok) }) } } func TestParseHostSNIV2(t *testing.T) { testCases := []struct { description string expression string domain []string errorExpected bool }{ { description: "Unknown rule", expression: "Foobar(`foo.bar`,`test.bar`)", errorExpected: true, }, { description: "Many hostSNI rules", expression: "HostSNI(`foo.bar`,`test.bar`)", domain: []string{"foo.bar", "test.bar"}, }, { description: "Many hostSNI rules upper", expression: "HOSTSNI(`foo.bar`,`test.bar`)", domain: []string{"foo.bar", "test.bar"}, }, { description: "Many hostSNI rules lower", expression: "hostsni(`foo.bar`,`test.bar`)", domain: []string{"foo.bar", "test.bar"}, }, { description: "No hostSNI rule", expression: "ClientIP(`10.1`)", }, { description: "HostSNI rule and another rule", expression: "HostSNI(`foo.bar`) && ClientIP(`10.1`)", domain: []string{"foo.bar"}, }, { description: "HostSNI rule to lower and another rule", expression: "HostSNI(`Foo.Bar`) && ClientIP(`10.1`)", domain: []string{"foo.bar"}, }, { description: "HostSNI rule with no domain", expression: "HostSNI() && ClientIP(`10.1`)", }, } for _, test := range testCases { t.Run(test.expression, func(t *testing.T) { t.Parallel() domains, err := ParseHostSNI(test.expression) if test.errorExpected { require.Errorf(t, err, "unable to parse correctly the domains in the HostSNI rule from %q", test.expression) } else { require.NoError(t, err, "%s: Error while parsing domain.", test.expression) } assert.Equal(t, test.domain, domains, "%s: Error parsing domains from expression.", test.expression) }) } } func Test_HostSNICatchAllV2(t *testing.T) { testCases := []struct { desc string rule string isCatchAll bool }{ { desc: "HostSNI(`foobar`) is not catchAll", rule: "HostSNI(`foobar`)", }, { desc: "HostSNI(`*`) is catchAll", rule: "HostSNI(`*`)", isCatchAll: true, }, { desc: "HOSTSNI(`*`) is catchAll", rule: "HOSTSNI(`*`)", isCatchAll: true, }, { desc: `HostSNI("*") is catchAll`, rule: `HostSNI("*")`, isCatchAll: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() muxer, err := NewMuxer() require.NoError(t, err) err = muxer.AddRoute(test.rule, "v2", 0, tcp.HandlerFunc(func(conn tcp.WriteCloser) {})) require.NoError(t, err) handler, catchAll := muxer.Match(ConnData{ serverName: "foobar", }) require.NotNil(t, handler) assert.Equal(t, test.isCatchAll, catchAll) }) } } func Test_HostSNIV2(t *testing.T) { testCases := []struct { desc string ruleHosts []string serverName string buildErr bool matchErr bool }{ { desc: "Empty", buildErr: true, }, { desc: "Non ASCII host", ruleHosts: []string{"héhé"}, buildErr: true, }, { desc: "Not Matching hosts", ruleHosts: []string{"foobar"}, serverName: "bar", matchErr: true, }, { desc: "Matching globing host `*`", ruleHosts: []string{"*"}, serverName: "foobar", }, { desc: "Matching globing host `*` and empty serverName", ruleHosts: []string{"*"}, serverName: "", }, { desc: "Matching globing host `*` and another non matching host", ruleHosts: []string{"foo", "*"}, serverName: "bar", }, { desc: "Matching globing host `*` and another non matching host, and empty servername", ruleHosts: []string{"foo", "*"}, serverName: "", matchErr: true, }, { desc: "Not Matching globing host with subdomain", ruleHosts: []string{"*.bar"}, buildErr: true, }, { desc: "Not Matching host with trailing dot with ", ruleHosts: []string{"foobar."}, serverName: "foobar.", }, { desc: "Matching host with trailing dot", ruleHosts: []string{"foobar."}, serverName: "foobar", }, { desc: "Matching hosts", ruleHosts: []string{"foobar", "foo-bar.baz"}, serverName: "foobar", }, { desc: "Matching hosts with subdomains", ruleHosts: []string{"foo.bar"}, serverName: "foo.bar", }, { desc: "Matching hosts with subdomains with _", ruleHosts: []string{"foo_bar.example.com"}, serverName: "foo_bar.example.com", }, { desc: "Matching IPv4", ruleHosts: []string{"127.0.0.1"}, serverName: "127.0.0.1", }, { desc: "Matching IPv6", ruleHosts: []string{"10::10"}, serverName: "10::10", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() matcherTree := &matchersTree{} err := hostSNIV2(matcherTree, test.ruleHosts...) if test.buildErr { require.Error(t, err) return } require.NoError(t, err) meta := ConnData{ serverName: test.serverName, } assert.Equal(t, test.matchErr, !matcherTree.match(meta)) }) } } func Test_HostSNIRegexpV2(t *testing.T) { testCases := []struct { desc string pattern string serverNames map[string]bool buildErr bool }{ { desc: "unbalanced braces", pattern: "subdomain:(foo\\.)?bar\\.com}", buildErr: true, }, { desc: "empty group name", pattern: "{:(foo\\.)?bar\\.com}", buildErr: true, }, { desc: "empty capturing group", pattern: "{subdomain:}", buildErr: true, }, { desc: "malformed capturing group", pattern: "{subdomain:(foo\\.?bar\\.com}", buildErr: true, }, { desc: "not interpreted as a regexp", pattern: "bar.com", serverNames: map[string]bool{ "bar.com": true, "barucom": false, }, }, { desc: "capturing group", pattern: "{subdomain:(foo\\.)?bar\\.com}", serverNames: map[string]bool{ "foo.bar.com": true, "bar.com": true, "fooubar.com": false, "barucom": false, "barcom": false, }, }, { desc: "non capturing group", pattern: "{subdomain:(?:foo\\.)?bar\\.com}", serverNames: map[string]bool{ "foo.bar.com": true, "bar.com": true, "fooubar.com": false, "barucom": false, "barcom": false, }, }, { desc: "regex insensitive", pattern: "{dummy:[A-Za-z-]+\\.bar\\.com}", serverNames: map[string]bool{ "FOO.bar.com": true, "foo.bar.com": true, "fooubar.com": false, "barucom": false, "barcom": false, }, }, { desc: "insensitive host", pattern: "{dummy:[a-z-]+\\.bar\\.com}", serverNames: map[string]bool{ "FOO.bar.com": true, "foo.bar.com": true, "fooubar.com": false, "barucom": false, "barcom": false, }, }, { desc: "insensitive host simple", pattern: "foo.bar.com", serverNames: map[string]bool{ "FOO.bar.com": true, "foo.bar.com": true, "fooubar.com": false, "barucom": false, "barcom": false, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() matchersTree := &matchersTree{} err := hostSNIRegexpV2(matchersTree, test.pattern) if test.buildErr { require.Error(t, err) return } require.NoError(t, err) for serverName, match := range test.serverNames { meta := ConnData{ serverName: serverName, } assert.Equal(t, match, matchersTree.match(meta)) } }) } } func Test_ClientIPV2(t *testing.T) { testCases := []struct { desc string ruleCIDRs []string remoteIP string buildErr bool matchErr bool }{ { desc: "Empty", buildErr: true, }, { desc: "Malformed CIDR", ruleCIDRs: []string{"héhé"}, buildErr: true, }, { desc: "Not matching empty remote IP", ruleCIDRs: []string{"20.20.20.20"}, matchErr: true, }, { desc: "Not matching IP", ruleCIDRs: []string{"20.20.20.20"}, remoteIP: "10.10.10.10", matchErr: true, }, { desc: "Matching IP", ruleCIDRs: []string{"10.10.10.10"}, remoteIP: "10.10.10.10", }, { desc: "Not matching multiple IPs", ruleCIDRs: []string{"20.20.20.20", "30.30.30.30"}, remoteIP: "10.10.10.10", matchErr: true, }, { desc: "Matching multiple IPs", ruleCIDRs: []string{"10.10.10.10", "20.20.20.20", "30.30.30.30"}, remoteIP: "20.20.20.20", }, { desc: "Not matching CIDR", ruleCIDRs: []string{"20.0.0.0/24"}, remoteIP: "10.10.10.10", matchErr: true, }, { desc: "Matching CIDR", ruleCIDRs: []string{"20.0.0.0/8"}, remoteIP: "20.10.10.10", }, { desc: "Not matching multiple CIDRs", ruleCIDRs: []string{"10.0.0.0/24", "20.0.0.0/24"}, remoteIP: "10.10.10.10", matchErr: true, }, { desc: "Matching multiple CIDRs", ruleCIDRs: []string{"10.0.0.0/8", "20.0.0.0/8"}, remoteIP: "20.10.10.10", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() matchersTree := &matchersTree{} err := clientIPV2(matchersTree, test.ruleCIDRs...) if test.buildErr { require.Error(t, err) return } require.NoError(t, err) meta := ConnData{ remoteIP: test.remoteIP, } assert.Equal(t, test.matchErr, !matchersTree.match(meta)) }) } } func Test_ALPNV2(t *testing.T) { testCases := []struct { desc string ruleALPNProtos []string connProto string buildErr bool matchErr bool }{ { desc: "Empty", buildErr: true, }, { desc: "ACME TLS proto", ruleALPNProtos: []string{tlsalpn01.ACMETLS1Protocol}, buildErr: true, }, { desc: "Not matching empty proto", ruleALPNProtos: []string{"h2"}, matchErr: true, }, { desc: "Not matching ALPN", ruleALPNProtos: []string{"h2"}, connProto: "mqtt", matchErr: true, }, { desc: "Matching ALPN", ruleALPNProtos: []string{"h2"}, connProto: "h2", }, { desc: "Not matching multiple ALPNs", ruleALPNProtos: []string{"h2", "mqtt"}, connProto: "h2c", matchErr: true, }, { desc: "Matching multiple ALPNs", ruleALPNProtos: []string{"h2", "h2c", "mqtt"}, connProto: "h2c", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() matchersTree := &matchersTree{} err := alpnV2(matchersTree, test.ruleALPNProtos...) if test.buildErr { require.Error(t, err) return } require.NoError(t, err) meta := ConnData{ alpnProtos: []string{test.connProto}, } assert.Equal(t, test.matchErr, !matchersTree.match(meta)) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/tcp/mux.go
pkg/muxer/tcp/mux.go
package tcp import ( "fmt" "net" "sort" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/rules" "github.com/traefik/traefik/v3/pkg/tcp" "github.com/traefik/traefik/v3/pkg/types" "github.com/vulcand/predicate" ) // ConnData contains TCP connection metadata. type ConnData struct { serverName string remoteIP string alpnProtos []string } // NewConnData builds a connData struct from the given parameters. func NewConnData(serverName string, conn tcp.WriteCloser, alpnProtos []string) (ConnData, error) { remoteIP, _, err := net.SplitHostPort(conn.RemoteAddr().String()) if err != nil { return ConnData{}, fmt.Errorf("error while parsing remote address %q: %w", conn.RemoteAddr().String(), err) } // as per https://datatracker.ietf.org/doc/html/rfc6066: // > The hostname is represented as a byte string using ASCII encoding without a trailing dot. // so there is no need to trim a potential trailing dot serverName = types.CanonicalDomain(serverName) return ConnData{ serverName: types.CanonicalDomain(serverName), remoteIP: remoteIP, alpnProtos: alpnProtos, }, nil } // Muxer defines a muxer that handles TCP routing with rules. type Muxer struct { routes routes parser predicate.Parser parserV2 predicate.Parser } // NewMuxer returns a TCP muxer. func NewMuxer() (*Muxer, error) { var matcherNames []string for matcherName := range tcpFuncs { matcherNames = append(matcherNames, matcherName) } parser, err := rules.NewParser(matcherNames) if err != nil { return nil, fmt.Errorf("error while creating rules parser: %w", err) } var matchersV2 []string for matcher := range tcpFuncsV2 { matchersV2 = append(matchersV2, matcher) } parserV2, err := rules.NewParser(matchersV2) if err != nil { return nil, fmt.Errorf("error while creating v2 rules parser: %w", err) } return &Muxer{ parser: parser, parserV2: parserV2, }, nil } // Match returns the handler of the first route matching the connection metadata, // and whether the match is exactly from the rule HostSNI(*). func (m *Muxer) Match(meta ConnData) (tcp.Handler, bool) { for _, route := range m.routes { if route.matchers.match(meta) { return route.handler, route.catchAll } } return nil, false } // GetRulePriority computes the priority for a given rule. // The priority is calculated using the length of rule. // There is a special case where the HostSNI(`*`) has a priority of -1. func GetRulePriority(rule string) int { catchAllParser, err := rules.NewParser([]string{"HostSNI"}) if err != nil { return len(rule) } parse, err := catchAllParser.Parse(rule) if err != nil { return len(rule) } buildTree, ok := parse.(rules.TreeBuilder) if !ok { return len(rule) } ruleTree := buildTree() // Special case for when the catchAll fallback is present. // When no user-defined priority is found, the lowest computable priority minus one is used, // in order to make the fallback the last to be evaluated. if ruleTree.RuleLeft == nil && ruleTree.RuleRight == nil && len(ruleTree.Value) == 1 && ruleTree.Value[0] == "*" && strings.EqualFold(ruleTree.Matcher, "HostSNI") { return -1 } return len(rule) } // AddRoute adds a new route, associated to the given handler, at the given // priority, to the muxer. func (m *Muxer) AddRoute(rule string, syntax string, priority int, handler tcp.Handler) error { var parse interface{} var err error var matcherFuncs map[string]func(*matchersTree, ...string) error switch syntax { case "v2": parse, err = m.parserV2.Parse(rule) if err != nil { return fmt.Errorf("error while parsing rule %s: %w", rule, err) } matcherFuncs = tcpFuncsV2 default: parse, err = m.parser.Parse(rule) if err != nil { return fmt.Errorf("error while parsing rule %s: %w", rule, err) } matcherFuncs = tcpFuncs } buildTree, ok := parse.(rules.TreeBuilder) if !ok { return fmt.Errorf("error while parsing rule %s", rule) } ruleTree := buildTree() var matchers matchersTree err = matchers.addRule(ruleTree, matcherFuncs) if err != nil { return fmt.Errorf("error while adding rule %s: %w", rule, err) } var catchAll bool if ruleTree.RuleLeft == nil && ruleTree.RuleRight == nil && len(ruleTree.Value) == 1 { catchAll = ruleTree.Value[0] == "*" && strings.EqualFold(ruleTree.Matcher, "HostSNI") } newRoute := &route{ handler: handler, matchers: matchers, catchAll: catchAll, priority: priority, } m.routes = append(m.routes, newRoute) sort.Sort(m.routes) return nil } // HasRoutes returns whether the muxer has routes. func (m *Muxer) HasRoutes() bool { return len(m.routes) > 0 } // ParseHostSNI extracts the HostSNIs declared in a rule. // This is a first naive implementation used in TCP routing. func ParseHostSNI(rule string) ([]string, error) { var matchers []string for matcher := range tcpFuncs { matchers = append(matchers, matcher) } for matcher := range tcpFuncsV2 { matchers = append(matchers, matcher) } parser, err := rules.NewParser(matchers) if err != nil { return nil, err } parse, err := parser.Parse(rule) if err != nil { return nil, err } buildTree, ok := parse.(rules.TreeBuilder) if !ok { return nil, fmt.Errorf("error while parsing rule %s", rule) } return buildTree().ParseMatchers([]string{"HostSNI"}), nil } // routes implements sort.Interface. type routes []*route // Len implements sort.Interface. func (r routes) Len() int { return len(r) } // Swap implements sort.Interface. func (r routes) Swap(i, j int) { r[i], r[j] = r[j], r[i] } // Less implements sort.Interface. func (r routes) Less(i, j int) bool { return r[i].priority > r[j].priority } // route holds the matchers to match TCP route, // and the handler that will serve the connection. type route struct { // matchers tree structure reflecting the rule. matchers matchersTree // handler responsible for handling the route. handler tcp.Handler // catchAll indicates whether the route rule has exactly the catchAll value (HostSNI(`*`)). catchAll bool // priority is used to disambiguate between two (or more) rules that would // all match for a given request. // Computed from the matching rule length, if not user-set. priority int } // matchersTree represents the matchers tree structure. type matchersTree struct { // matcher is a matcher func used to match connection properties. // If matcher is not nil, it means that this matcherTree is a leaf of the tree. // It is therefore mutually exclusive with left and right. matcher func(ConnData) bool // operator to combine the evaluation of left and right leaves. operator string // Mutually exclusive with matcher. left *matchersTree right *matchersTree } func (m *matchersTree) match(meta ConnData) bool { if m == nil { // This should never happen as it should have been detected during parsing. log.Warn().Msg("Rule matcher is nil") return false } if m.matcher != nil { return m.matcher(meta) } switch m.operator { case "or": return m.left.match(meta) || m.right.match(meta) case "and": return m.left.match(meta) && m.right.match(meta) default: // This should never happen as it should have been detected during parsing. log.Warn().Str("operator", m.operator).Msg("Invalid rule operator") return false } } type matcherFuncs map[string]func(*matchersTree, ...string) error func (m *matchersTree) addRule(rule *rules.Tree, funcs matcherFuncs) error { switch rule.Matcher { case "and", "or": m.operator = rule.Matcher m.left = &matchersTree{} err := m.left.addRule(rule.RuleLeft, funcs) if err != nil { return err } m.right = &matchersTree{} return m.right.addRule(rule.RuleRight, funcs) default: err := rules.CheckRule(rule) if err != nil { return err } err = funcs[rule.Matcher](m, rule.Value...) if err != nil { return err } if rule.Not { matcherFunc := m.matcher m.matcher = func(meta ConnData) bool { return !matcherFunc(meta) } } } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/http/parser.go
pkg/muxer/http/parser.go
package http import ( "errors" "fmt" "maps" "slices" "strings" "github.com/traefik/traefik/v3/pkg/rules" "github.com/vulcand/predicate" ) type SyntaxParser struct { parsers map[string]*parser } type Options func(map[string]matcherBuilderFuncs) func WithMatcher(syntax, matcherName string, builderFunc func(params ...string) (MatcherFunc, error)) Options { return func(syntaxFuncs map[string]matcherBuilderFuncs) { syntax = strings.ToLower(syntax) syntaxFuncs[syntax][matcherName] = func(tree *matchersTree, s ...string) error { matcher, err := builderFunc(s...) if err != nil { return fmt.Errorf("building matcher: %w", err) } tree.matcher = matcher return nil } } } func NewSyntaxParser(opts ...Options) (SyntaxParser, error) { syntaxFuncs := map[string]matcherBuilderFuncs{ "v2": httpFuncsV2, "v3": httpFuncs, } for _, opt := range opts { opt(syntaxFuncs) } parsers := map[string]*parser{} for syntax, funcs := range syntaxFuncs { var err error parsers[syntax], err = newParser(funcs) if err != nil { return SyntaxParser{}, err } } return SyntaxParser{ parsers: parsers, }, nil } func (s SyntaxParser) parse(syntax string, rule string) (matchersTree, error) { parser, ok := s.parsers[syntax] if !ok { parser = s.parsers["v3"] } return parser.parse(rule) } func newParser(funcs matcherBuilderFuncs) (*parser, error) { p, err := rules.NewParser(slices.Collect(maps.Keys(funcs))) if err != nil { return nil, err } return &parser{ parser: p, matcherFuncs: funcs, }, nil } type parser struct { parser predicate.Parser matcherFuncs matcherBuilderFuncs } func (p *parser) parse(rule string) (matchersTree, error) { parse, err := p.parser.Parse(rule) if err != nil { return matchersTree{}, fmt.Errorf("parsing rule %s: %w", rule, err) } buildTree, ok := parse.(rules.TreeBuilder) if !ok { return matchersTree{}, errors.New("obtaining build tree") } var matchers matchersTree err = matchers.addRule(buildTree(), p.matcherFuncs) if err != nil { return matchersTree{}, fmt.Errorf("adding rule %s: %w", rule, err) } return matchers, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/http/matcher_test.go
pkg/muxer/http/matcher_test.go
package http import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/middlewares/requestdecorator" ) func TestClientIPMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid ClientIP matcher", rule: "ClientIP(`1`)", expectedError: true, }, { desc: "invalid ClientIP matcher (no parameter)", rule: "ClientIP()", expectedError: true, }, { desc: "invalid ClientIP matcher (empty parameter)", rule: "ClientIP(``)", expectedError: true, }, { desc: "invalid ClientIP matcher (too many parameters)", rule: "ClientIP(`127.0.0.1`, `192.168.1.0/24`)", expectedError: true, }, { desc: "valid ClientIP matcher", rule: "ClientIP(`127.0.0.1`)", expected: map[string]int{ "127.0.0.1": http.StatusOK, "192.168.1.1": http.StatusNotFound, }, }, { desc: "valid ClientIP matcher but invalid remote address", rule: "ClientIP(`127.0.0.1`)", expected: map[string]int{ "1": http.StatusNotFound, }, }, { desc: "valid ClientIP matcher using CIDR", rule: "ClientIP(`192.168.1.0/24`)", expected: map[string]int{ "192.168.1.1": http.StatusOK, "192.168.1.100": http.StatusOK, "192.168.2.1": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for remoteAddr := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "https://example.com", http.NoBody) req.RemoteAddr = remoteAddr muxer.ServeHTTP(w, req) results[remoteAddr] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestMethodMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid Method matcher (no parameter)", rule: "Method()", expectedError: true, }, { desc: "invalid Method matcher (empty parameter)", rule: "Method(``)", expectedError: true, }, { desc: "invalid Method matcher (too many parameters)", rule: "Method(`GET`, `POST`)", expectedError: true, }, { desc: "valid Method matcher", rule: "Method(`GET`)", expected: map[string]int{ http.MethodGet: http.StatusOK, http.MethodPost: http.StatusNotFound, strings.ToLower(http.MethodGet): http.StatusNotFound, }, }, { desc: "valid Method matcher (lower case)", rule: "Method(`get`)", expected: map[string]int{ http.MethodGet: http.StatusOK, http.MethodPost: http.StatusNotFound, strings.ToLower(http.MethodGet): http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for method := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(method, "https://example.com", http.NoBody) muxer.ServeHTTP(w, req) results[method] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestHostMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid Host matcher (no parameter)", rule: "Host()", expectedError: true, }, { desc: "invalid Host matcher (empty parameter)", rule: "Host(``)", expectedError: true, }, { desc: "invalid Host matcher (non-ASCII)", rule: "Host(`🦭.com`)", expectedError: true, }, { desc: "invalid Host matcher (too many parameters)", rule: "Host(`example.com`, `example.org`)", expectedError: true, }, { desc: "valid Host matcher", rule: "Host(`example.com`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com:8080": http.StatusOK, "https://example.com/path": http.StatusOK, "https://EXAMPLE.COM/path": http.StatusOK, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, { desc: "valid Host matcher - matcher ending with a dot", rule: "Host(`example.com.`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com/path": http.StatusOK, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, "https://example.com.": http.StatusOK, "https://example.com./path": http.StatusOK, "https://example.org.": http.StatusNotFound, "https://example.org./path": http.StatusNotFound, }, }, { desc: "valid Host matcher - URL ending with a dot", rule: "Host(`example.com`)", expected: map[string]int{ "https://example.com.": http.StatusOK, "https://example.com./path": http.StatusOK, "https://example.org.": http.StatusNotFound, "https://example.org./path": http.StatusNotFound, }, }, { desc: "valid Host matcher - matcher with UPPER case", rule: "Host(`EXAMPLE.COM`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com/path": http.StatusOK, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, { desc: "valid Host matcher - puny-coded emoji", rule: "Host(`xn--9t9h.com`)", expected: map[string]int{ "https://xn--9t9h.com": http.StatusOK, "https://xn--9t9h.com/path": http.StatusOK, "https://example.com": http.StatusNotFound, "https://example.com/path": http.StatusNotFound, // The request's sender must use puny-code. "https://🦭.com": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) // RequestDecorator is necessary for the Host matcher reqHost := requestdecorator.New(nil) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) reqHost.ServeHTTP(w, req, muxer.ServeHTTP) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestHostRegexpMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid HostRegexp matcher (no parameter)", rule: "HostRegexp()", expectedError: true, }, { desc: "invalid HostRegexp matcher (empty parameter)", rule: "HostRegexp(``)", expectedError: true, }, { desc: "invalid HostRegexp matcher (non-ASCII)", rule: "HostRegexp(`🦭.com`)", expectedError: true, }, { desc: "invalid HostRegexp matcher (invalid regexp)", rule: "HostRegexp(`(example.com`)", expectedError: true, }, { desc: "invalid HostRegexp matcher (too many parameters)", rule: "HostRegexp(`example.com`, `example.org`)", expectedError: true, }, { desc: "valid HostRegexp matcher", rule: "HostRegexp(`^[a-zA-Z-]+\\.com$`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com:8080": http.StatusOK, "https://example.com/path": http.StatusOK, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, { desc: "valid HostRegexp matcher with case sensitive regexp", rule: "HostRegexp(`^[A-Z]+\\.com$`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://EXAMPLE.com": http.StatusNotFound, "https://example.com/path": http.StatusNotFound, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, { desc: "valid HostRegexp matcher with Traefik v2 syntax", rule: "HostRegexp(`{domain:[a-zA-Z-]+\\.com}`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/path": http.StatusNotFound, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) // RequestDecorator is necessary for the HostRegexp matcher reqHost := requestdecorator.New(nil) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) reqHost.ServeHTTP(w, req, muxer.ServeHTTP) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestPathMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid Path matcher (no parameter)", rule: "Path()", expectedError: true, }, { desc: "invalid Path matcher (empty parameter)", rule: "Path(``)", expectedError: true, }, { desc: "invalid Path matcher (no leading /)", rule: "Path(`css`)", expectedError: true, }, { desc: "invalid Path matcher (too many parameters)", rule: "Path(`/css`, `/js`)", expectedError: true, }, { desc: "valid Path matcher", rule: "Path(`/css`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/html": http.StatusNotFound, "https://example.org/css": http.StatusOK, "https://example.com/css": http.StatusOK, "https://example.com/css/": http.StatusNotFound, "https://example.com/css/main.css": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) muxer.ServeHTTP(w, req) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestPathRegexpMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid PathRegexp matcher (no parameter)", rule: "PathRegexp()", expectedError: true, }, { desc: "invalid PathRegexp matcher (empty parameter)", rule: "PathRegexp(``)", expectedError: true, }, { desc: "invalid PathRegexp matcher (invalid regexp)", rule: "PathRegexp(`/(css`)", expectedError: true, }, { desc: "invalid PathRegexp matcher (too many parameters)", rule: "PathRegexp(`/css`, `/js`)", expectedError: true, }, { desc: "valid PathRegexp matcher", rule: "PathRegexp(`^/(css|js)`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/html": http.StatusNotFound, "https://example.org/css": http.StatusOK, "https://example.com/CSS": http.StatusNotFound, "https://example.com/css": http.StatusOK, "https://example.com/css/": http.StatusOK, "https://example.com/css/main.css": http.StatusOK, "https://example.com/js": http.StatusOK, "https://example.com/js/": http.StatusOK, "https://example.com/js/main.js": http.StatusOK, }, }, { desc: "valid PathRegexp matcher with Traefik v2 syntax", rule: `PathRegexp("/{path:(css|js)}")`, expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/html": http.StatusNotFound, "https://example.org/css": http.StatusNotFound, "https://example.com/{path:css}": http.StatusOK, "https://example.com/{path:css}/": http.StatusOK, "https://example.com/%7Bpath:css%7D": http.StatusOK, "https://example.com/%7Bpath:css%7D/": http.StatusOK, "https://example.com/{path:js}": http.StatusOK, "https://example.com/{path:js}/": http.StatusOK, "https://example.com/%7Bpath:js%7D": http.StatusOK, "https://example.com/%7Bpath:js%7D/": http.StatusOK, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) muxer.ServeHTTP(w, req) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestPathPrefixMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid PathPrefix matcher (no parameter)", rule: "PathPrefix()", expectedError: true, }, { desc: "invalid PathPrefix matcher (empty parameter)", rule: "PathPrefix(``)", expectedError: true, }, { desc: "invalid PathPrefix matcher (no leading /)", rule: "PathPrefix(`css`)", expectedError: true, }, { desc: "invalid PathPrefix matcher (too many parameters)", rule: "PathPrefix(`/css`, `/js`)", expectedError: true, }, { desc: "valid PathPrefix matcher", rule: `PathPrefix("/css")`, expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/html": http.StatusNotFound, "https://example.org/css": http.StatusOK, "https://example.com/css": http.StatusOK, "https://example.com/css/": http.StatusOK, "https://example.com/css/main.css": http.StatusOK, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) muxer.ServeHTTP(w, req) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestHeaderMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[*http.Header]int expectedError bool }{ { desc: "invalid Header matcher (no parameter)", rule: "Header()", expectedError: true, }, { desc: "invalid Header matcher (missing value parameter)", rule: "Header(`X-Forwarded-Host`)", expectedError: true, }, { desc: "invalid Header matcher (missing value parameter)", rule: "Header(`X-Forwarded-Host`, ``)", expectedError: true, }, { desc: "invalid Header matcher (missing key parameter)", rule: "Header(``, `example.com`)", expectedError: true, }, { desc: "invalid Header matcher (too many parameters)", rule: "Header(`X-Forwarded-Host`, `example.com`, `example.org`)", expectedError: true, }, { desc: "valid Header matcher", rule: "Header(`X-Forwarded-Proto`, `https`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"https"}}: http.StatusOK, {"x-forwarded-proto": []string{"https"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"http", "https"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"https", "http"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, { desc: "valid Header matcher (non-canonical form)", rule: "Header(`x-forwarded-proto`, `https`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"https"}}: http.StatusOK, {"x-forwarded-proto": []string{"https"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"http", "https"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"https", "http"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) for headers := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "https://example.com", http.NoBody) req.Header = *headers muxer.ServeHTTP(w, req) assert.Equal(t, test.expected[headers], w.Code, headers) } }) } } func TestHeaderRegexpMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[*http.Header]int expectedError bool }{ { desc: "invalid HeaderRegexp matcher (no parameter)", rule: "HeaderRegexp()", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (missing value parameter)", rule: "HeaderRegexp(`X-Forwarded-Host`)", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (missing value parameter)", rule: "HeaderRegexp(`X-Forwarded-Host`, ``)", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (missing key parameter)", rule: "HeaderRegexp(``, `example.com`)", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (invalid regexp)", rule: "HeaderRegexp(`X-Forwarded-Host`,`(example.com`)", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (too many parameters)", rule: "HeaderRegexp(`X-Forwarded-Host`, `example.com`, `example.org`)", expectedError: true, }, { desc: "valid HeaderRegexp matcher", rule: "HeaderRegexp(`X-Forwarded-Proto`, `^https?$`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"http"}}: http.StatusOK, {"x-forwarded-proto": []string{"http"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"https"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"HTTPS"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"ws", "https"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, { desc: "valid HeaderRegexp matcher (non-canonical form)", rule: "HeaderRegexp(`x-forwarded-proto`, `^https?$`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"http"}}: http.StatusOK, {"x-forwarded-proto": []string{"http"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"https"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"HTTPS"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"ws", "https"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, { desc: "valid HeaderRegexp matcher with Traefik v2 syntax", rule: "HeaderRegexp(`X-Forwarded-Proto`, `http{secure:s?}`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"http"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"https"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"http{secure:}"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"HTTP{secure:}"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"http{secure:s}"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"http{secure:S}"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"HTTPS"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"ws", "http{secure:s}"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) for headers := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "https://example.com", http.NoBody) req.Header = *headers muxer.ServeHTTP(w, req) assert.Equal(t, test.expected[headers], w.Code, *headers) } }) } } func TestQueryMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid Query matcher (no parameter)", rule: "Query()", expectedError: true, }, { desc: "invalid Query matcher (empty key, one parameter)", rule: "Query(``)", expectedError: true, }, { desc: "invalid Query matcher (empty key)", rule: "Query(``, `traefik`)", expectedError: true, }, { desc: "invalid Query matcher (empty value)", rule: "Query(`q`, ``)", expectedError: true, }, { desc: "invalid Query matcher (too many parameters)", rule: "Query(`q`, `traefik`, `proxy`)", expectedError: true, }, { desc: "valid Query matcher", rule: "Query(`q`, `traefik`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com?q=traefik": http.StatusOK, "https://example.com?rel=ddg&q=traefik": http.StatusOK, "https://example.com?q=traefik&q=proxy": http.StatusOK, "https://example.com?q=awesome&q=traefik": http.StatusOK, "https://example.com?q=nginx": http.StatusNotFound, "https://example.com?rel=ddg": http.StatusNotFound, "https://example.com?q=TRAEFIK": http.StatusNotFound, "https://example.com?Q=traefik": http.StatusNotFound, "https://example.com?rel=traefik": http.StatusNotFound, }, }, { desc: "valid Query matcher with empty value", rule: "Query(`mobile`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com?mobile": http.StatusOK, "https://example.com?mobile=true": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) muxer.ServeHTTP(w, req) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestQueryRegexpMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid QueryRegexp matcher (no parameter)", rule: "QueryRegexp()", expectedError: true, }, { desc: "invalid QueryRegexp matcher (empty parameter)", rule: "QueryRegexp(``)", expectedError: true, }, { desc: "invalid QueryRegexp matcher (invalid regexp)", rule: "QueryRegexp(`q`, `(traefik`)", expectedError: true, }, { desc: "invalid QueryRegexp matcher (too many parameters)", rule: "QueryRegexp(`q`, `traefik`, `proxy`)", expectedError: true, }, { desc: "valid QueryRegexp matcher", rule: "QueryRegexp(`q`, `^(traefik|nginx)$`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com?q=traefik": http.StatusOK, "https://example.com?rel=ddg&q=traefik": http.StatusOK, "https://example.com?q=traefik&q=proxy": http.StatusOK, "https://example.com?q=awesome&q=traefik": http.StatusOK, "https://example.com?q=TRAEFIK": http.StatusNotFound, "https://example.com?Q=traefik": http.StatusNotFound, "https://example.com?rel=traefik": http.StatusNotFound, "https://example.com?q=nginx": http.StatusOK, "https://example.com?rel=ddg&q=nginx": http.StatusOK, "https://example.com?q=nginx&q=proxy": http.StatusOK, "https://example.com?q=awesome&q=nginx": http.StatusOK, "https://example.com?q=NGINX": http.StatusNotFound, "https://example.com?Q=nginx": http.StatusNotFound, "https://example.com?rel=nginx": http.StatusNotFound, "https://example.com?q=haproxy": http.StatusNotFound, "https://example.com?rel=ddg": http.StatusNotFound, }, }, { desc: "valid QueryRegexp matcher", rule: "QueryRegexp(`q`, `^.*$`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com?q=traefik": http.StatusOK, "https://example.com?rel=ddg&q=traefik": http.StatusOK, "https://example.com?q=traefik&q=proxy": http.StatusOK, "https://example.com?q=awesome&q=traefik": http.StatusOK, "https://example.com?q=TRAEFIK": http.StatusOK, "https://example.com?Q=traefik": http.StatusNotFound, "https://example.com?rel=traefik": http.StatusNotFound, "https://example.com?q=nginx": http.StatusOK, "https://example.com?rel=ddg&q=nginx": http.StatusOK, "https://example.com?q=nginx&q=proxy": http.StatusOK, "https://example.com?q=awesome&q=nginx": http.StatusOK, "https://example.com?q=NGINX": http.StatusOK, "https://example.com?Q=nginx": http.StatusNotFound, "https://example.com?rel=nginx": http.StatusNotFound, "https://example.com?q=haproxy": http.StatusOK, "https://example.com?rel=ddg": http.StatusNotFound, }, }, { desc: "valid QueryRegexp matcher with Traefik v2 syntax", rule: "QueryRegexp(`q`, `{value:(traefik|nginx)}`)", expected: map[string]int{ "https://example.com?q=traefik": http.StatusNotFound, "https://example.com?q={value:traefik}": http.StatusOK, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) muxer.ServeHTTP(w, req) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/http/matcher_v2.go
pkg/muxer/http/matcher_v2.go
package http import ( "fmt" "net/http" "strings" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/ip" "github.com/traefik/traefik/v3/pkg/middlewares/requestdecorator" ) var httpFuncsV2 = matcherBuilderFuncs{ "Host": hostV2, "HostHeader": hostV2, "HostRegexp": hostRegexpV2, "ClientIP": clientIPV2, "Path": pathV2, "PathPrefix": pathPrefixV2, "Method": methodsV2, "Headers": headersV2, "HeadersRegexp": headersRegexpV2, "Query": queryV2, } func pathV2(tree *matchersTree, paths ...string) error { var routes []*mux.Route for _, path := range paths { route := mux.NewRouter().UseRoutingPath().NewRoute() if err := route.Path(path).GetError(); err != nil { return err } routes = append(routes, route) } tree.matcher = func(req *http.Request) bool { for _, route := range routes { if route.Match(req, &mux.RouteMatch{}) { return true } } return false } return nil } func pathPrefixV2(tree *matchersTree, paths ...string) error { var routes []*mux.Route for _, path := range paths { route := mux.NewRouter().UseRoutingPath().NewRoute() if err := route.PathPrefix(path).GetError(); err != nil { return err } routes = append(routes, route) } tree.matcher = func(req *http.Request) bool { for _, route := range routes { if route.Match(req, &mux.RouteMatch{}) { return true } } return false } return nil } func hostV2(tree *matchersTree, hosts ...string) error { for i, host := range hosts { if !IsASCII(host) { return fmt.Errorf("invalid value %q for \"Host\" matcher, non-ASCII characters are not allowed", host) } hosts[i] = strings.ToLower(host) } tree.matcher = func(req *http.Request) bool { reqHost := requestdecorator.GetCanonizedHost(req.Context()) if len(reqHost) == 0 { // If the request is an HTTP/1.0 request, then a Host may not be defined. if req.ProtoAtLeast(1, 1) { log.Ctx(req.Context()).Warn().Msgf("Could not retrieve CanonizedHost, rejecting %s", req.Host) } return false } flatH := requestdecorator.GetCNAMEFlatten(req.Context()) if len(flatH) > 0 { for _, host := range hosts { if strings.EqualFold(reqHost, host) || strings.EqualFold(flatH, host) { return true } log.Ctx(req.Context()).Debug().Msgf("CNAMEFlattening: request %s which resolved to %s, is not matched to route %s", reqHost, flatH, host) } return false } for _, host := range hosts { if reqHost == host { return true } // Check for match on trailing period on host if last := len(host) - 1; last >= 0 && host[last] == '.' { h := host[:last] if reqHost == h { return true } } // Check for match on trailing period on request if last := len(reqHost) - 1; last >= 0 && reqHost[last] == '.' { h := reqHost[:last] if h == host { return true } } } return false } return nil } func clientIPV2(tree *matchersTree, clientIPs ...string) error { checker, err := ip.NewChecker(clientIPs) if err != nil { return fmt.Errorf("could not initialize IP Checker for \"ClientIP\" matcher: %w", err) } strategy := ip.RemoteAddrStrategy{} tree.matcher = func(req *http.Request) bool { ok, err := checker.Contains(strategy.GetIP(req)) if err != nil { log.Ctx(req.Context()).Warn().Err(err).Msg("\"ClientIP\" matcher: could not match remote address") return false } return ok } return nil } func methodsV2(tree *matchersTree, methods ...string) error { route := mux.NewRouter().NewRoute() route.Methods(methods...) if err := route.GetError(); err != nil { return err } tree.matcher = func(req *http.Request) bool { return route.Match(req, &mux.RouteMatch{}) } return nil } func headersV2(tree *matchersTree, headers ...string) error { route := mux.NewRouter().NewRoute() route.Headers(headers...) if err := route.GetError(); err != nil { return err } tree.matcher = func(req *http.Request) bool { return route.Match(req, &mux.RouteMatch{}) } return nil } func queryV2(tree *matchersTree, query ...string) error { var queries []string for _, elem := range query { queries = append(queries, strings.SplitN(elem, "=", 2)...) } route := mux.NewRouter().NewRoute() route.Queries(queries...) if err := route.GetError(); err != nil { return err } tree.matcher = func(req *http.Request) bool { return route.Match(req, &mux.RouteMatch{}) } return nil } func hostRegexpV2(tree *matchersTree, hosts ...string) error { router := mux.NewRouter() for _, host := range hosts { if !IsASCII(host) { return fmt.Errorf("invalid value %q for HostRegexp matcher, non-ASCII characters are not allowed", host) } tmpRt := router.Host(host) if tmpRt.GetError() != nil { return tmpRt.GetError() } } tree.matcher = func(req *http.Request) bool { return router.Match(req, &mux.RouteMatch{}) } return nil } func headersRegexpV2(tree *matchersTree, headers ...string) error { route := mux.NewRouter().NewRoute() route.HeadersRegexp(headers...) if err := route.GetError(); err != nil { return err } tree.matcher = func(req *http.Request) bool { return route.Match(req, &mux.RouteMatch{}) } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/http/mux_test.go
pkg/muxer/http/mux_test.go
package http import ( "bufio" "bytes" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/middlewares/requestdecorator" "github.com/traefik/traefik/v3/pkg/testhelpers" ) func TestMuxer(t *testing.T) { testCases := []struct { desc string rule string headers map[string]string remoteAddr string expected map[string]int expectedError bool }{ { desc: "no tree", expectedError: true, }, { desc: "Rule with no matcher", rule: "rulewithnotmatcher", expectedError: true, }, { desc: "Rule without quote", rule: "Host(example.com)", expectedError: true, }, { desc: "Host IPv4", rule: "Host(`127.0.0.1`)", expected: map[string]int{ "http://127.0.0.1/foo": http.StatusOK, }, }, { desc: "Host IPv6", rule: "Host(`10::10`)", expected: map[string]int{ "http://10::10/foo": http.StatusOK, }, }, { desc: "Host and PathPrefix", rule: "Host(`localhost`) && PathPrefix(`/css`)", expected: map[string]int{ "https://localhost/css": http.StatusOK, "https://localhost/js": http.StatusNotFound, }, }, { desc: "Rule with Host OR Host", rule: "Host(`example.com`) || Host(`example.org`)", expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.org/js": http.StatusOK, "https://example.eu/html": http.StatusNotFound, }, }, { desc: "Rule with host OR (host AND path)", rule: `Host("example.com") || (Host("example.org") && Path("/css"))`, expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.com/js": http.StatusOK, "https://example.org/css": http.StatusOK, "https://example.org/js": http.StatusNotFound, "https://example.eu/css": http.StatusNotFound, }, }, { desc: "Rule with host OR host AND path", rule: `Host("example.com") || Host("example.org") && Path("/css")`, expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.com/js": http.StatusOK, "https://example.org/css": http.StatusOK, "https://example.org/js": http.StatusNotFound, "https://example.eu/css": http.StatusNotFound, }, }, { desc: "Rule with (host OR host) AND path", rule: `(Host("example.com") || Host("example.org")) && Path("/css")`, expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.com/js": http.StatusNotFound, "https://example.org/css": http.StatusOK, "https://example.org/js": http.StatusNotFound, "https://example.eu/css": http.StatusNotFound, }, }, { desc: "Rule with (host AND path) OR (host AND path)", rule: `(Host("example.com") && Path("/js")) || ((Host("example.org")) && Path("/css"))`, expected: map[string]int{ "https://example.com/css": http.StatusNotFound, "https://example.com/js": http.StatusOK, "https://example.org/css": http.StatusOK, "https://example.org/js": http.StatusNotFound, "https://example.eu/css": http.StatusNotFound, }, }, { desc: "Rule case UPPER", rule: `PATHPREFIX("/css")`, expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.com/js": http.StatusNotFound, }, }, { desc: "Rule case lower", rule: `pathprefix("/css")`, expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.com/js": http.StatusNotFound, }, }, { desc: "Rule case CamelCase", rule: `PathPrefix("/css")`, expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.com/js": http.StatusNotFound, }, }, { desc: "Rule case Title", rule: `Pathprefix("/css")`, expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.com/js": http.StatusNotFound, }, }, { desc: "Rule with not", rule: `!Host("example.com")`, expected: map[string]int{ "https://example.org": http.StatusOK, "https://example.com": http.StatusNotFound, }, }, { desc: "Rule with not on multiple route with or", rule: `!(Host("example.com") || Host("example.org"))`, expected: map[string]int{ "https://example.eu/js": http.StatusOK, "https://example.com/css": http.StatusNotFound, "https://example.org/js": http.StatusNotFound, }, }, { desc: "Rule with not on multiple route with and", rule: `!(Host("example.com") && Path("/css"))`, expected: map[string]int{ "https://example.com/js": http.StatusOK, "https://example.eu/css": http.StatusOK, "https://example.com/css": http.StatusNotFound, }, }, { desc: "Rule with not on multiple route with and another not", rule: `!(Host("example.com") && !Path("/css"))`, expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.org/css": http.StatusOK, "https://example.com/js": http.StatusNotFound, }, }, { desc: "Rule with not on two rule", rule: `!Host("example.com") || !Path("/css")`, expected: map[string]int{ "https://example.com/js": http.StatusOK, "https://example.org/css": http.StatusOK, "https://example.com/css": http.StatusNotFound, }, }, { desc: "Rule case with double not", rule: `!(!(Host("example.com") && Pathprefix("/css")))`, expected: map[string]int{ "https://example.com/css": http.StatusOK, "https://example.com/js": http.StatusNotFound, "https://example.org/css": http.StatusNotFound, }, }, { desc: "Rule case with not domain", rule: `!Host("example.com") && Pathprefix("/css")`, expected: map[string]int{ "https://example.org/css": http.StatusOK, "https://example.org/js": http.StatusNotFound, "https://example.com/css": http.StatusNotFound, "https://example.com/js": http.StatusNotFound, }, }, { desc: "Rule with multiple host AND multiple path AND not", rule: `!(Host("example.com") && Path("/js"))`, expected: map[string]int{ "https://example.com/js": http.StatusNotFound, "https://example.com/html": http.StatusOK, "https://example.org/js": http.StatusOK, "https://example.com/css": http.StatusOK, "https://example.org/css": http.StatusOK, "https://example.org/html": http.StatusOK, "https://example.eu/images": http.StatusOK, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) err = muxer.AddRoute(test.rule, "", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) // RequestDecorator is necessary for the host rule reqHost := requestdecorator.New(nil) results := make(map[string]int) for calledURL := range test.expected { req := testhelpers.MustNewRequest(http.MethodGet, calledURL, http.NoBody) // Useful for the ClientIP matcher req.RemoteAddr = test.remoteAddr for key, value := range test.headers { req.Header.Set(key, value) } w := httptest.NewRecorder() reqHost.ServeHTTP(w, req, muxer.ServeHTTP) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func Test_addRoutePriority(t *testing.T) { type Case struct { xFrom string rule string priority int } testCases := []struct { desc string path string cases []Case expected string }{ { desc: "Higher priority on second rule", path: "/my", cases: []Case{ { xFrom: "header1", rule: "PathPrefix(`/my`)", priority: 10, }, { xFrom: "header2", rule: "PathPrefix(`/my`)", priority: 20, }, }, expected: "header2", }, { desc: "Higher priority on first rule", path: "/my", cases: []Case{ { xFrom: "header1", rule: "PathPrefix(`/my`)", priority: 20, }, { xFrom: "header2", rule: "PathPrefix(`/my`)", priority: 10, }, }, expected: "header1", }, { desc: "Higher priority on second rule with different rule", path: "/mypath", cases: []Case{ { xFrom: "header1", rule: "PathPrefix(`/mypath`)", priority: 10, }, { xFrom: "header2", rule: "PathPrefix(`/my`)", priority: 20, }, }, expected: "header2", }, { desc: "Higher priority on longest rule (longest first)", path: "/mypath", cases: []Case{ { xFrom: "header1", rule: "PathPrefix(`/mypath`)", }, { xFrom: "header2", rule: "PathPrefix(`/my`)", }, }, expected: "header1", }, { desc: "Higher priority on longest rule (longest second)", path: "/mypath", cases: []Case{ { xFrom: "header1", rule: "PathPrefix(`/my`)", }, { xFrom: "header2", rule: "PathPrefix(`/mypath`)", }, }, expected: "header2", }, { desc: "Higher priority on longest rule (longest third)", path: "/mypath", cases: []Case{ { xFrom: "header1", rule: "PathPrefix(`/my`)", }, { xFrom: "header2", rule: "PathPrefix(`/mypa`)", }, { xFrom: "header3", rule: "PathPrefix(`/mypath`)", }, }, expected: "header3", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) for _, route := range test.cases { handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-From", route.xFrom) }) if route.priority == 0 { route.priority = GetRulePriority(route.rule) } err := muxer.AddRoute(route.rule, "", route.priority, handler) require.NoError(t, err, route.rule) } w := httptest.NewRecorder() req := testhelpers.MustNewRequest(http.MethodGet, test.path, http.NoBody) muxer.ServeHTTP(w, req) assert.Equal(t, test.expected, w.Header().Get("X-From")) }) } } func TestParseDomains(t *testing.T) { testCases := []struct { description string expression string domain []string errorExpected bool }{ { description: "Unknown rule", expression: "Foobar(`foo.bar`,`test.bar`)", errorExpected: true, }, { description: "No host rule", expression: "Path(`/test`)", }, { description: "Host rule and another rule", expression: "Host(`foo.bar`) && Path(`/test`)", domain: []string{"foo.bar"}, }, { description: "Host rule to trim and another rule", expression: "Host(`Foo.Bar`) || Host(`bar.buz`) && Path(`/test`)", domain: []string{"foo.bar", "bar.buz"}, }, { description: "Host rule to trim and another rule", expression: "Host(`Foo.Bar`) && Path(`/test`)", domain: []string{"foo.bar"}, }, { description: "Host rule with no domain", expression: "Host() && Path(`/test`)", }, } for _, test := range testCases { t.Run(test.expression, func(t *testing.T) { t.Parallel() domains, err := ParseDomains(test.expression) if test.errorExpected { require.Errorf(t, err, "unable to parse correctly the domains in the Host rule from %q", test.expression) } else { require.NoError(t, err, "%s: Error while parsing domain.", test.expression) } assert.Equal(t, test.domain, domains, "%s: Error parsing domains from expression.", test.expression) }) } } // TestEmptyHost is a non regression test for // https://github.com/traefik/traefik/pull/9131 func TestEmptyHost(t *testing.T) { testCases := []struct { desc string request string rule string expected int }{ { desc: "HostRegexp with absolute-form URL with empty host with non-matching host header", request: "GET http://@/ HTTP/1.1\r\nHost: example.com\r\n\r\n", rule: "HostRegexp(`example.com`)", expected: http.StatusOK, }, { desc: "Host with absolute-form URL with empty host with non-matching host header", request: "GET http://@/ HTTP/1.1\r\nHost: example.com\r\n\r\n", rule: "Host(`example.com`)", expected: http.StatusOK, }, { desc: "HostRegexp with absolute-form URL with matching host header", request: "GET http://example.com/ HTTP/1.1\r\nHost: example.org\r\n\r\n", rule: "HostRegexp(`example.com`)", expected: http.StatusOK, }, { desc: "Host with absolute-form URL with matching host header", request: "GET http://example.com/ HTTP/1.1\r\nHost: example.org\r\n\r\n", rule: "Host(`example.com`)", expected: http.StatusOK, }, { desc: "HostRegexp with absolute-form URL with non-matching host header", request: "GET http://example.com/ HTTP/1.1\r\nHost: example.org\r\n\r\n", rule: "HostRegexp(`example.org`)", expected: http.StatusNotFound, }, { desc: "Host with absolute-form URL with non-matching host header", request: "GET http://example.com/ HTTP/1.1\r\nHost: example.org\r\n\r\n", rule: "Host(`example.org`)", expected: http.StatusNotFound, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "", 0, handler) require.NoError(t, err) // RequestDecorator is necessary for the host rule reqHost := requestdecorator.New(nil) w := httptest.NewRecorder() req, err := http.ReadRequest(bufio.NewReader(bytes.NewReader([]byte(test.request)))) require.NoError(t, err) reqHost.ServeHTTP(w, req, muxer.ServeHTTP) assert.Equal(t, test.expected, w.Code) }) } } func TestGetRulePriority(t *testing.T) { testCases := []struct { desc string rule string expected int }{ { desc: "simple rule", rule: "Host(`example.org`)", expected: 19, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() assert.Equal(t, test.expected, GetRulePriority(test.rule)) }) } } func TestRoutingPath(t *testing.T) { tests := []struct { desc string path string expectedRoutingPath string }{ { desc: "unallowed percent-encoded character is decoded", path: "/foo%20bar", expectedRoutingPath: "/foo bar", }, { desc: "reserved percent-encoded character is kept encoded", path: "/foo%2Fbar", expectedRoutingPath: "/foo%2Fbar", }, { desc: "multiple mixed characters", path: "/foo%20bar%2Fbaz%23qux", expectedRoutingPath: "/foo bar%2Fbaz%23qux", }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() req := httptest.NewRequest(http.MethodGet, "http://foo"+test.path, http.NoBody) var err error req, err = withRoutingPath(req) require.NoError(t, err) gotRoutingPath := getRoutingPath(req) assert.NotNil(t, gotRoutingPath) assert.Equal(t, test.expectedRoutingPath, *gotRoutingPath) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/http/matcher.go
pkg/muxer/http/matcher.go
package http import ( "fmt" "net/http" "regexp" "slices" "strings" "unicode/utf8" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/ip" "github.com/traefik/traefik/v3/pkg/middlewares/requestdecorator" ) var httpFuncs = matcherBuilderFuncs{ "ClientIP": expectNParameters(clientIP, 1), "Method": expectNParameters(method, 1), "Host": expectNParameters(host, 1), "HostRegexp": expectNParameters(hostRegexp, 1), "Path": expectNParameters(path, 1), "PathRegexp": expectNParameters(pathRegexp, 1), "PathPrefix": expectNParameters(pathPrefix, 1), "Header": expectNParameters(header, 2), "HeaderRegexp": expectNParameters(headerRegexp, 2), "Query": expectNParameters(query, 1, 2), "QueryRegexp": expectNParameters(queryRegexp, 1, 2), } func expectNParameters(fn func(*matchersTree, ...string) error, n ...int) func(*matchersTree, ...string) error { return func(tree *matchersTree, s ...string) error { if !slices.Contains(n, len(s)) { return fmt.Errorf("unexpected number of parameters; got %d, expected one of %v", len(s), n) } return fn(tree, s...) } } func clientIP(tree *matchersTree, clientIP ...string) error { checker, err := ip.NewChecker(clientIP) if err != nil { return fmt.Errorf("initializing IP checker for ClientIP matcher: %w", err) } strategy := ip.RemoteAddrStrategy{} tree.matcher = func(req *http.Request) bool { ok, err := checker.Contains(strategy.GetIP(req)) if err != nil { log.Ctx(req.Context()).Warn().Err(err).Msg("ClientIP matcher: could not match remote address") return false } return ok } return nil } func method(tree *matchersTree, methods ...string) error { method := strings.ToUpper(methods[0]) tree.matcher = func(req *http.Request) bool { return method == req.Method } return nil } func host(tree *matchersTree, hosts ...string) error { host := hosts[0] if !IsASCII(host) { return fmt.Errorf("invalid value %q for Host matcher, non-ASCII characters are not allowed", host) } host = strings.ToLower(host) tree.matcher = func(req *http.Request) bool { reqHost := requestdecorator.GetCanonizedHost(req.Context()) if len(reqHost) == 0 { return false } if reqHost == host { return true } flatH := requestdecorator.GetCNAMEFlatten(req.Context()) if len(flatH) > 0 { return strings.EqualFold(flatH, host) } // Check for match on trailing period on host if last := len(host) - 1; last >= 0 && host[last] == '.' { h := host[:last] if reqHost == h { return true } } // Check for match on trailing period on request if last := len(reqHost) - 1; last >= 0 && reqHost[last] == '.' { h := reqHost[:last] if h == host { return true } } return false } return nil } func hostRegexp(tree *matchersTree, hosts ...string) error { host := hosts[0] if !IsASCII(host) { return fmt.Errorf("invalid value %q for HostRegexp matcher, non-ASCII characters are not allowed", host) } re, err := regexp.Compile(host) if err != nil { return fmt.Errorf("compiling HostRegexp matcher: %w", err) } tree.matcher = func(req *http.Request) bool { return re.MatchString(requestdecorator.GetCanonizedHost(req.Context())) || re.MatchString(requestdecorator.GetCNAMEFlatten(req.Context())) } return nil } func path(tree *matchersTree, paths ...string) error { path := paths[0] if !strings.HasPrefix(path, "/") { return fmt.Errorf("path %q does not start with a '/'", path) } tree.matcher = func(req *http.Request) bool { routingPath := getRoutingPath(req) return routingPath != nil && *routingPath == path } return nil } func pathRegexp(tree *matchersTree, paths ...string) error { path := paths[0] re, err := regexp.Compile(path) if err != nil { return fmt.Errorf("compiling PathPrefix matcher: %w", err) } tree.matcher = func(req *http.Request) bool { routingPath := getRoutingPath(req) return routingPath != nil && re.MatchString(*routingPath) } return nil } func pathPrefix(tree *matchersTree, paths ...string) error { path := paths[0] if !strings.HasPrefix(path, "/") { return fmt.Errorf("path %q does not start with a '/'", path) } tree.matcher = func(req *http.Request) bool { routingPath := getRoutingPath(req) return routingPath != nil && strings.HasPrefix(*routingPath, path) } return nil } func header(tree *matchersTree, headers ...string) error { key, value := http.CanonicalHeaderKey(headers[0]), headers[1] tree.matcher = func(req *http.Request) bool { for _, headerValue := range req.Header[key] { if headerValue == value { return true } } return false } return nil } func headerRegexp(tree *matchersTree, headers ...string) error { key, value := http.CanonicalHeaderKey(headers[0]), headers[1] re, err := regexp.Compile(value) if err != nil { return fmt.Errorf("compiling HeaderRegexp matcher: %w", err) } tree.matcher = func(req *http.Request) bool { for _, headerValue := range req.Header[key] { if re.MatchString(headerValue) { return true } } return false } return nil } func query(tree *matchersTree, queries ...string) error { key := queries[0] var value string if len(queries) == 2 { value = queries[1] } tree.matcher = func(req *http.Request) bool { values, ok := req.URL.Query()[key] if !ok { return false } return slices.Contains(values, value) } return nil } func queryRegexp(tree *matchersTree, queries ...string) error { if len(queries) == 1 { return query(tree, queries...) } key, value := queries[0], queries[1] re, err := regexp.Compile(value) if err != nil { return fmt.Errorf("compiling QueryRegexp matcher: %w", err) } tree.matcher = func(req *http.Request) bool { values, ok := req.URL.Query()[key] if !ok { return false } idx := slices.IndexFunc(values, func(value string) bool { return re.MatchString(value) }) return idx >= 0 } return nil } // IsASCII checks if the given string contains only ASCII characters. func IsASCII(s string) bool { for i := range len(s) { if s[i] >= utf8.RuneSelf { return false } } return true }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/http/matcher_v2_test.go
pkg/muxer/http/matcher_v2_test.go
package http import ( "net/http" "net/http/httptest" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/middlewares/requestdecorator" "github.com/traefik/traefik/v3/pkg/testhelpers" ) func TestClientIPV2Matcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid ClientIP matcher", rule: "ClientIP(`1`)", expectedError: true, }, { desc: "invalid ClientIP matcher (no parameter)", rule: "ClientIP()", expectedError: true, }, { desc: "invalid ClientIP matcher (empty parameter)", rule: "ClientIP(``)", expectedError: true, }, { desc: "valid ClientIP matcher (many parameters)", rule: "ClientIP(`127.0.0.1`, `192.168.1.0/24`)", expected: map[string]int{ "127.0.0.1": http.StatusOK, "192.168.1.1": http.StatusOK, }, }, { desc: "valid ClientIP matcher", rule: "ClientIP(`127.0.0.1`)", expected: map[string]int{ "127.0.0.1": http.StatusOK, "192.168.1.1": http.StatusNotFound, }, }, { desc: "valid ClientIP matcher but invalid remote address", rule: "ClientIP(`127.0.0.1`)", expected: map[string]int{ "1": http.StatusNotFound, }, }, { desc: "valid ClientIP matcher using CIDR", rule: "ClientIP(`192.168.1.0/24`)", expected: map[string]int{ "192.168.1.1": http.StatusOK, "192.168.1.100": http.StatusOK, "192.168.2.1": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "v2", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for remoteAddr := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "https://example.com", http.NoBody) req.RemoteAddr = remoteAddr muxer.ServeHTTP(w, req) results[remoteAddr] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestMethodV2Matcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid Method matcher (no parameter)", rule: "Method()", expectedError: true, }, { desc: "invalid Method matcher (empty parameter)", rule: "Method(``)", expectedError: true, }, { desc: "valid Method matcher (many parameters)", rule: "Method(`GET`, `POST`)", expected: map[string]int{ http.MethodGet: http.StatusOK, http.MethodPost: http.StatusOK, }, }, { desc: "valid Method matcher", rule: "Method(`GET`)", expected: map[string]int{ http.MethodGet: http.StatusOK, http.MethodPost: http.StatusNotFound, strings.ToLower(http.MethodGet): http.StatusNotFound, }, }, { desc: "valid Method matcher (lower case)", rule: "Method(`get`)", expected: map[string]int{ http.MethodGet: http.StatusOK, http.MethodPost: http.StatusNotFound, strings.ToLower(http.MethodGet): http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "v2", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for method := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(method, "https://example.com", http.NoBody) muxer.ServeHTTP(w, req) results[method] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestHostV2Matcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid Host matcher (no parameter)", rule: "Host()", expectedError: true, }, { desc: "invalid Host matcher (empty parameter)", rule: "Host(``)", expectedError: true, }, { desc: "invalid Host matcher (non-ASCII)", rule: "Host(`🦭.com`)", expectedError: true, }, { desc: "valid Host matcher (many parameters)", rule: "Host(`example.com`, `example.org`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com:8080": http.StatusOK, "https://example.com/path": http.StatusOK, "https://EXAMPLE.COM/path": http.StatusOK, "https://example.org": http.StatusOK, "https://example.org/path": http.StatusOK, }, }, { desc: "valid Host matcher", rule: "Host(`example.com`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com:8080": http.StatusOK, "https://example.com/path": http.StatusOK, "https://EXAMPLE.COM/path": http.StatusOK, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, { desc: "valid Host matcher - matcher ending with a dot", rule: "Host(`example.com.`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com/path": http.StatusOK, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, "https://example.com.": http.StatusOK, "https://example.com./path": http.StatusOK, "https://example.org.": http.StatusNotFound, "https://example.org./path": http.StatusNotFound, }, }, { desc: "valid Host matcher - URL ending with a dot", rule: "Host(`example.com`)", expected: map[string]int{ "https://example.com.": http.StatusOK, "https://example.com./path": http.StatusOK, "https://example.org.": http.StatusNotFound, "https://example.org./path": http.StatusNotFound, }, }, { desc: "valid Host matcher - matcher with UPPER case", rule: "Host(`EXAMPLE.COM`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com/path": http.StatusOK, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, { desc: "valid Host matcher - puny-coded emoji", rule: "Host(`xn--9t9h.com`)", expected: map[string]int{ "https://xn--9t9h.com": http.StatusOK, "https://xn--9t9h.com/path": http.StatusOK, "https://example.com": http.StatusNotFound, "https://example.com/path": http.StatusNotFound, // The request's sender must use puny-code. "https://🦭.com": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "v2", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) // RequestDecorator is necessary for the Host matcher reqHost := requestdecorator.New(nil) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) reqHost.ServeHTTP(w, req, muxer.ServeHTTP) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestHostRegexpV2Matcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid HostRegexp matcher (no parameter)", rule: "HostRegexp()", expectedError: true, }, { desc: "invalid HostRegexp matcher (empty parameter)", rule: "HostRegexp(``)", expectedError: true, }, { desc: "invalid HostRegexp matcher (non-ASCII)", rule: "HostRegexp(`🦭.com`)", expectedError: true, }, { desc: "valid HostRegexp matcher (invalid regexp)", rule: "HostRegexp(`(example.com`)", // This is weird. expectedError: false, expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com:8080": http.StatusNotFound, "https://example.com/path": http.StatusNotFound, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, { desc: "valid HostRegexp matcher (many parameters)", rule: "HostRegexp(`example.com`, `example.org`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com:8080": http.StatusOK, "https://example.com/path": http.StatusOK, "https://example.org": http.StatusOK, "https://example.org/path": http.StatusOK, }, }, { desc: "valid HostRegexp matcher with case sensitive regexp", rule: "HostRegexp(`^[A-Z]+\\.com$`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://EXAMPLE.com": http.StatusNotFound, "https://example.com/path": http.StatusNotFound, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, { desc: "valid HostRegexp matcher with Traefik v2 syntax", rule: "HostRegexp(`{domain:[a-zA-Z-]+\\.com}`)", expected: map[string]int{ "https://example.com": http.StatusOK, "https://example.com/path": http.StatusOK, "https://example.org": http.StatusNotFound, "https://example.org/path": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "v2", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) // RequestDecorator is necessary for the HostRegexp matcher reqHost := requestdecorator.New(nil) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) reqHost.ServeHTTP(w, req, muxer.ServeHTTP) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestPathV2Matcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid Path matcher (no parameter)", rule: "Path()", expectedError: true, }, { desc: "invalid Path matcher (empty parameter)", rule: "Path(``)", expectedError: true, }, { desc: "invalid Path matcher (no leading /)", rule: "Path(`css`)", expectedError: true, }, { desc: "valid Path matcher (many parameters)", rule: "Path(`/css`, `/js`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/html": http.StatusNotFound, "https://example.org/css": http.StatusOK, "https://example.com/css": http.StatusOK, "https://example.com/css/": http.StatusNotFound, "https://example.com/css/main.css": http.StatusNotFound, "https://example.com/js": http.StatusOK, "https://example.com/js/main.js": http.StatusNotFound, }, }, { desc: "valid Path matcher", rule: "Path(`/css`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/html": http.StatusNotFound, "https://example.org/css": http.StatusOK, "https://example.com/css": http.StatusOK, "https://example.com/css/": http.StatusNotFound, "https://example.com/css/main.css": http.StatusNotFound, }, }, { desc: "valid Path matcher with regexp", rule: "Path(`/css{path:(/.*)?}`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/css/main.css": http.StatusOK, "https://example.org/css/main.css": http.StatusOK, "https://example.com/css/components/component.css": http.StatusOK, "https://example.com/css.css": http.StatusNotFound, "https://example.com/js/main.js": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "v2", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) muxer.ServeHTTP(w, req) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestPathPrefixV2Matcher(t *testing.T) { testCases := []struct { desc string rule string expected map[string]int expectedError bool }{ { desc: "invalid PathPrefix matcher (no parameter)", rule: "PathPrefix()", expectedError: true, }, { desc: "invalid PathPrefix matcher (empty parameter)", rule: "PathPrefix(``)", expectedError: true, }, { desc: "invalid PathPrefix matcher (no leading /)", rule: "PathPrefix(`css`)", expectedError: true, }, { desc: "valid PathPrefix matcher (many parameters)", rule: "PathPrefix(`/css`, `/js`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/html": http.StatusNotFound, "https://example.org/css": http.StatusOK, "https://example.com/css": http.StatusOK, "https://example.com/css/": http.StatusOK, "https://example.com/css/main.css": http.StatusOK, "https://example.com/js/": http.StatusOK, "https://example.com/js/main.js": http.StatusOK, }, }, { desc: "valid PathPrefix matcher", rule: `PathPrefix("/css")`, expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/html": http.StatusNotFound, "https://example.org/css": http.StatusOK, "https://example.com/css": http.StatusOK, "https://example.com/css/": http.StatusOK, "https://example.com/css/main.css": http.StatusOK, }, }, { desc: "valid PathPrefix matcher with regexp", rule: "PathPrefix(`/css-{name:[0-9]?}`)", expected: map[string]int{ "https://example.com": http.StatusNotFound, "https://example.com/css-1/main.css": http.StatusOK, "https://example.org/css-222/main.css": http.StatusOK, "https://example.com/css-333333/components/component.css": http.StatusOK, "https://example.com/css.css": http.StatusNotFound, "https://example.com/js/main.js": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "v2", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) results := make(map[string]int) for calledURL := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) muxer.ServeHTTP(w, req) results[calledURL] = w.Code } assert.Equal(t, test.expected, results) }) } } func TestHeadersMatcher(t *testing.T) { testCases := []struct { desc string rule string expected map[*http.Header]int expectedError bool }{ { desc: "invalid Header matcher (no parameter)", rule: "Headers()", expectedError: true, }, { desc: "invalid Header matcher (missing value parameter)", rule: "Headers(`X-Forwarded-Host`)", expectedError: true, }, { desc: "invalid Header matcher (missing value parameter)", rule: "Headers(`X-Forwarded-Host`, ``)", expectedError: true, }, { desc: "invalid Header matcher (missing key parameter)", rule: "Headers(``, `example.com`)", expectedError: true, }, { desc: "invalid Header matcher (too many parameters)", rule: "Headers(`X-Forwarded-Host`, `example.com`, `example.org`)", expectedError: true, }, { desc: "valid Header matcher", rule: "Headers(`X-Forwarded-Proto`, `https`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"https"}}: http.StatusOK, {"x-forwarded-proto": []string{"https"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"http", "https"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"https", "http"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, { desc: "valid Header matcher (non-canonical form)", rule: "Headers(`x-forwarded-proto`, `https`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"https"}}: http.StatusOK, {"x-forwarded-proto": []string{"https"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"http", "https"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"https", "http"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "v2", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) for headers := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "https://example.com", http.NoBody) req.Header = *headers muxer.ServeHTTP(w, req) assert.Equal(t, test.expected[headers], w.Code, headers) } }) } } func TestHeaderRegexpV2Matcher(t *testing.T) { testCases := []struct { desc string rule string expected map[*http.Header]int expectedError bool }{ { desc: "invalid HeaderRegexp matcher (no parameter)", rule: "HeaderRegexp()", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (missing value parameter)", rule: "HeadersRegexp(`X-Forwarded-Host`)", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (missing value parameter)", rule: "HeadersRegexp(`X-Forwarded-Host`, ``)", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (missing key parameter)", rule: "HeadersRegexp(``, `example.com`)", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (invalid regexp)", rule: "HeadersRegexp(`X-Forwarded-Host`,`(example.com`)", expectedError: true, }, { desc: "invalid HeaderRegexp matcher (too many parameters)", rule: "HeadersRegexp(`X-Forwarded-Host`, `example.com`, `example.org`)", expectedError: true, }, { desc: "valid HeaderRegexp matcher", rule: "HeadersRegexp(`X-Forwarded-Proto`, `^https?$`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"http"}}: http.StatusOK, {"x-forwarded-proto": []string{"http"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"https"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"HTTPS"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"ws", "https"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, { desc: "valid HeaderRegexp matcher (non-canonical form)", rule: "HeadersRegexp(`x-forwarded-proto`, `^https?$`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"http"}}: http.StatusOK, {"x-forwarded-proto": []string{"http"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"https"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"HTTPS"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"ws", "https"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, { desc: "valid HeaderRegexp matcher with Traefik v2 syntax", rule: "HeadersRegexp(`X-Forwarded-Proto`, `http{secure:s?}`)", expected: map[*http.Header]int{ {"X-Forwarded-Proto": []string{"http"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"https"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"http{secure:}"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"HTTP{secure:}"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"http{secure:s}"}}: http.StatusOK, {"X-Forwarded-Proto": []string{"http{secure:S}"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"HTTPS"}}: http.StatusNotFound, {"X-Forwarded-Proto": []string{"ws", "http{secure:s}"}}: http.StatusOK, {"X-Forwarded-Host": []string{"example.com"}}: http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.rule, "v2", 0, handler) if test.expectedError { require.Error(t, err) return } require.NoError(t, err) for headers := range test.expected { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, "https://example.com", http.NoBody) req.Header = *headers muxer.ServeHTTP(w, req) assert.Equal(t, test.expected[headers], w.Code, *headers) } }) } } func TestHostRegexp(t *testing.T) { testCases := []struct { desc string hostExp string urls map[string]int }{ { desc: "capturing group", hostExp: "HostRegexp(`{subdomain:(foo\\.)?bar\\.com}`)", urls: map[string]int{ "http://foo.bar.com": http.StatusOK, "http://bar.com": http.StatusOK, "http://fooubar.com": http.StatusNotFound, "http://barucom": http.StatusNotFound, "http://barcom": http.StatusNotFound, }, }, { desc: "non capturing group", hostExp: "HostRegexp(`{subdomain:(?:foo\\.)?bar\\.com}`)", urls: map[string]int{ "http://foo.bar.com": http.StatusOK, "http://bar.com": http.StatusOK, "http://fooubar.com": http.StatusNotFound, "http://barucom": http.StatusNotFound, "http://barcom": http.StatusNotFound, }, }, { desc: "regex insensitive", hostExp: "HostRegexp(`{dummy:[A-Za-z-]+\\.bar\\.com}`)", urls: map[string]int{ "http://FOO.bar.com": http.StatusOK, "http://foo.bar.com": http.StatusOK, "http://fooubar.com": http.StatusNotFound, "http://barucom": http.StatusNotFound, "http://barcom": http.StatusNotFound, }, }, { desc: "insensitive host", hostExp: "HostRegexp(`{dummy:[a-z-]+\\.bar\\.com}`)", urls: map[string]int{ "http://FOO.bar.com": http.StatusOK, "http://foo.bar.com": http.StatusOK, "http://fooubar.com": http.StatusNotFound, "http://barucom": http.StatusNotFound, "http://barcom": http.StatusNotFound, }, }, { desc: "insensitive host simple", hostExp: "HostRegexp(`foo.bar.com`)", urls: map[string]int{ "http://FOO.bar.com": http.StatusOK, "http://foo.bar.com": http.StatusOK, "http://fooubar.com": http.StatusNotFound, "http://barucom": http.StatusNotFound, "http://barcom": http.StatusNotFound, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}) parser, err := NewSyntaxParser() require.NoError(t, err) muxer := NewMuxer(parser) err = muxer.AddRoute(test.hostExp, "v2", 0, handler) require.NoError(t, err) results := make(map[string]int) for calledURL := range test.urls { w := httptest.NewRecorder() req := httptest.NewRequest(http.MethodGet, calledURL, http.NoBody) muxer.ServeHTTP(w, req) results[calledURL] = w.Code } assert.Equal(t, test.urls, results) }) } } // This test is a copy from the v2 branch mux_test.go file. func Test_addRoute(t *testing.T) { testCases := []struct { desc string rule string headers map[string]string remoteAddr string expected map[string]int expectedError bool }{ { desc: "no tree", expectedError: true, }, { desc: "Rule with no matcher", rule: "rulewithnotmatcher", expectedError: true, }, { desc: "Host empty", rule: "Host(``)", expectedError: true, }, { desc: "PathPrefix empty", rule: "PathPrefix(``)", expectedError: true, }, { desc: "PathPrefix", rule: "PathPrefix(`/foo`)", expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "wrong PathPrefix", rule: "PathPrefix(`/bar`)", expected: map[string]int{ "http://localhost/foo": http.StatusNotFound, }, }, { desc: "Host", rule: "Host(`localhost`)", expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "Host IPv4", rule: "Host(`127.0.0.1`)", expected: map[string]int{ "http://127.0.0.1/foo": http.StatusOK, }, }, { desc: "Host IPv6", rule: "Host(`10::10`)", expected: map[string]int{ "http://10::10/foo": http.StatusOK, }, }, { desc: "Non-ASCII Host", rule: "Host(`locàlhost`)", expectedError: true, }, { desc: "Non-ASCII HostRegexp", rule: "HostRegexp(`locàlhost`)", expectedError: true, }, { desc: "HostHeader equivalent to Host", rule: "HostHeader(`localhost`)", expected: map[string]int{ "http://localhost/foo": http.StatusOK, "http://bar/foo": http.StatusNotFound, }, }, { desc: "Host with trailing period in rule", rule: "Host(`localhost.`)", expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "Host with trailing period in domain", rule: "Host(`localhost`)", expected: map[string]int{ "http://localhost./foo": http.StatusOK, }, }, { desc: "Host with trailing period in domain and rule", rule: "Host(`localhost.`)", expected: map[string]int{ "http://localhost./foo": http.StatusOK, }, }, { desc: "wrong Host", rule: "Host(`nope`)", expected: map[string]int{ "http://localhost/foo": http.StatusNotFound, }, }, { desc: "Host and PathPrefix", rule: "Host(`localhost`) && PathPrefix(`/foo`)", expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "Host and PathPrefix wrong PathPrefix", rule: "Host(`localhost`) && PathPrefix(`/bar`)", expected: map[string]int{ "http://localhost/foo": http.StatusNotFound, }, }, { desc: "Host and PathPrefix wrong Host", rule: "Host(`nope`) && PathPrefix(`/foo`)", expected: map[string]int{ "http://localhost/foo": http.StatusNotFound, }, }, { desc: "Host and PathPrefix Host OR, first host", rule: "Host(`nope`,`localhost`) && PathPrefix(`/foo`)", expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "Host and PathPrefix Host OR, second host", rule: "Host(`nope`,`localhost`) && PathPrefix(`/foo`)", expected: map[string]int{ "http://nope/foo": http.StatusOK, }, }, { desc: "Host and PathPrefix Host OR, first host and wrong PathPrefix", rule: "Host(`nope,localhost`) && PathPrefix(`/bar`)", expected: map[string]int{ "http://localhost/foo": http.StatusNotFound, }, }, { desc: "HostRegexp with capturing group", rule: "HostRegexp(`{subdomain:(foo\\.)?bar\\.com}`)", expected: map[string]int{ "http://foo.bar.com": http.StatusOK, "http://bar.com": http.StatusOK, "http://fooubar.com": http.StatusNotFound, "http://barucom": http.StatusNotFound, "http://barcom": http.StatusNotFound, }, }, { desc: "HostRegexp with non capturing group", rule: "HostRegexp(`{subdomain:(?:foo\\.)?bar\\.com}`)", expected: map[string]int{ "http://foo.bar.com": http.StatusOK, "http://bar.com": http.StatusOK, "http://fooubar.com": http.StatusNotFound, "http://barucom": http.StatusNotFound, "http://barcom": http.StatusNotFound, }, }, { desc: "Methods with GET", rule: "Method(`GET`)", expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "Methods with GET and POST", rule: "Method(`GET`,`POST`)", expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "Methods with POST", rule: "Method(`POST`)", expected: map[string]int{ // On v2 this test expect a http.StatusMethodNotAllowed status code. // This was due to a custom behavior of mux https://github.com/containous/mux/blob/b2dd784e613f218225150a5e8b5742c5733bc1b6/mux.go#L130-L132. // Unfortunately, this behavior cannot be ported easily due to the matcher func signature. "http://localhost/foo": http.StatusNotFound, }, }, { desc: "Header with matching header", rule: "Headers(`Content-Type`,`application/json`)", headers: map[string]string{ "Content-Type": "application/json", }, expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "Header without matching header", rule: "Headers(`Content-Type`,`application/foo`)", headers: map[string]string{ "Content-Type": "application/json", }, expected: map[string]int{ "http://localhost/foo": http.StatusNotFound, }, }, { desc: "HeaderRegExp with matching header", rule: "HeadersRegexp(`Content-Type`, `application/(text|json)`)", headers: map[string]string{ "Content-Type": "application/json", }, expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "HeaderRegExp without matching header", rule: "HeadersRegexp(`Content-Type`, `application/(text|json)`)", headers: map[string]string{ "Content-Type": "application/foo", }, expected: map[string]int{ "http://localhost/foo": http.StatusNotFound, }, }, { desc: "HeaderRegExp with matching second header", rule: "HeadersRegexp(`Content-Type`, `application/(text|json)`)", headers: map[string]string{ "Content-Type": "application/text", }, expected: map[string]int{ "http://localhost/foo": http.StatusOK, }, }, { desc: "Query with multiple params", rule: "Query(`foo=bar`, `bar=baz`)", expected: map[string]int{ "http://localhost/foo?foo=bar&bar=baz": http.StatusOK,
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
true
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/muxer/http/mux.go
pkg/muxer/http/mux.go
package http import ( "context" "errors" "fmt" "net/http" "net/url" "sort" "strings" "github.com/gorilla/mux" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/rules" ) type matcherBuilderFuncs map[string]matcherBuilderFunc type matcherBuilderFunc func(*matchersTree, ...string) error type MatcherFunc func(*http.Request) bool // Muxer handles routing with rules. type Muxer struct { routes routes parser SyntaxParser defaultHandler http.Handler } // NewMuxer returns a new muxer instance. func NewMuxer(parser SyntaxParser) *Muxer { return &Muxer{ parser: parser, defaultHandler: http.NotFoundHandler(), } } // ServeHTTP forwards the connection to the matching HTTP handler. // Serves 404 if no handler is found. func (m *Muxer) ServeHTTP(rw http.ResponseWriter, req *http.Request) { logger := log.Ctx(req.Context()) var err error req, err = withRoutingPath(req) if err != nil { logger.Debug().Err(err).Msg("Unable to add routing path to request context") rw.WriteHeader(http.StatusBadRequest) return } for _, route := range m.routes { if route.matchers.match(req) { route.handler.ServeHTTP(rw, req) return } } m.defaultHandler.ServeHTTP(rw, req) } // SetDefaultHandler sets the muxer default handler. func (m *Muxer) SetDefaultHandler(handler http.Handler) { m.defaultHandler = handler } // GetRulePriority computes the priority for a given rule. // The priority is calculated using the length of rule. func GetRulePriority(rule string) int { return len(rule) } // AddRoute add a new route to the router. func (m *Muxer) AddRoute(rule string, syntax string, priority int, handler http.Handler) error { matchers, err := m.parser.parse(syntax, rule) if err != nil { return fmt.Errorf("error while parsing rule %s: %w", rule, err) } m.routes = append(m.routes, &route{ handler: handler, matchers: matchers, priority: priority, }) sort.Sort(m.routes) return nil } // reservedCharacters contains the mapping of the percent-encoded form to the ASCII form // of the reserved characters according to https://datatracker.ietf.org/doc/html/rfc3986#section-2.2. // By extension to https://datatracker.ietf.org/doc/html/rfc3986#section-2.1 the percent character is also considered a reserved character. // Because decoding the percent character would change the meaning of the URL. var reservedCharacters = map[string]rune{ "%3A": ':', "%2F": '/', "%3F": '?', "%23": '#', "%5B": '[', "%5D": ']', "%40": '@', "%21": '!', "%24": '$', "%26": '&', "%27": '\'', "%28": '(', "%29": ')', "%2A": '*', "%2B": '+', "%2C": ',', "%3B": ';', "%3D": '=', "%25": '%', } // getRoutingPath retrieves the routing path from the request context. // It returns nil if the routing path is not set in the context. func getRoutingPath(req *http.Request) *string { routingPath := req.Context().Value(mux.RoutingPathKey) if routingPath != nil { rp := routingPath.(string) return &rp } return nil } // withRoutingPath decodes non-allowed characters in the EscapedPath and stores it in the request context to be able to use it for routing. // This allows using the decoded version of the non-allowed characters in the routing rules for a better UX. // For example, the rule PathPrefix(`/foo bar`) will match the following request path `/foo%20bar`. func withRoutingPath(req *http.Request) (*http.Request, error) { escapedPath := req.URL.EscapedPath() var routingPathBuilder strings.Builder for i := 0; i < len(escapedPath); i++ { if escapedPath[i] != '%' { routingPathBuilder.WriteString(string(escapedPath[i])) continue } // This should never happen as the standard library will reject requests containing invalid percent-encodings. // This discards URLs with a percent character at the end. if i+2 >= len(escapedPath) { return nil, errors.New("invalid percent-encoding at the end of the URL path") } encodedCharacter := escapedPath[i : i+3] if _, reserved := reservedCharacters[encodedCharacter]; reserved { routingPathBuilder.WriteString(encodedCharacter) } else { // This should never happen as the standard library will reject requests containing invalid percent-encodings. decodedCharacter, err := url.PathUnescape(encodedCharacter) if err != nil { return nil, errors.New("invalid percent-encoding in URL path") } routingPathBuilder.WriteString(decodedCharacter) } i += 2 } return req.WithContext( context.WithValue( req.Context(), mux.RoutingPathKey, routingPathBuilder.String(), ), ), nil } // ParseDomains extract domains from rule. func ParseDomains(rule string) ([]string, error) { var matchers []string for matcher := range httpFuncs { matchers = append(matchers, matcher) } for matcher := range httpFuncsV2 { matchers = append(matchers, matcher) } parser, err := rules.NewParser(matchers) if err != nil { return nil, fmt.Errorf("error while creating parser: %w", err) } parse, err := parser.Parse(rule) if err != nil { return nil, fmt.Errorf("error while parsing rule %s: %w", rule, err) } buildTree, ok := parse.(rules.TreeBuilder) if !ok { return nil, fmt.Errorf("error while parsing rule %s", rule) } return buildTree().ParseMatchers([]string{"Host"}), nil } // routes implements sort.Interface. type routes []*route // Len implements sort.Interface. func (r routes) Len() int { return len(r) } // Swap implements sort.Interface. func (r routes) Swap(i, j int) { r[i], r[j] = r[j], r[i] } // Less implements sort.Interface. func (r routes) Less(i, j int) bool { return r[i].priority > r[j].priority } // route holds the matchers to match HTTP route, // and the handler that will serve the request. type route struct { // matchers tree structure reflecting the rule. matchers matchersTree // handler responsible for handling the route. handler http.Handler // priority is used to disambiguate between two (or more) rules that would all match for a given request. // Computed from the matching rule length, if not user-set. priority int } // matchersTree represents the matchers tree structure. type matchersTree struct { // matcher is a matcher func used to match HTTP request properties. // If matcher is not nil, it means that this matcherTree is a leaf of the tree. // It is therefore mutually exclusive with left and right. matcher MatcherFunc // operator to combine the evaluation of left and right leaves. operator string // Mutually exclusive with matcher. left *matchersTree right *matchersTree } func (m *matchersTree) match(req *http.Request) bool { if m == nil { // This should never happen as it should have been detected during parsing. log.Warn().Msg("Rule matcher is nil") return false } if m.matcher != nil { return m.matcher(req) } switch m.operator { case "or": return m.left.match(req) || m.right.match(req) case "and": return m.left.match(req) && m.right.match(req) default: // This should never happen as it should have been detected during parsing. log.Warn().Str("operator", m.operator).Msg("Invalid rule operator") return false } } func (m *matchersTree) addRule(rule *rules.Tree, funcs matcherBuilderFuncs) error { switch rule.Matcher { case "and", "or": m.operator = rule.Matcher m.left = &matchersTree{} err := m.left.addRule(rule.RuleLeft, funcs) if err != nil { return fmt.Errorf("error while adding rule %s: %w", rule.Matcher, err) } m.right = &matchersTree{} return m.right.addRule(rule.RuleRight, funcs) default: err := rules.CheckRule(rule) if err != nil { return fmt.Errorf("error while checking rule %s: %w", rule.Matcher, err) } err = funcs[rule.Matcher](m, rule.Value...) if err != nil { return fmt.Errorf("error while adding rule %s: %w", rule.Matcher, err) } if rule.Not { matcherFunc := m.matcher m.matcher = func(req *http.Request) bool { return !matcherFunc(req) } } } return nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/ocsp.go
pkg/tls/ocsp.go
package tls import ( "bytes" "context" "crypto/x509" "errors" "fmt" "io" "net/http" "time" "github.com/patrickmn/go-cache" "github.com/rs/zerolog/log" "golang.org/x/crypto/ocsp" ) const defaultCacheDuration = 24 * time.Hour type ocspEntry struct { leaf *x509.Certificate issuer *x509.Certificate responders []string nextUpdate time.Time staple []byte } // ocspStapler retrieves staples from OCSP responders and store them in an in-memory cache. // It also updates the staples on a regular basis and before they expire. type ocspStapler struct { client *http.Client cache cache.Cache forceStapleUpdates chan struct{} responderOverrides map[string]string } // newOCSPStapler creates a new ocspStapler cache. func newOCSPStapler(responderOverrides map[string]string) *ocspStapler { return &ocspStapler{ client: &http.Client{Timeout: 10 * time.Second}, cache: *cache.New(defaultCacheDuration, 5*time.Minute), forceStapleUpdates: make(chan struct{}, 1), responderOverrides: responderOverrides, } } // Run updates the OCSP staples every hours. func (o *ocspStapler) Run(ctx context.Context) { ticker := time.NewTicker(time.Hour) defer ticker.Stop() for { select { case <-ctx.Done(): return case <-o.forceStapleUpdates: o.updateStaples(ctx) case <-ticker.C: o.updateStaples(ctx) } } } // ForceStapleUpdates triggers staple updates in the background instead of waiting for the Run routine to update them. func (o *ocspStapler) ForceStapleUpdates() { select { case o.forceStapleUpdates <- struct{}{}: default: } } // GetStaple retrieves the OCSP staple for the corresponding to the given key (public certificate hash). func (o *ocspStapler) GetStaple(key string) ([]byte, bool) { if item, ok := o.cache.Get(key); ok && item != nil { if entry, ok := item.(*ocspEntry); ok { return entry.staple, true } } return nil, false } // Upsert creates a new entry for the given certificate. // The ocspStapler will then be responsible from retrieving and updating the corresponding OCSP obtainStaple. func (o *ocspStapler) Upsert(key string, leaf, issuer *x509.Certificate) error { if len(leaf.OCSPServer) == 0 { return errors.New("leaf certificate does not contain an OCSP server") } if item, ok := o.cache.Get(key); ok { o.cache.Set(key, item, cache.NoExpiration) return nil } var responders []string for _, url := range leaf.OCSPServer { if len(o.responderOverrides) > 0 { if newURL, ok := o.responderOverrides[url]; ok { url = newURL } } responders = append(responders, url) } o.cache.Set(key, &ocspEntry{ leaf: leaf, issuer: issuer, responders: responders, }, cache.NoExpiration) return nil } // ResetTTL resets the expiration time for all items having no expiration. // This allows setting a TTL for certificates that do not exist anymore in the dynamic configuration. // For certificates that are still provided by the dynamic configuration, // their expiration time will be unset when calling the Upsert method. func (o *ocspStapler) ResetTTL() { for key, item := range o.cache.Items() { if item.Expiration > 0 { continue } o.cache.Set(key, item.Object, defaultCacheDuration) } } func (o *ocspStapler) updateStaples(ctx context.Context) { for _, item := range o.cache.Items() { select { case <-ctx.Done(): return default: } entry := item.Object.(*ocspEntry) if entry.staple != nil && time.Now().Before(entry.nextUpdate) { continue } if err := o.updateStaple(ctx, entry); err != nil { log.Error().Err(err).Msgf("Unable to retieve OCSP staple for: %s", entry.leaf.Subject.CommonName) continue } } } // obtainStaple obtains the OCSP stable for the given leaf certificate. func (o *ocspStapler) updateStaple(ctx context.Context, entry *ocspEntry) error { ocspReq, err := ocsp.CreateRequest(entry.leaf, entry.issuer, nil) if err != nil { return fmt.Errorf("creating OCSP request: %w", err) } for _, responder := range entry.responders { logger := log.With().Str("responder", responder).Logger() req, err := http.NewRequestWithContext(ctx, http.MethodPost, responder, bytes.NewReader(ocspReq)) if err != nil { return fmt.Errorf("creating OCSP request: %w", err) } req.Header.Set("Content-Type", "application/ocsp-request") res, err := o.client.Do(req) if err != nil && ctx.Err() != nil { return ctx.Err() } if err != nil { logger.Debug().Err(err).Msg("Unable to obtain OCSP response") continue } defer res.Body.Close() if res.StatusCode/100 != 2 { logger.Debug().Msgf("Unable to obtain OCSP response due to status code: %d", res.StatusCode) continue } ocspResBytes, err := io.ReadAll(res.Body) if err != nil { logger.Debug().Err(err).Msg("Unable to read OCSP response bytes") continue } ocspRes, err := ocsp.ParseResponseForCert(ocspResBytes, entry.leaf, entry.issuer) if err != nil { logger.Debug().Err(err).Msg("Unable to parse OCSP response") continue } entry.staple = ocspResBytes // As per RFC 6960, the nextUpdate field is optional. if ocspRes.NextUpdate.IsZero() { // NextUpdate is not set, the staple should be updated on the next update. entry.nextUpdate = time.Now() } else { entry.nextUpdate = ocspRes.ThisUpdate.Add(ocspRes.NextUpdate.Sub(ocspRes.ThisUpdate) / 2) } return nil } return errors.New("no OCSP staple obtained from any responders") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/cipher.go
pkg/tls/cipher.go
package tls import ( "crypto/tls" ) var ( // CipherSuites Map of TLS CipherSuites from crypto/tls // Available CipherSuites defined at https://pkg.go.dev/crypto/tls/#pkg-constants CipherSuites = map[string]uint16{ `TLS_RSA_WITH_RC4_128_SHA`: tls.TLS_RSA_WITH_RC4_128_SHA, `TLS_RSA_WITH_3DES_EDE_CBC_SHA`: tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA, `TLS_RSA_WITH_AES_128_CBC_SHA`: tls.TLS_RSA_WITH_AES_128_CBC_SHA, `TLS_RSA_WITH_AES_256_CBC_SHA`: tls.TLS_RSA_WITH_AES_256_CBC_SHA, `TLS_RSA_WITH_AES_128_CBC_SHA256`: tls.TLS_RSA_WITH_AES_128_CBC_SHA256, `TLS_RSA_WITH_AES_128_GCM_SHA256`: tls.TLS_RSA_WITH_AES_128_GCM_SHA256, `TLS_RSA_WITH_AES_256_GCM_SHA384`: tls.TLS_RSA_WITH_AES_256_GCM_SHA384, `TLS_ECDHE_ECDSA_WITH_RC4_128_SHA`: tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA`: tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA`: tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, `TLS_ECDHE_RSA_WITH_RC4_128_SHA`: tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA, `TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA`: tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA`: tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA`: tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256`: tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256, `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256`: tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`: tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`: tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`: tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`: tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, `TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305`: tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305, `TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256`: tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305`: tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305, `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256`: tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, `TLS_AES_128_GCM_SHA256`: tls.TLS_AES_128_GCM_SHA256, `TLS_AES_256_GCM_SHA384`: tls.TLS_AES_256_GCM_SHA384, `TLS_CHACHA20_POLY1305_SHA256`: tls.TLS_CHACHA20_POLY1305_SHA256, `TLS_FALLBACK_SCSV`: tls.TLS_FALLBACK_SCSV, } // CipherSuitesReversed Map of TLS CipherSuites from crypto/tls // Available CipherSuites defined at https://pkg.go.dev/crypto/tls/#pkg-constants CipherSuitesReversed = map[uint16]string{ tls.TLS_RSA_WITH_RC4_128_SHA: `TLS_RSA_WITH_RC4_128_SHA`, tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA: `TLS_RSA_WITH_3DES_EDE_CBC_SHA`, tls.TLS_RSA_WITH_AES_128_CBC_SHA: `TLS_RSA_WITH_AES_128_CBC_SHA`, tls.TLS_RSA_WITH_AES_256_CBC_SHA: `TLS_RSA_WITH_AES_256_CBC_SHA`, tls.TLS_RSA_WITH_AES_128_CBC_SHA256: `TLS_RSA_WITH_AES_128_CBC_SHA256`, tls.TLS_RSA_WITH_AES_128_GCM_SHA256: `TLS_RSA_WITH_AES_128_GCM_SHA256`, tls.TLS_RSA_WITH_AES_256_GCM_SHA384: `TLS_RSA_WITH_AES_256_GCM_SHA384`, tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA: `TLS_ECDHE_ECDSA_WITH_RC4_128_SHA`, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA: `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA`, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA: `TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA`, tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA: `TLS_ECDHE_RSA_WITH_RC4_128_SHA`, tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA: `TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA`, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA: `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA`, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA: `TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA`, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256: `TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256`, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256: `TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256`, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256: `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256: `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384: `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`, tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384: `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256: `TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256`, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256: `TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256`, tls.TLS_AES_128_GCM_SHA256: `TLS_AES_128_GCM_SHA256`, tls.TLS_AES_256_GCM_SHA384: `TLS_AES_256_GCM_SHA384`, tls.TLS_CHACHA20_POLY1305_SHA256: `TLS_CHACHA20_POLY1305_SHA256`, tls.TLS_FALLBACK_SCSV: `TLS_FALLBACK_SCSV`, } ) // GetCipherName returns the Cipher suite name. // Available CipherSuites defined at https://pkg.go.dev/crypto/tls/#pkg-constants func GetCipherName(connState *tls.ConnectionState) string { if cipher, ok := CipherSuitesReversed[connState.CipherSuite]; ok { return cipher } return "unknown" }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/zz_generated.deepcopy.go
pkg/tls/zz_generated.deepcopy.go
//go:build !ignore_autogenerated // +build !ignore_autogenerated /* The MIT License (MIT) Copyright (c) 2016-2020 Containous SAS; 2020-2026 Traefik Labs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // Code generated by deepcopy-gen. DO NOT EDIT. package tls import ( types "github.com/traefik/traefik/v3/pkg/types" ) // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *CertAndStores) DeepCopyInto(out *CertAndStores) { *out = *in out.Certificate = in.Certificate if in.Stores != nil { in, out := &in.Stores, &out.Stores *out = make([]string, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new CertAndStores. func (in *CertAndStores) DeepCopy() *CertAndStores { if in == nil { return nil } out := new(CertAndStores) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *ClientAuth) DeepCopyInto(out *ClientAuth) { *out = *in if in.CAFiles != nil { in, out := &in.CAFiles, &out.CAFiles *out = make([]types.FileOrContent, len(*in)) copy(*out, *in) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new ClientAuth. func (in *ClientAuth) DeepCopy() *ClientAuth { if in == nil { return nil } out := new(ClientAuth) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *GeneratedCert) DeepCopyInto(out *GeneratedCert) { *out = *in if in.Domain != nil { in, out := &in.Domain, &out.Domain *out = new(types.Domain) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new GeneratedCert. func (in *GeneratedCert) DeepCopy() *GeneratedCert { if in == nil { return nil } out := new(GeneratedCert) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Options) DeepCopyInto(out *Options) { *out = *in if in.CipherSuites != nil { in, out := &in.CipherSuites, &out.CipherSuites *out = make([]string, len(*in)) copy(*out, *in) } if in.CurvePreferences != nil { in, out := &in.CurvePreferences, &out.CurvePreferences *out = make([]string, len(*in)) copy(*out, *in) } in.ClientAuth.DeepCopyInto(&out.ClientAuth) if in.ALPNProtocols != nil { in, out := &in.ALPNProtocols, &out.ALPNProtocols *out = make([]string, len(*in)) copy(*out, *in) } if in.PreferServerCipherSuites != nil { in, out := &in.PreferServerCipherSuites, &out.PreferServerCipherSuites *out = new(bool) **out = **in } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Options. func (in *Options) DeepCopy() *Options { if in == nil { return nil } out := new(Options) in.DeepCopyInto(out) return out } // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil. func (in *Store) DeepCopyInto(out *Store) { *out = *in if in.DefaultCertificate != nil { in, out := &in.DefaultCertificate, &out.DefaultCertificate *out = new(Certificate) **out = **in } if in.DefaultGeneratedCert != nil { in, out := &in.DefaultGeneratedCert, &out.DefaultGeneratedCert *out = new(GeneratedCert) (*in).DeepCopyInto(*out) } return } // DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Store. func (in *Store) DeepCopy() *Store { if in == nil { return nil } out := new(Store) in.DeepCopyInto(out) return out }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/tlsmanager.go
pkg/tls/tlsmanager.go
package tls import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "hash/fnv" "slices" "strconv" "strings" "sync" "github.com/go-acme/lego/v4/challenge/dns01" "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/logs" "github.com/traefik/traefik/v3/pkg/tls/generate" "github.com/traefik/traefik/v3/pkg/types" ) const ( // DefaultTLSConfigName is the name of the default set of options for configuring TLS. DefaultTLSConfigName = "default" // DefaultTLSStoreName is the name of the default store of TLS certificates. // Note that it actually is the only usable one for now. DefaultTLSStoreName = "default" ) // DefaultTLSOptions the default TLS options. var DefaultTLSOptions = Options{ // ensure http2 enabled ALPNProtocols: []string{"h2", "http/1.1", tlsalpn01.ACMETLS1Protocol}, MinVersion: "VersionTLS12", CipherSuites: getCipherSuites(), } func getCipherSuites() []string { gsc := tls.CipherSuites() ciphers := make([]string, len(gsc)) for idx, cs := range gsc { ciphers[idx] = cs.Name } return ciphers } // OCSPConfig contains the OCSP configuration. type OCSPConfig struct { ResponderOverrides map[string]string `description:"Defines a map of OCSP responders to replace for querying OCSP servers." json:"responderOverrides,omitempty" toml:"responderOverrides,omitempty" yaml:"responderOverrides,omitempty"` } // Manager is the TLS option/store/configuration factory. type Manager struct { lock sync.RWMutex storesConfig map[string]Store stores map[string]*CertificateStore configs map[string]Options certs []*CertAndStores // As of today, the TLS manager contains and is responsible for creating/starting the OCSP ocspStapler. // It would likely have been a Configuration listener but this implies that certs are re-parsed. // But this would probably have impact on resource consumption. ocspStapler *ocspStapler } // NewManager creates a new Manager. func NewManager(ocspConfig *OCSPConfig) *Manager { manager := &Manager{ stores: map[string]*CertificateStore{}, configs: map[string]Options{ "default": DefaultTLSOptions, }, } if ocspConfig != nil { manager.ocspStapler = newOCSPStapler(ocspConfig.ResponderOverrides) } return manager } func (m *Manager) Run(ctx context.Context) { if m.ocspStapler != nil { m.ocspStapler.Run(ctx) } } // UpdateConfigs updates the TLS* configuration options. // It initializes the default TLS store, and the TLS store for the ACME challenges. func (m *Manager) UpdateConfigs(ctx context.Context, stores map[string]Store, configs map[string]Options, certs []*CertAndStores) { m.lock.Lock() defer m.lock.Unlock() m.configs = configs for optionName, option := range m.configs { // Handle `PreferServerCipherSuites` depreciation if option.PreferServerCipherSuites != nil { log.Ctx(ctx).Warn().Msgf("TLSOption %q uses `PreferServerCipherSuites` option, but this option is deprecated and ineffective, please remove this option.", optionName) } } m.storesConfig = stores m.certs = certs if m.storesConfig == nil { m.storesConfig = make(map[string]Store) } if _, ok := m.storesConfig[DefaultTLSStoreName]; !ok { m.storesConfig[DefaultTLSStoreName] = Store{} } if _, ok := m.storesConfig[tlsalpn01.ACMETLS1Protocol]; !ok { m.storesConfig[tlsalpn01.ACMETLS1Protocol] = Store{} } storesCertificates := make(map[string]map[string]*CertificateData) // Define the TTL for all the cache entries with no TTL. // This will discard entries that are not used anymore. if m.ocspStapler != nil { m.ocspStapler.ResetTTL() } for _, conf := range certs { if len(conf.Stores) == 0 { log.Ctx(ctx).Debug().MsgFunc(func() string { return fmt.Sprintf("No store is defined to add the certificate %s, it will be added to the default store", conf.Certificate.GetTruncatedCertificateName()) }) conf.Stores = []string{DefaultTLSStoreName} } cert, SANs, err := parseCertificate(&conf.Certificate) if err != nil { log.Ctx(ctx).Error().Err(err).Msgf("Unable to parse certificate %s", conf.Certificate.GetTruncatedCertificateName()) continue } var certHash string if m.ocspStapler != nil && len(cert.Leaf.OCSPServer) > 0 { certHash = hashRawCert(cert.Leaf.Raw) issuer := cert.Leaf if len(cert.Certificate) > 1 { issuer, err = x509.ParseCertificate(cert.Certificate[1]) if err != nil { log.Ctx(ctx).Error().Err(err).Msgf("Unable to parse issuer certificate %s", conf.Certificate.GetTruncatedCertificateName()) continue } } if err := m.ocspStapler.Upsert(certHash, cert.Leaf, issuer); err != nil { log.Ctx(ctx).Error().Err(err).Msgf("Unable to upsert OCSP certificate %s", conf.Certificate.GetTruncatedCertificateName()) continue } } certData := &CertificateData{ Certificate: &cert, Hash: certHash, } for _, store := range conf.Stores { if _, ok := m.storesConfig[store]; !ok { m.storesConfig[store] = Store{} } appendCertificate(storesCertificates, SANs, store, certData) } } m.stores = make(map[string]*CertificateStore) for storeName, storeConfig := range m.storesConfig { st := NewCertificateStore(m.ocspStapler) m.stores[storeName] = st if certs, ok := storesCertificates[storeName]; ok { st.DynamicCerts.Set(certs) } // a default cert for the ACME store does not make any sense, so generating one is a waste. if storeName == tlsalpn01.ACMETLS1Protocol { continue } logger := log.Ctx(ctx).With().Str(logs.TLSStoreName, storeName).Logger() ctxStore := logger.WithContext(ctx) certificate, err := m.getDefaultCertificate(ctxStore, storeConfig, st) if err != nil { logger.Error().Err(err).Msg("Error while creating certificate store") } st.DefaultCertificate = certificate } if m.ocspStapler != nil { m.ocspStapler.ForceStapleUpdates() } } // sanitizeDomains sanitizes the domain definition Main and SANS, // and returns them as a slice. // This func apply the same sanitization as the ACME provider do before resolving certificates. func sanitizeDomains(domain types.Domain) ([]string, error) { domains := domain.ToStrArray() if len(domains) == 0 { return nil, errors.New("no domain was given") } var cleanDomains []string for _, domain := range domains { canonicalDomain := types.CanonicalDomain(domain) cleanDomain := dns01.UnFqdn(canonicalDomain) cleanDomains = append(cleanDomains, cleanDomain) } return cleanDomains, nil } // Get gets the TLS configuration to use for a given store / configuration. func (m *Manager) Get(storeName, configName string) (*tls.Config, error) { m.lock.RLock() defer m.lock.RUnlock() sniStrict := false config, ok := m.configs[configName] if !ok { return nil, fmt.Errorf("unknown TLS options: %s", configName) } sniStrict = config.SniStrict tlsConfig, err := buildTLSConfig(config) if err != nil { return nil, fmt.Errorf("building TLS config: %w", err) } store := m.getStore(storeName) if store == nil { err = fmt.Errorf("TLS store %s not found", storeName) } acmeTLSStore := m.getStore(tlsalpn01.ACMETLS1Protocol) if acmeTLSStore == nil && err == nil { err = fmt.Errorf("ACME TLS store %s not found", tlsalpn01.ACMETLS1Protocol) } tlsConfig.GetCertificate = func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { domainToCheck := types.CanonicalDomain(clientHello.ServerName) if slices.Contains(clientHello.SupportedProtos, tlsalpn01.ACMETLS1Protocol) { certificate := acmeTLSStore.GetBestCertificate(clientHello) if certificate == nil { log.Debug().Msgf("TLS: no certificate for TLSALPN challenge: %s", domainToCheck) // We want the user to eventually get the (alertUnrecognizedName) "unrecognized name" error. // Unfortunately, if we returned an error here, // since we can't use the unexported error (errNoCertificates) that our caller (config.getCertificate in crypto/tls) uses as a sentinel, // it would report an (alertInternalError) "internal error" instead of an alertUnrecognizedName. // Which is why we return no error, and we let the caller detect that there's actually no certificate, // and fall back into the flow that will report the desired error. // https://cs.opensource.google/go/go/+/dev.boringcrypto.go1.17:src/crypto/tls/common.go;l=1058 return nil, nil } return certificate, nil } bestCertificate := store.GetBestCertificate(clientHello) if bestCertificate != nil { return bestCertificate, nil } if sniStrict { log.Debug().Msgf("TLS: strict SNI enabled - No certificate found for domain: %q, closing connection", domainToCheck) // Same comment as above, as in the isACMETLS case. return nil, nil } if store == nil { log.Error().Msgf("TLS: No certificate store found with this name: %q, closing connection", storeName) // Same comment as above, as in the isACMETLS case. return nil, nil } log.Debug().Msgf("Serving default certificate for request: %q", domainToCheck) return store.GetDefaultCertificate(), nil } return tlsConfig, err } // GetServerCertificates returns all certificates from the default store, // as well as the user-defined default certificate (if it exists). func (m *Manager) GetServerCertificates() []*x509.Certificate { var certificates []*x509.Certificate // The default store is the only relevant, because it is the only one configurable. defaultStore, ok := m.stores[DefaultTLSStoreName] if !ok || defaultStore == nil { return certificates } // We iterate over all the certificates. if defaultStore.DynamicCerts != nil && defaultStore.DynamicCerts.Get() != nil { for _, cert := range defaultStore.DynamicCerts.Get().(map[string]*CertificateData) { x509Cert, err := x509.ParseCertificate(cert.Certificate.Certificate[0]) if err != nil { continue } certificates = append(certificates, x509Cert) } } if defaultStore.DefaultCertificate != nil { x509Cert, err := x509.ParseCertificate(defaultStore.DefaultCertificate.Certificate.Certificate[0]) if err != nil { return certificates } // Excluding the generated Traefik default certificate. if x509Cert.Subject.CommonName == generate.DefaultDomain { return certificates } certificates = append(certificates, x509Cert) } return certificates } // getStore returns the store found for storeName, or nil otherwise. func (m *Manager) getStore(storeName string) *CertificateStore { st, ok := m.stores[storeName] if !ok { return nil } return st } // GetStore gets the certificate store of a given name. func (m *Manager) GetStore(storeName string) *CertificateStore { m.lock.RLock() defer m.lock.RUnlock() return m.getStore(storeName) } func (m *Manager) getDefaultCertificate(ctx context.Context, tlsStore Store, st *CertificateStore) (*CertificateData, error) { if tlsStore.DefaultCertificate != nil { cert, err := m.buildDefaultCertificate(tlsStore.DefaultCertificate) if err != nil { return nil, err } return cert, nil } defaultCert, err := generate.DefaultCertificate() if err != nil { return nil, err } defaultCertificate := &CertificateData{ Certificate: defaultCert, } if tlsStore.DefaultGeneratedCert != nil && tlsStore.DefaultGeneratedCert.Domain != nil && tlsStore.DefaultGeneratedCert.Resolver != "" { domains, err := sanitizeDomains(*tlsStore.DefaultGeneratedCert.Domain) if err != nil { return defaultCertificate, fmt.Errorf("falling back to the internal generated certificate because invalid domains: %w", err) } defaultACMECert := st.GetCertificate(domains) if defaultACMECert == nil { return defaultCertificate, fmt.Errorf("unable to find certificate for domains %q: falling back to the internal generated certificate", strings.Join(domains, ",")) } return defaultACMECert, nil } log.Ctx(ctx).Debug().Msg("No default certificate, fallback to the internal generated certificate") return defaultCertificate, nil } func (m *Manager) buildDefaultCertificate(defaultCertificate *Certificate) (*CertificateData, error) { certFile, err := defaultCertificate.CertFile.Read() if err != nil { return nil, fmt.Errorf("failed to get cert file content: %w", err) } keyFile, err := defaultCertificate.KeyFile.Read() if err != nil { return nil, fmt.Errorf("failed to get key file content: %w", err) } cert, err := tls.X509KeyPair(certFile, keyFile) if err != nil { return nil, fmt.Errorf("failed to load X509 key pair: %w", err) } var certHash string if m.ocspStapler != nil && len(cert.Leaf.OCSPServer) > 0 { certHash = hashRawCert(cert.Leaf.Raw) issuer := cert.Leaf if len(cert.Certificate) > 1 { issuer, err = x509.ParseCertificate(cert.Certificate[1]) if err != nil { return nil, fmt.Errorf("parsing issuer certificate %s: %w", defaultCertificate.GetTruncatedCertificateName(), err) } } if err := m.ocspStapler.Upsert(certHash, cert.Leaf, issuer); err != nil { return nil, fmt.Errorf("upserting OCSP certificate %s: %w", defaultCertificate.GetTruncatedCertificateName(), err) } } return &CertificateData{ Certificate: &cert, Hash: certHash, }, nil } // creates a TLS config that allows terminating HTTPS for multiple domains using SNI. func buildTLSConfig(tlsOption Options) (*tls.Config, error) { conf := &tls.Config{ NextProtos: tlsOption.ALPNProtocols, SessionTicketsDisabled: tlsOption.DisableSessionTickets, } if len(tlsOption.ClientAuth.CAFiles) > 0 { pool := x509.NewCertPool() for _, caFile := range tlsOption.ClientAuth.CAFiles { data, err := caFile.Read() if err != nil { return nil, err } ok := pool.AppendCertsFromPEM(data) if !ok { if caFile.IsPath() { return nil, fmt.Errorf("invalid certificate(s) in %s", caFile) } return nil, errors.New("invalid certificate(s) content") } } conf.ClientCAs = pool conf.ClientAuth = tls.RequireAndVerifyClientCert } clientAuthType := tlsOption.ClientAuth.ClientAuthType if len(clientAuthType) > 0 { if conf.ClientCAs == nil && (clientAuthType == "VerifyClientCertIfGiven" || clientAuthType == "RequireAndVerifyClientCert") { return nil, fmt.Errorf("invalid clientAuthType: %s, CAFiles is required", clientAuthType) } switch clientAuthType { case "NoClientCert": conf.ClientAuth = tls.NoClientCert case "RequestClientCert": conf.ClientAuth = tls.RequestClientCert case "RequireAnyClientCert": conf.ClientAuth = tls.RequireAnyClientCert case "VerifyClientCertIfGiven": conf.ClientAuth = tls.VerifyClientCertIfGiven case "RequireAndVerifyClientCert": conf.ClientAuth = tls.RequireAndVerifyClientCert default: return nil, fmt.Errorf("unknown client auth type %q", clientAuthType) } } // Set the minimum TLS version if set in the config if minConst, exists := MinVersion[tlsOption.MinVersion]; exists { conf.MinVersion = minConst } // Set the maximum TLS version if set in the config TOML if maxConst, exists := MaxVersion[tlsOption.MaxVersion]; exists { conf.MaxVersion = maxConst } // Set the list of CipherSuites if set in the config if tlsOption.CipherSuites != nil { // if our list of CipherSuites is defined in the entryPoint config, we can re-initialize the suites list as empty conf.CipherSuites = make([]uint16, 0) for _, cipher := range tlsOption.CipherSuites { if cipherConst, exists := CipherSuites[cipher]; exists { conf.CipherSuites = append(conf.CipherSuites, cipherConst) } else { // CipherSuite listed in the toml does not exist in our listed return nil, fmt.Errorf("invalid CipherSuite: %s", cipher) } } } // Set the list of CurvePreferences/CurveIDs if set in the config if tlsOption.CurvePreferences != nil { conf.CurvePreferences = make([]tls.CurveID, 0) // if our list of CurvePreferences/CurveIDs is defined in the config, we can re-initialize the list as empty for _, curve := range tlsOption.CurvePreferences { if curveID, exists := CurveIDs[curve]; exists { conf.CurvePreferences = append(conf.CurvePreferences, curveID) } else { // CurveID listed in the toml does not exist in our listed return nil, fmt.Errorf("invalid CurveID in curvePreferences: %s", curve) } } } return conf, nil } func hashRawCert(rawCert []byte) string { hasher := fnv.New64() // purposely ignoring the error, as no error can be returned from the implementation. _, _ = hasher.Write(rawCert) return strconv.FormatUint(hasher.Sum64(), 16) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/ocsp_test.go
pkg/tls/ocsp_test.go
package tls import ( "crypto" "crypto/tls" "io" "net/http" "net/http/httptest" "testing" "time" "github.com/patrickmn/go-cache" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "golang.org/x/crypto/ocsp" ) const certWithOCSPServer = `-----BEGIN CERTIFICATE----- MIIBgjCCASegAwIBAgICIAAwCgYIKoZIzj0EAwIwEjEQMA4GA1UEAxMHVGVzdCBD QTAeFw0yMzAxMDExMjAwMDBaFw0yMzAyMDExMjAwMDBaMCAxHjAcBgNVBAMTFU9D U1AgVGVzdCBDZXJ0aWZpY2F0ZTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABIoe I/bjo34qony8LdRJD+Jhuk8/S8YHXRHl6rH9t5VFCFtX8lIPN/Ll1zCrQ2KB3Wlb fxSgiQyLrCpZyrdhVPSjXzBdMAwGA1UdEwEB/wQCMAAwHwYDVR0jBBgwFoAU+Eo3 5sST4LRrwS4dueIdGBZ5d7IwLAYIKwYBBQUHAQEEIDAeMBwGCCsGAQUFBzABhhBv Y3NwLmV4YW1wbGUuY29tMAoGCCqGSM49BAMCA0kAMEYCIQDg94xY/+/VepESdvTT ykCwiWOS2aCpjyryrKpwMKkR0AIhAPc/+ZEz4W10OENxC1t+NUTvS8JbEGOwulkZ z9yfaLuD -----END CERTIFICATE-----` const certWithoutOCSPServer = `-----BEGIN CERTIFICATE----- MIIBUzCB+aADAgECAgIgADAKBggqhkjOPQQDAjASMRAwDgYDVQQDEwdUZXN0IENB MB4XDTIzMDEwMTEyMDAwMFoXDTIzMDIwMTEyMDAwMFowIDEeMBwGA1UEAxMVT0NT UCBUZXN0IENlcnRpZmljYXRlMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEih4j 9uOjfiqifLwt1EkP4mG6Tz9LxgddEeXqsf23lUUIW1fyUg838uXXMKtDYoHdaVt/ FKCJDIusKlnKt2FU9KMxMC8wDAYDVR0TAQH/BAIwADAfBgNVHSMEGDAWgBT4Sjfm xJPgtGvBLh254h0YFnl3sjAKBggqhkjOPQQDAgNJADBGAiEA3rWetLGblfSuNZKf 5CpZxhj3A0BjEocEh+2P+nAgIdUCIQDIgptabR1qTLQaF2u0hJsEX2IKuIUvYWH3 6Lb92+zIHg== -----END CERTIFICATE-----` // certKey is the private key for both certWithOCSPServer and certWithoutOCSPServer. const certKey = `-----BEGIN EC PRIVATE KEY----- MHcCAQEEINnVcgrSNh4HlThWlZpegq14M8G/p9NVDtdVjZrseUGLoAoGCCqGSM49 AwEHoUQDQgAEih4j9uOjfiqifLwt1EkP4mG6Tz9LxgddEeXqsf23lUUIW1fyUg83 8uXXMKtDYoHdaVt/FKCJDIusKlnKt2FU9A== -----END EC PRIVATE KEY-----` // caCert is the issuing certificate for certWithOCSPServer and certWithoutOCSPServer. const caCert = `-----BEGIN CERTIFICATE----- MIIBazCCARGgAwIBAgICEAAwCgYIKoZIzj0EAwIwEjEQMA4GA1UEAxMHVGVzdCBD QTAeFw0yMzAxMDExMjAwMDBaFw0yMzAyMDExMjAwMDBaMBIxEDAOBgNVBAMTB1Rl c3QgQ0EwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASdKexSor/aeazDM57UHhAX rCkJxUeF2BWf0lZYCRxc3f0GdrEsVvjJW8+/E06eAzDCGSdM/08Nvun1nb6AmAlt o1cwVTAOBgNVHQ8BAf8EBAMCAQYwEwYDVR0lBAwwCgYIKwYBBQUHAwkwDwYDVR0T AQH/BAUwAwEB/zAdBgNVHQ4EFgQU+Eo35sST4LRrwS4dueIdGBZ5d7IwCgYIKoZI zj0EAwIDSAAwRQIgGbA39+kETTB/YMLBFoC2fpZe1cDWfFB7TUdfINUqdH4CIQCR ByUFC8A+hRNkK5YNH78bgjnKk/88zUQF5ONy4oPGdQ== -----END CERTIFICATE-----` const caKey = `-----BEGIN EC PRIVATE KEY----- MHcCAQEEIDJ59ptjq3MzILH4zn5IKoH1sYn+zrUeq2kD8+DD2x+OoAoGCCqGSM49 AwEHoUQDQgAEnSnsUqK/2nmswzOe1B4QF6wpCcVHhdgVn9JWWAkcXN39BnaxLFb4 yVvPvxNOngMwwhknTP9PDb7p9Z2+gJgJbQ== -----END EC PRIVATE KEY-----` func TestOCSPStapler_Upsert(t *testing.T) { ocspStapler := newOCSPStapler(nil) issuerCert, err := tls.X509KeyPair([]byte(caCert), []byte(caKey)) require.NoError(t, err) leafCert, err := tls.X509KeyPair([]byte(certWithOCSPServer), []byte(certKey)) require.NoError(t, err) // Upsert a certificate without an OCSP server should raise an error. leafCertWithoutOCSPServer, err := tls.X509KeyPair([]byte(certWithoutOCSPServer), []byte(certKey)) require.NoError(t, err) err = ocspStapler.Upsert("foo", leafCertWithoutOCSPServer.Leaf, issuerCert.Leaf) require.Error(t, err) // Upsert a certificate with an OCSP server. err = ocspStapler.Upsert("foo", leafCert.Leaf, issuerCert.Leaf) require.NoError(t, err) i, ok := ocspStapler.cache.Get("foo") require.True(t, ok) e, ok := i.(*ocspEntry) require.True(t, ok) assert.Equal(t, leafCert.Leaf, e.leaf) assert.Equal(t, issuerCert.Leaf, e.issuer) assert.Nil(t, e.staple) assert.Equal(t, []string{"ocsp.example.com"}, e.responders) assert.Equal(t, int64(0), ocspStapler.cache.Items()["foo"].Expiration) // Upsert an existing entry to make sure that the existing staple is preserved. e.staple = []byte("foo") e.nextUpdate = time.Now() e.responders = []string{"foo.com"} err = ocspStapler.Upsert("foo", leafCert.Leaf, issuerCert.Leaf) require.NoError(t, err) i, ok = ocspStapler.cache.Get("foo") require.True(t, ok) e, ok = i.(*ocspEntry) require.True(t, ok) assert.Equal(t, leafCert.Leaf, e.leaf) assert.Equal(t, issuerCert.Leaf, e.issuer) assert.Equal(t, []byte("foo"), e.staple) assert.NotZero(t, e.nextUpdate) assert.Equal(t, []string{"foo.com"}, e.responders) assert.Equal(t, int64(0), ocspStapler.cache.Items()["foo"].Expiration) } func TestOCSPStapler_Upsert_withResponderOverrides(t *testing.T) { ocspStapler := newOCSPStapler(map[string]string{ "ocsp.example.com": "foo.com", }) issuerCert, err := tls.X509KeyPair([]byte(caCert), []byte(caKey)) require.NoError(t, err) leafCert, err := tls.X509KeyPair([]byte(certWithOCSPServer), []byte(certKey)) require.NoError(t, err) err = ocspStapler.Upsert("foo", leafCert.Leaf, issuerCert.Leaf) require.NoError(t, err) i, ok := ocspStapler.cache.Get("foo") require.True(t, ok) e, ok := i.(*ocspEntry) require.True(t, ok) assert.Equal(t, leafCert.Leaf, e.leaf) assert.Equal(t, issuerCert.Leaf, e.issuer) assert.Nil(t, e.staple) assert.Equal(t, []string{"foo.com"}, e.responders) } func TestOCSPStapler_ResetTTL(t *testing.T) { ocspStapler := newOCSPStapler(nil) issuerCert, err := tls.X509KeyPair([]byte(caCert), []byte(caKey)) require.NoError(t, err) leafCert, err := tls.X509KeyPair([]byte(certWithOCSPServer), []byte(certKey)) require.NoError(t, err) ocspStapler.cache.Set("foo", &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{"foo.com"}, nextUpdate: time.Now(), staple: []byte("foo"), }, cache.NoExpiration) ocspStapler.cache.Set("bar", &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{"bar.com"}, nextUpdate: time.Now(), staple: []byte("bar"), }, time.Hour) wantBarExpiration := ocspStapler.cache.Items()["bar"].Expiration ocspStapler.ResetTTL() item, ok := ocspStapler.cache.Items()["foo"] require.True(t, ok) e, ok := item.Object.(*ocspEntry) require.True(t, ok) assert.Positive(t, item.Expiration) assert.Equal(t, leafCert.Leaf, e.leaf) assert.Equal(t, issuerCert.Leaf, e.issuer) assert.Equal(t, []byte("foo"), e.staple) assert.NotZero(t, e.nextUpdate) assert.Equal(t, []string{"foo.com"}, e.responders) item, ok = ocspStapler.cache.Items()["bar"] require.True(t, ok) e, ok = item.Object.(*ocspEntry) require.True(t, ok) assert.Equal(t, wantBarExpiration, item.Expiration) assert.Equal(t, leafCert.Leaf, e.leaf) assert.Equal(t, issuerCert.Leaf, e.issuer) assert.Equal(t, []byte("bar"), e.staple) assert.NotZero(t, e.nextUpdate) assert.Equal(t, []string{"bar.com"}, e.responders) } func TestOCSPStapler_GetStaple(t *testing.T) { ocspStapler := newOCSPStapler(nil) // Get an un-existing staple. staple, exists := ocspStapler.GetStaple("foo") assert.False(t, exists) assert.Nil(t, staple) // Get an existing staple. ocspStapler.cache.Set("foo", &ocspEntry{staple: []byte("foo")}, cache.NoExpiration) staple, exists = ocspStapler.GetStaple("foo") assert.True(t, exists) assert.Equal(t, []byte("foo"), staple) } func TestOCSPStapler_updateStaple(t *testing.T) { leafCert, err := tls.X509KeyPair([]byte(certWithOCSPServer), []byte(certKey)) require.NoError(t, err) issuerCert, err := tls.X509KeyPair([]byte(caCert), []byte(caKey)) require.NoError(t, err) thisUpdate, err := time.Parse("2006-01-02", "2025-01-01") require.NoError(t, err) nextUpdate, err := time.Parse("2006-01-02", "2025-01-02") require.NoError(t, err) stapleUpdate := thisUpdate.Add(nextUpdate.Sub(thisUpdate) / 2) ocspResponseTmpl := ocsp.Response{ SerialNumber: leafCert.Leaf.SerialNumber, TBSResponseData: []byte("foo"), ThisUpdate: thisUpdate, NextUpdate: nextUpdate, } ocspResponse, err := ocsp.CreateResponse(leafCert.Leaf, leafCert.Leaf, ocspResponseTmpl, issuerCert.PrivateKey.(crypto.Signer)) require.NoError(t, err) handler := func(rw http.ResponseWriter, req *http.Request) { ct := req.Header.Get("Content-Type") assert.Equal(t, "application/ocsp-request", ct) reqBytes, err := io.ReadAll(req.Body) require.NoError(t, err) _, err = ocsp.ParseRequest(reqBytes) require.NoError(t, err) rw.Header().Set("Content-Type", "application/ocsp-response") _, err = rw.Write(ocspResponse) require.NoError(t, err) } responder := httptest.NewServer(http.HandlerFunc(handler)) t.Cleanup(responder.Close) responderStatusNotOK := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) })) t.Cleanup(responderStatusNotOK.Close) testCases := []struct { desc string entry *ocspEntry expectError bool }{ { desc: "no responder", entry: &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, }, expectError: true, }, { desc: "wrong responder", entry: &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{"http://foo.bar"}, }, expectError: true, }, { desc: "not ok status responder", entry: &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{responderStatusNotOK.URL}, }, expectError: true, }, { desc: "one wrong responder, one ok", entry: &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{"http://foo.bar", responder.URL}, }, }, { desc: "ok responder", entry: &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{responder.URL}, }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() ocspStapler := newOCSPStapler(nil) ocspStapler.client = &http.Client{Timeout: time.Second} err = ocspStapler.updateStaple(t.Context(), test.entry) if test.expectError { require.Error(t, err) return } require.NoError(t, err) assert.Equal(t, ocspResponse, test.entry.staple) assert.Equal(t, stapleUpdate.UTC(), test.entry.nextUpdate) }) } } func TestOCSPStapler_updateStaple_withoutNextUpdate(t *testing.T) { leafCert, err := tls.X509KeyPair([]byte(certWithOCSPServer), []byte(certKey)) require.NoError(t, err) issuerCert, err := tls.X509KeyPair([]byte(caCert), []byte(caKey)) require.NoError(t, err) thisUpdate, err := time.Parse("2006-01-02", "2025-01-01") require.NoError(t, err) ocspResponseTmpl := ocsp.Response{ SerialNumber: leafCert.Leaf.SerialNumber, TBSResponseData: []byte("foo"), ThisUpdate: thisUpdate, } ocspResponse, err := ocsp.CreateResponse(leafCert.Leaf, leafCert.Leaf, ocspResponseTmpl, issuerCert.PrivateKey.(crypto.Signer)) require.NoError(t, err) handler := func(rw http.ResponseWriter, req *http.Request) { ct := req.Header.Get("Content-Type") assert.Equal(t, "application/ocsp-request", ct) reqBytes, err := io.ReadAll(req.Body) require.NoError(t, err) _, err = ocsp.ParseRequest(reqBytes) require.NoError(t, err) rw.Header().Set("Content-Type", "application/ocsp-response") _, err = rw.Write(ocspResponse) require.NoError(t, err) } responder := httptest.NewServer(http.HandlerFunc(handler)) t.Cleanup(responder.Close) responderStatusNotOK := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusNotFound) })) t.Cleanup(responderStatusNotOK.Close) ocspStapler := newOCSPStapler(nil) ocspStapler.client = &http.Client{Timeout: time.Second} entry := &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{responder.URL}, } err = ocspStapler.updateStaple(t.Context(), entry) require.NoError(t, err) assert.Equal(t, ocspResponse, entry.staple) assert.NotZero(t, entry.nextUpdate) assert.Greater(t, time.Now(), entry.nextUpdate) } func TestOCSPStapler_updateStaples(t *testing.T) { leafCert, err := tls.X509KeyPair([]byte(certWithOCSPServer), []byte(certKey)) require.NoError(t, err) issuerCert, err := tls.X509KeyPair([]byte(caCert), []byte(caKey)) require.NoError(t, err) thisUpdate, err := time.Parse("2006-01-02", "2025-01-01") require.NoError(t, err) nextUpdate, err := time.Parse("2006-01-02", "2025-01-02") require.NoError(t, err) stapleUpdate := thisUpdate.Add(nextUpdate.Sub(thisUpdate) / 2) ocspResponseTmpl := ocsp.Response{ SerialNumber: leafCert.Leaf.SerialNumber, TBSResponseData: []byte("foo"), ThisUpdate: thisUpdate, NextUpdate: nextUpdate, } ocspResponse, err := ocsp.CreateResponse(leafCert.Leaf, leafCert.Leaf, ocspResponseTmpl, issuerCert.PrivateKey.(crypto.Signer)) require.NoError(t, err) handler := func(rw http.ResponseWriter, req *http.Request) { ct := req.Header.Get("Content-Type") assert.Equal(t, "application/ocsp-request", ct) reqBytes, err := io.ReadAll(req.Body) require.NoError(t, err) _, err = ocsp.ParseRequest(reqBytes) require.NoError(t, err) rw.Header().Set("Content-Type", "application/ocsp-response") _, err = rw.Write(ocspResponse) require.NoError(t, err) } responder := httptest.NewServer(http.HandlerFunc(handler)) t.Cleanup(responder.Close) ocspStapler := newOCSPStapler(nil) ocspStapler.client = &http.Client{Timeout: time.Second} // nil staple entry ocspStapler.cache.Set("nilStaple", &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{responder.URL}, nextUpdate: time.Now().Add(-time.Hour), }, cache.NoExpiration) // staple entry with nextUpdate in the past ocspStapler.cache.Set("toUpdate", &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{responder.URL}, staple: []byte("foo"), nextUpdate: time.Now().Add(-time.Hour), }, cache.NoExpiration) // staple entry with nextUpdate in the future inOneHour := time.Now().Add(time.Hour) ocspStapler.cache.Set("noUpdate", &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, responders: []string{responder.URL}, staple: []byte("foo"), nextUpdate: inOneHour, }, cache.NoExpiration) ocspStapler.updateStaples(t.Context()) nilStaple, ok := ocspStapler.cache.Get("nilStaple") require.True(t, ok) assert.Equal(t, ocspResponse, nilStaple.(*ocspEntry).staple) assert.Equal(t, stapleUpdate.UTC(), nilStaple.(*ocspEntry).nextUpdate) toUpdate, ok := ocspStapler.cache.Get("toUpdate") require.True(t, ok) assert.Equal(t, ocspResponse, toUpdate.(*ocspEntry).staple) assert.Equal(t, stapleUpdate.UTC(), nilStaple.(*ocspEntry).nextUpdate) noUpdate, ok := ocspStapler.cache.Get("noUpdate") require.True(t, ok) assert.Equal(t, []byte("foo"), noUpdate.(*ocspEntry).staple) assert.Equal(t, inOneHour, noUpdate.(*ocspEntry).nextUpdate) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/tlsmanager_test.go
pkg/tls/tlsmanager_test.go
package tls import ( "context" "crypto" "crypto/tls" "crypto/x509" "encoding/pem" "io" "net/http" "net/http/httptest" "testing" "time" "github.com/patrickmn/go-cache" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/types" "golang.org/x/crypto/ocsp" ) // LocalhostCert is a PEM-encoded TLS cert with SAN IPs // "127.0.0.1" and "[::1]", expiring at Jan 29 16:00:00 2084 GMT. // generated from src/crypto/tls: // go run generate_cert.go --rsa-bits 1024 --host 127.0.0.1,::1,example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h var ( localhostCert = types.FileOrContent(`-----BEGIN CERTIFICATE----- MIIDOTCCAiGgAwIBAgIQSRJrEpBGFc7tNb1fb5pKFzANBgkqhkiG9w0BAQsFADAS MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A MIIBCgKCAQEA6Gba5tHV1dAKouAaXO3/ebDUU4rvwCUg/CNaJ2PT5xLD4N1Vcb8r bFSW2HXKq+MPfVdwIKR/1DczEoAGf/JWQTW7EgzlXrCd3rlajEX2D73faWJekD0U aUgz5vtrTXZ90BQL7WvRICd7FlEZ6FPOcPlumiyNmzUqtwGhO+9ad1W5BqJaRI6P YfouNkwR6Na4TzSj5BrqUfP0FwDizKSJ0XXmh8g8G9mtwxOSN3Ru1QFc61Xyeluk POGKBV/q6RBNklTNe0gI8usUMlYyoC7ytppNMW7X2vodAelSu25jgx2anj9fDVZu h7AXF5+4nJS4AAt0n1lNY7nGSsdZas8PbQIDAQABo4GIMIGFMA4GA1UdDwEB/wQE AwICpDATBgNVHSUEDDAKBggrBgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MB0GA1Ud DgQWBBStsdjh3/JCXXYlQryOrL4Sh7BW5TAuBgNVHREEJzAlggtleGFtcGxlLmNv bYcEfwAAAYcQAAAAAAAAAAAAAAAAAAAAATANBgkqhkiG9w0BAQsFAAOCAQEAxWGI 5NhpF3nwwy/4yB4i/CwwSpLrWUa70NyhvprUBC50PxiXav1TeDzwzLx/o5HyNwsv cxv3HdkLW59i/0SlJSrNnWdfZ19oTcS+6PtLoVyISgtyN6DpkKpdG1cOkW3Cy2P2 +tK/tKHRP1Y/Ra0RiDpOAmqn0gCOFGz8+lqDIor/T7MTpibL3IxqWfPrvfVRHL3B grw/ZQTTIVjjh4JBSW3WyWgNo/ikC1lrVxzl4iPUGptxT36Cr7Zk2Bsg0XqwbOvK 5d+NTDREkSnUbie4GeutujmX3Dsx88UiV6UY/4lHJa6I5leHUNOHahRbpbWeOfs/ WkBKOclmOV2xlTVuPw== -----END CERTIFICATE-----`) // LocalhostKey is the private key for localhostCert. localhostKey = types.FileOrContent(`-----BEGIN RSA PRIVATE KEY----- MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDoZtrm0dXV0Aqi 4Bpc7f95sNRTiu/AJSD8I1onY9PnEsPg3VVxvytsVJbYdcqr4w99V3AgpH/UNzMS gAZ/8lZBNbsSDOVesJ3euVqMRfYPvd9pYl6QPRRpSDPm+2tNdn3QFAvta9EgJ3sW URnoU85w+W6aLI2bNSq3AaE771p3VbkGolpEjo9h+i42TBHo1rhPNKPkGupR8/QX AOLMpInRdeaHyDwb2a3DE5I3dG7VAVzrVfJ6W6Q84YoFX+rpEE2SVM17SAjy6xQy VjKgLvK2mk0xbtfa+h0B6VK7bmODHZqeP18NVm6HsBcXn7iclLgAC3SfWU1jucZK x1lqzw9tAgMBAAECggEABWzxS1Y2wckblnXY57Z+sl6YdmLV+gxj2r8Qib7g4ZIk lIlWR1OJNfw7kU4eryib4fc6nOh6O4AWZyYqAK6tqNQSS/eVG0LQTLTTEldHyVJL dvBe+MsUQOj4nTndZW+QvFzbcm2D8lY5n2nBSxU5ypVoKZ1EqQzytFcLZpTN7d89 EPj0qDyrV4NZlWAwL1AygCwnlwhMQjXEalVF1ylXwU3QzyZ/6MgvF6d3SSUlh+sq XefuyigXw484cQQgbzopv6niMOmGP3of+yV4JQqUSb3IDmmT68XjGd2Dkxl4iPki 6ZwXf3CCi+c+i/zVEcufgZ3SLf8D99kUGE7v7fZ6AQKBgQD1ZX3RAla9hIhxCf+O 3D+I1j2LMrdjAh0ZKKqwMR4JnHX3mjQI6LwqIctPWTU8wYFECSh9klEclSdCa64s uI/GNpcqPXejd0cAAdqHEEeG5sHMDt0oFSurL4lyud0GtZvwlzLuwEweuDtvT9cJ Wfvl86uyO36IW8JdvUprYDctrQKBgQDycZ697qutBieZlGkHpnYWUAeImVA878sJ w44NuXHvMxBPz+lbJGAg8Cn8fcxNAPqHIraK+kx3po8cZGQywKHUWsxi23ozHoxo +bGqeQb9U661TnfdDspIXia+xilZt3mm5BPzOUuRqlh4Y9SOBpSWRmEhyw76w4ZP OPxjWYAgwQKBgA/FehSYxeJgRjSdo+MWnK66tjHgDJE8bYpUZsP0JC4R9DL5oiaA brd2fI6Y+SbyeNBallObt8LSgzdtnEAbjIH8uDJqyOmknNePRvAvR6mP4xyuR+Bv m+Lgp0DMWTw5J9CKpydZDItc49T/mJ5tPhdFVd+am0NAQnmr1MCZ6nHxAoGABS3Y LkaC9FdFUUqSU8+Chkd/YbOkuyiENdkvl6t2e52jo5DVc1T7mLiIrRQi4SI8N9bN /3oJWCT+uaSLX2ouCtNFunblzWHBrhxnZzTeqVq4SLc8aESAnbslKL4i8/+vYZlN s8xtiNcSvL+lMsOBORSXzpj/4Ot8WwTkn1qyGgECgYBKNTypzAHeLE6yVadFp3nQ Ckq9yzvP/ib05rvgbvrne00YeOxqJ9gtTrzgh7koqJyX1L4NwdkEza4ilDWpucn0 xiUZS4SoaJq6ZvcBYS62Yr1t8n09iG47YL8ibgtmH3L+svaotvpVxVK+d7BLevA/ ZboOWVe3icTy64BT3OQhmg== -----END RSA PRIVATE KEY-----`) ) func TestTLSInStore(t *testing.T) { dynamicConfigs := []*CertAndStores{{ Certificate: Certificate{ CertFile: localhostCert, KeyFile: localhostKey, }, }} tlsManager := NewManager(nil) tlsManager.UpdateConfigs(t.Context(), nil, nil, dynamicConfigs) certs := tlsManager.GetStore("default").DynamicCerts.Get().(map[string]*CertificateData) if len(certs) == 0 { t.Fatal("got error: default store must have TLS certificates.") } } func TestTLSInvalidStore(t *testing.T) { dynamicConfigs := []*CertAndStores{{ Certificate: Certificate{ CertFile: localhostCert, KeyFile: localhostKey, }, }} tlsManager := NewManager(nil) tlsManager.UpdateConfigs(t.Context(), map[string]Store{ "default": { DefaultCertificate: &Certificate{ CertFile: "/wrong", KeyFile: "/wrong", }, }, }, nil, dynamicConfigs) certs := tlsManager.GetStore("default").DynamicCerts.Get().(map[string]*CertificateData) if len(certs) == 0 { t.Fatal("got error: default store must have TLS certificates.") } } func TestManager_Get(t *testing.T) { dynamicConfigs := []*CertAndStores{{ Certificate: Certificate{ CertFile: localhostCert, KeyFile: localhostKey, }, }} tlsConfigs := map[string]Options{ "foo": {MinVersion: "VersionTLS12"}, "bar": {MinVersion: "VersionTLS11"}, "invalid": {CurvePreferences: []string{"42"}}, } testCases := []struct { desc string tlsOptionsName string expectedMinVersion uint16 expectedError bool }{ { desc: "Get a tls config from a valid name", tlsOptionsName: "foo", expectedMinVersion: uint16(tls.VersionTLS12), }, { desc: "Get another tls config from a valid name", tlsOptionsName: "bar", expectedMinVersion: uint16(tls.VersionTLS11), }, { desc: "Get a tls config from an invalid name", tlsOptionsName: "unknown", expectedError: true, }, { desc: "Get a tls config from unexisting 'default' name", tlsOptionsName: "default", expectedError: true, }, { desc: "Get an invalid tls config", tlsOptionsName: "invalid", expectedError: true, }, } tlsManager := NewManager(nil) tlsManager.UpdateConfigs(t.Context(), nil, tlsConfigs, dynamicConfigs) for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() config, err := tlsManager.Get("default", test.tlsOptionsName) if test.expectedError { require.Nil(t, config) require.Error(t, err) return } require.NoError(t, err) assert.Equal(t, test.expectedMinVersion, config.MinVersion) }) } } func TestClientAuth(t *testing.T) { tlsConfigs := map[string]Options{ "eca": { ClientAuth: ClientAuth{}, }, "ecat": { ClientAuth: ClientAuth{ClientAuthType: ""}, }, "ncc": { ClientAuth: ClientAuth{ClientAuthType: "NoClientCert"}, }, "rcc": { ClientAuth: ClientAuth{ClientAuthType: "RequestClientCert"}, }, "racc": { ClientAuth: ClientAuth{ClientAuthType: "RequireAnyClientCert"}, }, "vccig": { ClientAuth: ClientAuth{ CAFiles: []types.FileOrContent{localhostCert}, ClientAuthType: "VerifyClientCertIfGiven", }, }, "vccigwca": { ClientAuth: ClientAuth{ClientAuthType: "VerifyClientCertIfGiven"}, }, "ravcc": { ClientAuth: ClientAuth{ClientAuthType: "RequireAndVerifyClientCert"}, }, "ravccwca": { ClientAuth: ClientAuth{ CAFiles: []types.FileOrContent{localhostCert}, ClientAuthType: "RequireAndVerifyClientCert", }, }, "ravccwbca": { ClientAuth: ClientAuth{ CAFiles: []types.FileOrContent{"Bad content"}, ClientAuthType: "RequireAndVerifyClientCert", }, }, "ucat": { ClientAuth: ClientAuth{ClientAuthType: "Unknown"}, }, } block, _ := pem.Decode([]byte(localhostCert)) cert, err := x509.ParseCertificate(block.Bytes) require.NoError(t, err) testCases := []struct { desc string tlsOptionsName string expectedClientAuth tls.ClientAuthType expectedRawSubject []byte expectedError bool }{ { desc: "Empty ClientAuth option should get a tls.NoClientCert (default value)", tlsOptionsName: "eca", expectedClientAuth: tls.NoClientCert, }, { desc: "Empty ClientAuthType option should get a tls.NoClientCert (default value)", tlsOptionsName: "ecat", expectedClientAuth: tls.NoClientCert, }, { desc: "NoClientCert option should get a tls.NoClientCert as ClientAuthType", tlsOptionsName: "ncc", expectedClientAuth: tls.NoClientCert, }, { desc: "RequestClientCert option should get a tls.RequestClientCert as ClientAuthType", tlsOptionsName: "rcc", expectedClientAuth: tls.RequestClientCert, }, { desc: "RequireAnyClientCert option should get a tls.RequireAnyClientCert as ClientAuthType", tlsOptionsName: "racc", expectedClientAuth: tls.RequireAnyClientCert, }, { desc: "VerifyClientCertIfGiven option should get a tls.VerifyClientCertIfGiven as ClientAuthType", tlsOptionsName: "vccig", expectedClientAuth: tls.VerifyClientCertIfGiven, }, { desc: "VerifyClientCertIfGiven option without CAFiles yields a default ClientAuthType (NoClientCert)", tlsOptionsName: "vccigwca", expectedClientAuth: tls.NoClientCert, expectedError: true, }, { desc: "RequireAndVerifyClientCert option without CAFiles yields a default ClientAuthType (NoClientCert)", tlsOptionsName: "ravcc", expectedClientAuth: tls.NoClientCert, expectedError: true, }, { desc: "RequireAndVerifyClientCert option should get a tls.RequireAndVerifyClientCert as ClientAuthType with CA files", tlsOptionsName: "ravccwca", expectedClientAuth: tls.RequireAndVerifyClientCert, expectedRawSubject: cert.RawSubject, }, { desc: "Unknown option yields a default ClientAuthType (NoClientCert)", tlsOptionsName: "ucat", expectedClientAuth: tls.NoClientCert, expectedError: true, }, { desc: "Bad CA certificate content yields a default ClientAuthType (NoClientCert)", tlsOptionsName: "ravccwbca", expectedClientAuth: tls.NoClientCert, expectedError: true, }, } tlsManager := NewManager(nil) tlsManager.UpdateConfigs(t.Context(), nil, tlsConfigs, nil) for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() config, err := tlsManager.Get("default", test.tlsOptionsName) if test.expectedError { assert.Error(t, err) return } assert.NoError(t, err) if test.expectedRawSubject != nil { subjects := config.ClientCAs.Subjects() assert.Len(t, subjects, 1) assert.Equal(t, test.expectedRawSubject, subjects[0]) } assert.Equal(t, test.expectedClientAuth, config.ClientAuth) }) } } func TestManager_UpdateConfigs_OCSPConfig(t *testing.T) { leafCert, err := tls.X509KeyPair([]byte(certWithOCSPServer), []byte(certKey)) require.NoError(t, err) issuerCert, err := tls.X509KeyPair([]byte(caCert), []byte(caKey)) require.NoError(t, err) thisUpdate, err := time.Parse("2006-01-02", "2025-01-01") require.NoError(t, err) nextUpdate, err := time.Parse("2006-01-02", "2025-01-02") require.NoError(t, err) ocspResponseTmpl := ocsp.Response{ SerialNumber: leafCert.Leaf.SerialNumber, TBSResponseData: []byte("foo"), ThisUpdate: thisUpdate, NextUpdate: nextUpdate, } ocspResponse, err := ocsp.CreateResponse(leafCert.Leaf, leafCert.Leaf, ocspResponseTmpl, issuerCert.PrivateKey.(crypto.Signer)) require.NoError(t, err) responderCall := make(chan struct{}) handler := func(rw http.ResponseWriter, req *http.Request) { ct := req.Header.Get("Content-Type") assert.Equal(t, "application/ocsp-request", ct) reqBytes, err := io.ReadAll(req.Body) require.NoError(t, err) _, err = ocsp.ParseRequest(reqBytes) require.NoError(t, err) rw.Header().Set("Content-Type", "application/ocsp-response") _, err = rw.Write(ocspResponse) require.NoError(t, err) responderCall <- struct{}{} } responder := httptest.NewServer(http.HandlerFunc(handler)) t.Cleanup(responder.Close) testContext, cancel := context.WithCancel(t.Context()) t.Cleanup(cancel) tlsManager := NewManager(&OCSPConfig{ ResponderOverrides: map[string]string{ "ocsp.example.com": responder.URL, }, }) go tlsManager.Run(testContext) tlsManager.ocspStapler.cache.Set("existing", &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, staple: []byte("foo"), nextUpdate: time.Now().Add(time.Hour), }, cache.NoExpiration) tlsManager.ocspStapler.cache.Set("existingWithTTL", &ocspEntry{ leaf: leafCert.Leaf, issuer: issuerCert.Leaf, staple: []byte("foo"), nextUpdate: time.Now().Add(time.Hour), }, 2*defaultCacheDuration) tlsManager.UpdateConfigs(testContext, nil, nil, []*CertAndStores{ { Certificate: Certificate{ CertFile: certWithOCSPServer, KeyFile: certKey, }, }, }) // Asserting that UpdateConfigs resets the expiration for existing entries. _, expiration, ok := tlsManager.ocspStapler.cache.GetWithExpiration("existing") require.True(t, ok) assert.Greater(t, expiration, time.Now()) // But not for entries with TTL already set. _, expiration, ok = tlsManager.ocspStapler.cache.GetWithExpiration("existingWithTTL") require.True(t, ok) assert.Greater(t, expiration, time.Now().Add(defaultCacheDuration)) select { case <-responderCall: case <-time.After(3 * time.Second): t.Fatal("Timeout waiting for OCSP responder call") } assert.Len(t, tlsManager.ocspStapler.cache.Items(), 3) certHash := hashRawCert(leafCert.Leaf.Raw) _, ok = tlsManager.ocspStapler.cache.Get(certHash) require.True(t, ok) } func TestManager_Get_DefaultValues(t *testing.T) { tlsManager := NewManager(nil) // Ensures we won't break things for Traefik users when updating Go config, _ := tlsManager.Get("default", "default") assert.Equal(t, uint16(tls.VersionTLS12), config.MinVersion) assert.Equal(t, []string{"h2", "http/1.1", "acme-tls/1"}, config.NextProtos) assert.False(t, config.SessionTicketsDisabled) assert.Equal(t, []uint16{ tls.TLS_AES_128_GCM_SHA256, tls.TLS_AES_256_GCM_SHA384, tls.TLS_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384, tls.TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256, tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256, }, config.CipherSuites) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/certificate.go
pkg/tls/certificate.go
package tls import ( "crypto/tls" "crypto/x509" "errors" "fmt" "net/url" "os" "strings" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/types" ) var ( // MinVersion Map of allowed TLS minimum versions. MinVersion = map[string]uint16{ `VersionTLS10`: tls.VersionTLS10, `VersionTLS11`: tls.VersionTLS11, `VersionTLS12`: tls.VersionTLS12, `VersionTLS13`: tls.VersionTLS13, } // MaxVersion Map of allowed TLS maximum versions. MaxVersion = map[string]uint16{ `VersionTLS10`: tls.VersionTLS10, `VersionTLS11`: tls.VersionTLS11, `VersionTLS12`: tls.VersionTLS12, `VersionTLS13`: tls.VersionTLS13, } // CurveIDs is a Map of TLS elliptic curves from crypto/tls // Available CurveIDs defined at https://godoc.org/crypto/tls#CurveID, // also allowing rfc names defined at https://tools.ietf.org/html/rfc8446#section-4.2.7 CurveIDs = map[string]tls.CurveID{ `secp256r1`: tls.CurveP256, `CurveP256`: tls.CurveP256, `secp384r1`: tls.CurveP384, `CurveP384`: tls.CurveP384, `secp521r1`: tls.CurveP521, `CurveP521`: tls.CurveP521, `x25519`: tls.X25519, `X25519`: tls.X25519, `x25519mlkem768`: tls.X25519MLKEM768, `X25519MLKEM768`: tls.X25519MLKEM768, } ) // Certificates defines traefik certificates type // Certs and Keys could be either a file path, or the file content itself. type Certificates []Certificate // GetCertificates retrieves the certificates as slice of tls.Certificate. func (c Certificates) GetCertificates() []tls.Certificate { var certs []tls.Certificate for _, certificate := range c { cert, err := certificate.GetCertificate() if err != nil { log.Debug().Err(err).Msg("Error while getting certificate") continue } certs = append(certs, cert) } return certs } // Certificate holds a SSL cert/key pair // Certs and Key could be either a file path, or the file content itself. type Certificate struct { CertFile types.FileOrContent `json:"certFile,omitempty" toml:"certFile,omitempty" yaml:"certFile,omitempty"` KeyFile types.FileOrContent `json:"keyFile,omitempty" toml:"keyFile,omitempty" yaml:"keyFile,omitempty" loggable:"false"` } // GetCertificate returns a tls.Certificate matching the configured CertFile and KeyFile. func (c *Certificate) GetCertificate() (tls.Certificate, error) { certContent, err := c.CertFile.Read() if err != nil { return tls.Certificate{}, fmt.Errorf("unable to read CertFile: %w", err) } keyContent, err := c.KeyFile.Read() if err != nil { return tls.Certificate{}, fmt.Errorf("unable to read KeyFile: %w", err) } cert, err := tls.X509KeyPair(certContent, keyContent) if err != nil { return tls.Certificate{}, fmt.Errorf("unable to parse TLS certificate: %w", err) } return cert, nil } // GetCertificateFromBytes returns a tls.Certificate matching the configured CertFile and KeyFile. // It assumes that the configured CertFile and KeyFile are of byte type. func (c *Certificate) GetCertificateFromBytes() (tls.Certificate, error) { cert, err := tls.X509KeyPair([]byte(c.CertFile), []byte(c.KeyFile)) if err != nil { return tls.Certificate{}, fmt.Errorf("unable to parse TLS certificate: %w", err) } return cert, nil } // GetTruncatedCertificateName truncates the certificate name. func (c *Certificate) GetTruncatedCertificateName() string { certName := c.CertFile.String() // Truncate certificate information only if it's a well formed certificate content with more than 50 characters if !c.CertFile.IsPath() && strings.HasPrefix(certName, certificateHeader) && len(certName) > len(certificateHeader)+50 { certName = strings.TrimPrefix(c.CertFile.String(), certificateHeader)[:50] } return certName } // FileOrContent hold a file path or content. type FileOrContent string func (f FileOrContent) String() string { return string(f) } // IsPath returns true if the FileOrContent is a file path, otherwise returns false. func (f FileOrContent) IsPath() bool { _, err := os.Stat(f.String()) return err == nil } func (f FileOrContent) Read() ([]byte, error) { var content []byte if f.IsPath() { var err error content, err = os.ReadFile(f.String()) if err != nil { return nil, err } } else { content = []byte(f) } return content, nil } // VerifyPeerCertificate verifies the chain certificates and their URI. func VerifyPeerCertificate(uri string, cfg *tls.Config, rawCerts [][]byte) error { // TODO: Refactor to avoid useless verifyChain (ex: when insecureskipverify is false) cert, err := verifyChain(cfg.RootCAs, rawCerts) if err != nil { return err } if len(uri) > 0 { return verifyServerCertMatchesURI(uri, cert) } return nil } // verifyServerCertMatchesURI is used on tls connections dialed to a server // to ensure that the certificate it presented has the correct URI. func verifyServerCertMatchesURI(uri string, cert *x509.Certificate) error { if cert == nil { return errors.New("peer certificate mismatch: no peer certificate presented") } // Our certs will only ever have a single URI for now so only check that if len(cert.URIs) < 1 { return errors.New("peer certificate mismatch: peer certificate invalid") } gotURI := cert.URIs[0] // Override the hostname since we rely on x509 constraints to limit ability to spoof the trust domain if needed // (i.e. because a root is shared with other PKI or Consul clusters). // This allows for seamless migrations between trust domains. expectURI := &url.URL{} id, err := url.Parse(uri) if err != nil { return fmt.Errorf("%q is not a valid URI", uri) } *expectURI = *id expectURI.Host = gotURI.Host if strings.EqualFold(gotURI.String(), expectURI.String()) { return nil } return fmt.Errorf("peer certificate mismatch got %s, want %s", gotURI, uri) } // verifyChain performs standard TLS verification without enforcing remote hostname matching. func verifyChain(rootCAs *x509.CertPool, rawCerts [][]byte) (*x509.Certificate, error) { // Fetch leaf and intermediates. This is based on code form tls handshake. if len(rawCerts) < 1 { return nil, errors.New("tls: no certificates from peer") } certs := make([]*x509.Certificate, len(rawCerts)) for i, asn1Data := range rawCerts { cert, err := x509.ParseCertificate(asn1Data) if err != nil { return nil, fmt.Errorf("tls: failed to parse certificate from peer: %w", err) } certs[i] = cert } opts := x509.VerifyOptions{ Roots: rootCAs, Intermediates: x509.NewCertPool(), } // All but the first cert are intermediates for _, cert := range certs[1:] { opts.Intermediates.AddCert(cert) } _, err := certs[0].Verify(opts) if err != nil { return nil, err } return certs[0], nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/certificate_store_test.go
pkg/tls/certificate_store_test.go
package tls import ( "crypto/tls" "fmt" "strings" "testing" "time" "github.com/patrickmn/go-cache" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/safe" ) func TestGetBestCertificate(t *testing.T) { // TODO Add tests for defaultCert testCases := []struct { desc string domainToCheck string dynamicCert string expectedCert string uppercase bool }{ { desc: "Empty Store, returns no certs", domainToCheck: "snitest.com", dynamicCert: "", expectedCert: "", }, { desc: "Best Match with no corresponding", domainToCheck: "snitest.com", dynamicCert: "snitest.org", expectedCert: "", }, { desc: "Best Match", domainToCheck: "snitest.com", dynamicCert: "snitest.com", expectedCert: "snitest.com", }, { desc: "Best Match with dynamic wildcard", domainToCheck: "www.snitest.com", dynamicCert: "*.snitest.com", expectedCert: "*.snitest.com", }, { desc: "Best Match with dynamic wildcard only, case-insensitive", domainToCheck: "bar.www.snitest.com", dynamicCert: "*.www.snitest.com", expectedCert: "*.www.snitest.com", uppercase: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() dynamicMap := map[string]*CertificateData{} if test.dynamicCert != "" { cert, err := loadTestCert(test.dynamicCert, test.uppercase) require.NoError(t, err) dynamicMap[strings.ToLower(test.dynamicCert)] = &CertificateData{Certificate: cert} } store := &CertificateStore{ DynamicCerts: safe.New(dynamicMap), CertCache: cache.New(1*time.Hour, 10*time.Minute), } var expected *tls.Certificate if test.expectedCert != "" { cert, err := loadTestCert(test.expectedCert, test.uppercase) require.NoError(t, err) expected = cert } clientHello := &tls.ClientHelloInfo{ ServerName: test.domainToCheck, } actual := store.GetBestCertificate(clientHello) assert.Equal(t, expected, actual) }) } } func loadTestCert(certName string, uppercase bool) (*tls.Certificate, error) { replacement := "wildcard" if uppercase { replacement = "uppercase_wildcard" } staticCert, err := tls.LoadX509KeyPair( fmt.Sprintf("../../integration/fixtures/https/%s.cert", strings.ReplaceAll(certName, "*", replacement)), fmt.Sprintf("../../integration/fixtures/https/%s.key", strings.ReplaceAll(certName, "*", replacement)), ) if err != nil { return nil, err } return &staticCert, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/version.go
pkg/tls/version.go
package tls import "crypto/tls" // GetVersion returns the normalized TLS version. // Available TLS versions defined at https://pkg.go.dev/crypto/tls/#pkg-constants func GetVersion(connState *tls.ConnectionState) string { switch connState.Version { case tls.VersionTLS10: return "1.0" case tls.VersionTLS11: return "1.1" case tls.VersionTLS12: return "1.2" case tls.VersionTLS13: return "1.3" } return "unknown" }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/certificate_store.go
pkg/tls/certificate_store.go
package tls import ( "crypto/tls" "fmt" "net" "sort" "strings" "time" "github.com/patrickmn/go-cache" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/safe" ) // CertificateData holds runtime data for runtime TLS certificate handling. type CertificateData struct { Hash string Certificate *tls.Certificate } // CertificateStore store for dynamic certificates. type CertificateStore struct { DynamicCerts *safe.Safe DefaultCertificate *CertificateData CertCache *cache.Cache ocspStapler *ocspStapler } // NewCertificateStore create a store for dynamic certificates. func NewCertificateStore(ocspStapler *ocspStapler) *CertificateStore { var dynamicCerts safe.Safe dynamicCerts.Set(make(map[string]*CertificateData)) return &CertificateStore{ DynamicCerts: &dynamicCerts, CertCache: cache.New(1*time.Hour, 10*time.Minute), ocspStapler: ocspStapler, } } // GetAllDomains return a slice with all the certificate domain. func (c *CertificateStore) GetAllDomains() []string { allDomains := c.getDefaultCertificateDomains() // Get dynamic certificates if c.DynamicCerts != nil && c.DynamicCerts.Get() != nil { for domain := range c.DynamicCerts.Get().(map[string]*CertificateData) { allDomains = append(allDomains, domain) } } return allDomains } // GetDefaultCertificate returns the default certificate. func (c *CertificateStore) GetDefaultCertificate() *tls.Certificate { if c == nil { return nil } if c.ocspStapler != nil && c.DefaultCertificate.Hash != "" { if staple, ok := c.ocspStapler.GetStaple(c.DefaultCertificate.Hash); ok { // We are updating the OCSPStaple of the certificate without any synchronization // as this should not cause any issue. c.DefaultCertificate.Certificate.OCSPStaple = staple } } return c.DefaultCertificate.Certificate } // GetBestCertificate returns the best match certificate, and caches the response. func (c *CertificateStore) GetBestCertificate(clientHello *tls.ClientHelloInfo) *tls.Certificate { if c == nil { return nil } serverName := strings.ToLower(strings.TrimSpace(clientHello.ServerName)) if len(serverName) == 0 { // If no ServerName is provided, Check for local IP address matches host, _, err := net.SplitHostPort(clientHello.Conn.LocalAddr().String()) if err != nil { log.Debug().Err(err).Msg("Could not split host/port") } serverName = strings.TrimSpace(host) } if cert, ok := c.CertCache.Get(serverName); ok { certificateData := cert.(*CertificateData) if c.ocspStapler != nil && certificateData.Hash != "" { if staple, ok := c.ocspStapler.GetStaple(certificateData.Hash); ok { // We are updating the OCSPStaple of the certificate without any synchronization // as this should not cause any issue. certificateData.Certificate.OCSPStaple = staple } } return certificateData.Certificate } matchedCerts := map[string]*CertificateData{} if c.DynamicCerts != nil && c.DynamicCerts.Get() != nil { for domains, cert := range c.DynamicCerts.Get().(map[string]*CertificateData) { for _, certDomain := range strings.Split(domains, ",") { if matchDomain(serverName, certDomain) { matchedCerts[certDomain] = cert } } } } if len(matchedCerts) > 0 { // sort map by keys keys := make([]string, 0, len(matchedCerts)) for k := range matchedCerts { keys = append(keys, k) } sort.Strings(keys) // cache best match certificateData := matchedCerts[keys[len(keys)-1]] c.CertCache.SetDefault(serverName, certificateData) if c.ocspStapler != nil && certificateData.Hash != "" { if staple, ok := c.ocspStapler.GetStaple(certificateData.Hash); ok { // We are updating the OCSPStaple of the certificate without any synchronization // as this should not cause any issue. certificateData.Certificate.OCSPStaple = staple } } return certificateData.Certificate } return nil } // GetCertificate returns the first certificate matching all the given domains. func (c *CertificateStore) GetCertificate(domains []string) *CertificateData { if c == nil { return nil } sort.Strings(domains) domainsKey := strings.Join(domains, ",") if cert, ok := c.CertCache.Get(domainsKey); ok { return cert.(*CertificateData) } if c.DynamicCerts != nil && c.DynamicCerts.Get() != nil { for certDomains, cert := range c.DynamicCerts.Get().(map[string]*CertificateData) { if domainsKey == certDomains { c.CertCache.SetDefault(domainsKey, cert) return cert } var matchedDomains []string for _, certDomain := range strings.Split(certDomains, ",") { for _, checkDomain := range domains { if certDomain == checkDomain { matchedDomains = append(matchedDomains, certDomain) } } } if len(matchedDomains) == len(domains) { c.CertCache.SetDefault(domainsKey, cert) return cert } } } return nil } // ResetCache clears the cache in the store. func (c *CertificateStore) ResetCache() { if c.CertCache != nil { c.CertCache.Flush() } } func (c *CertificateStore) getDefaultCertificateDomains() []string { if c.DefaultCertificate == nil { return nil } defaultCert := c.DefaultCertificate.Certificate.Leaf var allCerts []string if len(defaultCert.Subject.CommonName) > 0 { allCerts = append(allCerts, defaultCert.Subject.CommonName) } allCerts = append(allCerts, defaultCert.DNSNames...) for _, ipSan := range defaultCert.IPAddresses { allCerts = append(allCerts, ipSan.String()) } return allCerts } // appendCertificate appends a Certificate to a certificates map keyed by store name. func appendCertificate(certs map[string]map[string]*CertificateData, subjectAltNames []string, storeName string, cert *CertificateData) { // Guarantees the order to produce a unique cert key. sort.Strings(subjectAltNames) certKey := strings.Join(subjectAltNames, ",") certExists := false if certs[storeName] == nil { certs[storeName] = make(map[string]*CertificateData) } else { for domains := range certs[storeName] { if domains == certKey { certExists = true break } } } if certExists { log.Debug().Msgf("Skipping addition of certificate for domain(s) %q, to TLS Store %s, as it already exists for this store.", certKey, storeName) } else { log.Debug().Msgf("Adding certificate for domain(s) %s", certKey) certs[storeName][certKey] = cert } } func parseCertificate(cert *Certificate) (tls.Certificate, []string, error) { certContent, err := cert.CertFile.Read() if err != nil { return tls.Certificate{}, nil, fmt.Errorf("unable to read CertFile: %w", err) } keyContent, err := cert.KeyFile.Read() if err != nil { return tls.Certificate{}, nil, fmt.Errorf("unable to read KeyFile: %w", err) } tlsCert, err := tls.X509KeyPair(certContent, keyContent) if err != nil { return tls.Certificate{}, nil, fmt.Errorf("unable to generate TLS certificate: %w", err) } var SANs []string if tlsCert.Leaf.Subject.CommonName != "" { SANs = append(SANs, strings.ToLower(tlsCert.Leaf.Subject.CommonName)) } if tlsCert.Leaf.DNSNames != nil { for _, dnsName := range tlsCert.Leaf.DNSNames { if dnsName != tlsCert.Leaf.Subject.CommonName { SANs = append(SANs, strings.ToLower(dnsName)) } } } if tlsCert.Leaf.IPAddresses != nil { for _, ip := range tlsCert.Leaf.IPAddresses { if ip.String() != tlsCert.Leaf.Subject.CommonName { SANs = append(SANs, strings.ToLower(ip.String())) } } } return tlsCert, SANs, err } // matchDomain returns whether the server name matches the cert domain. // The server name, from TLS SNI, must not have trailing dots (https://datatracker.ietf.org/doc/html/rfc6066#section-3). // This is enforced by https://github.com/golang/go/blob/d3d7998756c33f69706488cade1cd2b9b10a4c7f/src/crypto/tls/handshake_messages.go#L423-L427. func matchDomain(serverName, certDomain string) bool { // TODO: assert equality after removing the trailing dots? if serverName == certDomain { return true } for len(certDomain) > 0 && certDomain[len(certDomain)-1] == '.' { certDomain = certDomain[:len(certDomain)-1] } labels := strings.Split(serverName, ".") for i := range labels { labels[i] = "*" candidate := strings.Join(labels, ".") if certDomain == candidate { return true } } return false }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/cipher_test.go
pkg/tls/cipher_test.go
package tls import ( "testing" ) func TestCiphersMapsSync(t *testing.T) { for k, v := range CipherSuites { // Following names are legacy aliases. // We do not test for their presence in CipherSuitesReversed switch k { case "TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305", "TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305": continue } if rv, ok := CipherSuitesReversed[v]; !ok { t.Errorf("Maps not in sync: `%d` key is missing in tls.CipherSuitesReversed", v) } else if k != rv { t.Errorf("Maps not in sync: tls.CipherSuites[%s] = `%d` AND tls.CipherSuitesReversed[`%d`] = `%v`", k, v, v, rv) } } for k, v := range CipherSuitesReversed { if rv, ok := CipherSuites[v]; !ok { t.Errorf("Maps not in sync: `%s` key is missing in tls.CipherSuites", v) } else if k != rv { t.Errorf("Maps not in sync: tls.CipherSuitesReversed[`%d`] = `%s` AND tls.CipherSuites[`%s`] = `%d`", k, v, v, rv) } } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/tls.go
pkg/tls/tls.go
package tls import "github.com/traefik/traefik/v3/pkg/types" const certificateHeader = "-----BEGIN CERTIFICATE-----\n" // +k8s:deepcopy-gen=true // ClientAuth defines the parameters of the client authentication part of the TLS connection, if any. type ClientAuth struct { CAFiles []types.FileOrContent `json:"caFiles,omitempty" toml:"caFiles,omitempty" yaml:"caFiles,omitempty"` // ClientAuthType defines the client authentication type to apply. // The available values are: "NoClientCert", "RequestClientCert", "VerifyClientCertIfGiven" and "RequireAndVerifyClientCert". ClientAuthType string `json:"clientAuthType,omitempty" toml:"clientAuthType,omitempty" yaml:"clientAuthType,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // Options configures TLS for an entry point. type Options struct { MinVersion string `json:"minVersion,omitempty" toml:"minVersion,omitempty" yaml:"minVersion,omitempty" export:"true"` MaxVersion string `json:"maxVersion,omitempty" toml:"maxVersion,omitempty" yaml:"maxVersion,omitempty" export:"true"` CipherSuites []string `json:"cipherSuites,omitempty" toml:"cipherSuites,omitempty" yaml:"cipherSuites,omitempty" export:"true"` CurvePreferences []string `json:"curvePreferences,omitempty" toml:"curvePreferences,omitempty" yaml:"curvePreferences,omitempty" export:"true"` ClientAuth ClientAuth `json:"clientAuth,omitempty" toml:"clientAuth,omitempty" yaml:"clientAuth,omitempty"` SniStrict bool `json:"sniStrict,omitempty" toml:"sniStrict,omitempty" yaml:"sniStrict,omitempty" export:"true"` ALPNProtocols []string `json:"alpnProtocols,omitempty" toml:"alpnProtocols,omitempty" yaml:"alpnProtocols,omitempty" export:"true"` DisableSessionTickets bool `json:"disableSessionTickets,omitempty" toml:"disableSessionTickets,omitempty" yaml:"disableSessionTickets,omitempty" export:"true"` // Deprecated: https://github.com/golang/go/issues/45430 PreferServerCipherSuites *bool `json:"preferServerCipherSuites,omitempty" toml:"preferServerCipherSuites,omitempty" yaml:"preferServerCipherSuites,omitempty" export:"true"` } // SetDefaults sets the default values for an Options struct. func (o *Options) SetDefaults() { // ensure http2 enabled o.ALPNProtocols = DefaultTLSOptions.ALPNProtocols o.CipherSuites = DefaultTLSOptions.CipherSuites } // +k8s:deepcopy-gen=true // Store holds the options for a given Store. type Store struct { DefaultCertificate *Certificate `json:"defaultCertificate,omitempty" toml:"defaultCertificate,omitempty" yaml:"defaultCertificate,omitempty" label:"-" export:"true"` DefaultGeneratedCert *GeneratedCert `json:"defaultGeneratedCert,omitempty" toml:"defaultGeneratedCert,omitempty" yaml:"defaultGeneratedCert,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // GeneratedCert defines the default generated certificate configuration. type GeneratedCert struct { // Resolver is the name of the resolver that will be used to issue the DefaultCertificate. Resolver string `json:"resolver,omitempty" toml:"resolver,omitempty" yaml:"resolver,omitempty" export:"true"` // Domain is the domain definition for the DefaultCertificate. Domain *types.Domain `json:"domain,omitempty" toml:"domain,omitempty" yaml:"domain,omitempty" export:"true"` } // +k8s:deepcopy-gen=true // CertAndStores allows mapping a TLS certificate to a list of entry points. type CertAndStores struct { Certificate `yaml:",inline" export:"true"` Stores []string `json:"stores,omitempty" toml:"stores,omitempty" yaml:"stores,omitempty" export:"true"` }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tls/generate/generate.go
pkg/tls/generate/generate.go
package generate import ( "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "encoding/hex" "encoding/pem" "fmt" "math/big" "time" ) // DefaultDomain Traefik domain for the default certificate. const DefaultDomain = "TRAEFIK DEFAULT CERT" // DefaultCertificate generates random TLS certificates. func DefaultCertificate() (*tls.Certificate, error) { randomBytes := make([]byte, 100) _, err := rand.Read(randomBytes) if err != nil { return nil, err } zBytes := sha256.Sum256(randomBytes) z := hex.EncodeToString(zBytes[:sha256.Size]) domain := fmt.Sprintf("%s.%s.traefik.default", z[:32], z[32:]) certPEM, keyPEM, err := KeyPair(domain, time.Time{}) if err != nil { return nil, err } certificate, err := tls.X509KeyPair(certPEM, keyPEM) if err != nil { return nil, err } return &certificate, nil } // KeyPair generates cert and key files. func KeyPair(domain string, expiration time.Time) ([]byte, []byte, error) { rsaPrivKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { return nil, nil, err } keyPEM := pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(rsaPrivKey)}) certPEM, err := PemCert(rsaPrivKey, domain, expiration) if err != nil { return nil, nil, err } return certPEM, keyPEM, nil } // PemCert generates PEM cert file. func PemCert(privKey *rsa.PrivateKey, domain string, expiration time.Time) ([]byte, error) { derBytes, err := derCert(privKey, expiration, domain) if err != nil { return nil, err } return pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes}), nil } func derCert(privKey *rsa.PrivateKey, expiration time.Time, domain string) ([]byte, error) { serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) if err != nil { return nil, err } if expiration.IsZero() { expiration = time.Now().Add(365 * (24 * time.Hour)) } template := x509.Certificate{ SerialNumber: serialNumber, Subject: pkix.Name{ CommonName: DefaultDomain, }, NotBefore: time.Now(), NotAfter: expiration, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature | x509.KeyUsageKeyAgreement | x509.KeyUsageDataEncipherment, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, BasicConstraintsValid: true, DNSNames: []string{domain}, } return x509.CreateCertificate(rand.Reader, &template, &template, &privKey.PublicKey, privKey) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/switcher.go
pkg/tcp/switcher.go
package tcp import ( "github.com/traefik/traefik/v3/pkg/safe" ) // HandlerSwitcher is a TCP handler switcher. type HandlerSwitcher struct { router safe.Safe } // ServeTCP forwards the TCP connection to the current active handler. func (s *HandlerSwitcher) ServeTCP(conn WriteCloser) { handler := s.router.Get() h, ok := handler.(Handler) if ok { h.ServeTCP(conn) } else { conn.Close() } } // Switch sets the new TCP handler to use for new connections. func (s *HandlerSwitcher) Switch(handler Handler) { s.router.Set(handler) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/proxy.go
pkg/tcp/proxy.go
package tcp import ( "errors" "io" "net" "syscall" "time" "github.com/rs/zerolog/log" ) // Proxy forwards a TCP request to a TCP service. type Proxy struct { address string dialer Dialer } // NewProxy creates a new Proxy. func NewProxy(address string, dialer Dialer) (*Proxy, error) { return &Proxy{ address: address, dialer: dialer, }, nil } // ServeTCP forwards the connection to a service. func (p *Proxy) ServeTCP(conn WriteCloser) { log.Debug(). Str("address", p.address). Str("remoteAddr", conn.RemoteAddr().String()). Msg("Handling TCP connection") // needed because of e.g. server.trackedConnection defer conn.Close() connBackend, err := p.dialBackend(conn) if err != nil { log.Error().Err(err).Msg("Error while dialing backend") return } // maybe not needed, but just in case defer connBackend.Close() errChan := make(chan error) go p.connCopy(conn, connBackend, errChan) go p.connCopy(connBackend, conn, errChan) err = <-errChan if err != nil { // Treat connection reset error during a read operation with a lower log level. // This allows to not report an RST packet sent by the peer as an error, // as it is an abrupt but possible end for the TCP session if isReadConnResetError(err) { log.Debug().Err(err).Msg("Error while handling TCP connection") } else { log.Error().Err(err).Msg("Error while handling TCP connection") } } <-errChan } func (p *Proxy) dialBackend(clientConn net.Conn) (WriteCloser, error) { // The clientConn is passed to the dialer so that it can use information from it if needed, // to build a PROXY protocol header. conn, err := p.dialer.Dial("tcp", p.address, clientConn) if err != nil { return nil, err } return conn.(WriteCloser), nil } func (p *Proxy) connCopy(dst, src WriteCloser, errCh chan error) { _, err := io.Copy(dst, src) errCh <- err // Ends the connection with the dst connection peer. // It corresponds to sending a FIN packet to gracefully end the TCP session. errClose := dst.CloseWrite() if errClose != nil { // Calling CloseWrite() on a connection which have a socket which is "not connected" is expected to fail. // It happens notably when the dst connection has ended receiving an RST packet from the peer (within the other connCopy call). // In that case, logging the error is superfluous, // as in the first place we should not have needed to call CloseWrite. if !isSocketNotConnectedError(errClose) { log.Debug().Err(errClose).Msg("Error while terminating TCP connection") } return } if p.dialer.TerminationDelay() >= 0 { err := dst.SetReadDeadline(time.Now().Add(p.dialer.TerminationDelay())) if err != nil { log.Debug().Err(err).Msg("Error while setting TCP connection deadline") } } } // isSocketNotConnectedError reports whether err is a socket not connected error. func isSocketNotConnectedError(err error) bool { var oerr *net.OpError return errors.As(err, &oerr) && errors.Is(err, syscall.ENOTCONN) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/dialer.go
pkg/tcp/dialer.go
package tcp import ( "context" "crypto/tls" "crypto/x509" "errors" "fmt" "net" "sync" "time" "github.com/pires/go-proxyproto" "github.com/rs/zerolog/log" "github.com/spiffe/go-spiffe/v2/bundle/x509bundle" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig" "github.com/spiffe/go-spiffe/v2/svid/x509svid" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/config/dynamic" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) // ClientConn is the interface that provides information about the client connection. type ClientConn interface { // LocalAddr returns the local network address, if known. LocalAddr() net.Addr // RemoteAddr returns the remote network address, if known. RemoteAddr() net.Addr } // Dialer is an interface to dial a network connection, with support for PROXY protocol and termination delay. type Dialer interface { Dial(network, addr string, clientConn ClientConn) (c net.Conn, err error) DialContext(ctx context.Context, network, addr string, clientConn ClientConn) (c net.Conn, err error) TerminationDelay() time.Duration } type tcpDialer struct { dialer *net.Dialer terminationDelay time.Duration proxyProtocol *dynamic.ProxyProtocol } // TerminationDelay returns the termination delay duration. func (d tcpDialer) TerminationDelay() time.Duration { return d.terminationDelay } // Dial dials a network connection and optionally sends a PROXY protocol header. func (d tcpDialer) Dial(network, addr string, clientConn ClientConn) (net.Conn, error) { return d.DialContext(context.Background(), network, addr, clientConn) } // DialContext dials a network connection and optionally sends a PROXY protocol header, with context. func (d tcpDialer) DialContext(ctx context.Context, network, addr string, clientConn ClientConn) (net.Conn, error) { conn, err := d.dialer.DialContext(ctx, network, addr) if err != nil { return nil, err } if d.proxyProtocol != nil && clientConn != nil && d.proxyProtocol.Version > 0 && d.proxyProtocol.Version < 3 { header := proxyproto.HeaderProxyFromAddrs(byte(d.proxyProtocol.Version), clientConn.RemoteAddr(), clientConn.LocalAddr()) if _, err := header.WriteTo(conn); err != nil { _ = conn.Close() return nil, fmt.Errorf("writing PROXY Protocol header: %w", err) } } return conn, nil } type tcpTLSDialer struct { tcpDialer tlsConfig *tls.Config } // Dial dials a network connection with the wrapped tcpDialer and performs a TLS handshake. func (d tcpTLSDialer) Dial(network, addr string, clientConn ClientConn) (net.Conn, error) { return d.DialContext(context.Background(), network, addr, clientConn) } // DialContext dials a network connection with the wrapped tcpDialer and performs a TLS handshake, with context. func (d tcpTLSDialer) DialContext(ctx context.Context, network, addr string, clientConn ClientConn) (net.Conn, error) { conn, err := d.tcpDialer.DialContext(ctx, network, addr, clientConn) if err != nil { return nil, err } // Now perform TLS handshake on the connection tlsConn := tls.Client(conn, d.tlsConfig) if err := tlsConn.Handshake(); err != nil { _ = conn.Close() return nil, fmt.Errorf("TLS handshake failed: %w", err) } return tlsConn, nil } // SpiffeX509Source allows retrieving a x509 SVID and bundle. type SpiffeX509Source interface { x509svid.Source x509bundle.Source } // DialerManager handles dialer for the reverse proxy. type DialerManager struct { serversTransportsMu sync.RWMutex serversTransports map[string]*dynamic.TCPServersTransport spiffeX509Source SpiffeX509Source } // NewDialerManager creates a new DialerManager. func NewDialerManager(spiffeX509Source SpiffeX509Source) *DialerManager { return &DialerManager{ serversTransports: make(map[string]*dynamic.TCPServersTransport), spiffeX509Source: spiffeX509Source, } } // Update updates the TCP serversTransport configurations. func (d *DialerManager) Update(configs map[string]*dynamic.TCPServersTransport) { d.serversTransportsMu.Lock() defer d.serversTransportsMu.Unlock() d.serversTransports = configs } // Build builds a dialer by name. func (d *DialerManager) Build(config *dynamic.TCPServersLoadBalancer, isTLS bool) (Dialer, error) { name := "default@internal" if config.ServersTransport != "" { name = config.ServersTransport } var st *dynamic.TCPServersTransport d.serversTransportsMu.RLock() st, ok := d.serversTransports[name] d.serversTransportsMu.RUnlock() if !ok || st == nil { return nil, fmt.Errorf("no transport configuration found for %q", name) } // Handle TerminationDelay and ProxyProtocol deprecated options. var terminationDelay ptypes.Duration if config.TerminationDelay != nil { terminationDelay = ptypes.Duration(*config.TerminationDelay) } proxyProtocol := config.ProxyProtocol if config.ServersTransport != "" { terminationDelay = st.TerminationDelay proxyProtocol = st.ProxyProtocol } if proxyProtocol != nil && (proxyProtocol.Version < 1 || proxyProtocol.Version > 2) { return nil, fmt.Errorf("unknown proxyProtocol version: %d", proxyProtocol.Version) } var tlsConfig *tls.Config if st.TLS != nil { if st.TLS.Spiffe != nil { if d.spiffeX509Source == nil { return nil, errors.New("SPIFFE is enabled for this transport, but not configured") } authorizer, err := buildSpiffeAuthorizer(st.TLS.Spiffe) if err != nil { return nil, fmt.Errorf("unable to build SPIFFE authorizer: %w", err) } tlsConfig = tlsconfig.MTLSClientConfig(d.spiffeX509Source, d.spiffeX509Source, authorizer) } if st.TLS.InsecureSkipVerify || len(st.TLS.RootCAs) > 0 || len(st.TLS.ServerName) > 0 || len(st.TLS.Certificates) > 0 || st.TLS.PeerCertURI != "" { if tlsConfig != nil { return nil, errors.New("TLS and SPIFFE configuration cannot be defined at the same time") } tlsConfig = &tls.Config{ ServerName: st.TLS.ServerName, InsecureSkipVerify: st.TLS.InsecureSkipVerify, RootCAs: createRootCACertPool(st.TLS.RootCAs), Certificates: st.TLS.Certificates.GetCertificates(), } if st.TLS.PeerCertURI != "" { tlsConfig.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error { return traefiktls.VerifyPeerCertificate(st.TLS.PeerCertURI, tlsConfig, rawCerts) } } } } dialer := tcpDialer{ dialer: &net.Dialer{ Timeout: time.Duration(st.DialTimeout), KeepAlive: time.Duration(st.DialKeepAlive), }, terminationDelay: time.Duration(terminationDelay), proxyProtocol: proxyProtocol, } if !isTLS { return dialer, nil } return tcpTLSDialer{dialer, tlsConfig}, nil } func createRootCACertPool(rootCAs []types.FileOrContent) *x509.CertPool { if len(rootCAs) == 0 { return nil } roots := x509.NewCertPool() for _, cert := range rootCAs { certContent, err := cert.Read() if err != nil { log.Err(err).Msg("Error while read RootCAs") continue } roots.AppendCertsFromPEM(certContent) } return roots } func buildSpiffeAuthorizer(cfg *dynamic.Spiffe) (tlsconfig.Authorizer, error) { switch { case len(cfg.IDs) > 0: spiffeIDs := make([]spiffeid.ID, 0, len(cfg.IDs)) for _, rawID := range cfg.IDs { id, err := spiffeid.FromString(rawID) if err != nil { return nil, fmt.Errorf("invalid SPIFFE ID: %w", err) } spiffeIDs = append(spiffeIDs, id) } return tlsconfig.AuthorizeOneOf(spiffeIDs...), nil case cfg.TrustDomain != "": trustDomain, err := spiffeid.TrustDomainFromString(cfg.TrustDomain) if err != nil { return nil, fmt.Errorf("invalid SPIFFE trust domain: %w", err) } return tlsconfig.AuthorizeMemberOf(trustDomain), nil default: return tlsconfig.AuthorizeAny(), nil } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/chain_test.go
pkg/tcp/chain_test.go
package tcp import ( "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) type HandlerTCPFunc func(WriteCloser) // ServeTCP calls f(conn). func (f HandlerTCPFunc) ServeTCP(conn WriteCloser) { f(conn) } // A constructor for middleware // that writes its own "tag" into the Conn and does nothing else. // Useful in checking if a chain is behaving in the right order. func tagMiddleware(tag string) Constructor { return func(h Handler) (Handler, error) { return HandlerTCPFunc(func(conn WriteCloser) { _, err := conn.Write([]byte(tag)) if err != nil { panic("Unexpected") } h.ServeTCP(conn) }), nil } } var testApp = HandlerTCPFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("app\n")) if err != nil { panic("unexpected") } }) type myWriter struct { data []byte } func (mw *myWriter) Close() error { panic("implement me") } func (mw *myWriter) LocalAddr() net.Addr { panic("implement me") } func (mw *myWriter) RemoteAddr() net.Addr { panic("implement me") } func (mw *myWriter) SetDeadline(t time.Time) error { panic("implement me") } func (mw *myWriter) SetReadDeadline(t time.Time) error { panic("implement me") } func (mw *myWriter) SetWriteDeadline(t time.Time) error { panic("implement me") } func (mw *myWriter) Read(b []byte) (n int, err error) { panic("implement me") } func (mw *myWriter) Write(b []byte) (n int, err error) { mw.data = append(mw.data, b...) return len(mw.data), nil } func (mw *myWriter) CloseWrite() error { return nil } func TestNewChain(t *testing.T) { c1 := func(h Handler) (Handler, error) { return nil, nil } c2 := func(h Handler) (Handler, error) { return h, nil } slice := []Constructor{c1, c2} chain := NewChain(slice...) for k := range slice { assert.ObjectsAreEqual(chain.constructors[k], slice[k]) } } func TestThenWorksWithNoMiddleware(t *testing.T) { handler, err := NewChain().Then(testApp) require.NoError(t, err) assert.ObjectsAreEqual(handler, testApp) } func TestThenTreatsNilAsError(t *testing.T) { handler, err := NewChain().Then(nil) require.Error(t, err) assert.Nil(t, handler) } func TestThenOrdersHandlersCorrectly(t *testing.T) { t1 := tagMiddleware("t1\n") t2 := tagMiddleware("t2\n") t3 := tagMiddleware("t3\n") chained, err := NewChain(t1, t2, t3).Then(testApp) require.NoError(t, err) conn := &myWriter{} chained.ServeTCP(conn) assert.Equal(t, "t1\nt2\nt3\napp\n", string(conn.data)) } func TestAppendAddsHandlersCorrectly(t *testing.T) { chain := NewChain(tagMiddleware("t1\n"), tagMiddleware("t2\n")) newChain := chain.Append(tagMiddleware("t3\n"), tagMiddleware("t4\n")) assert.Len(t, chain.constructors, 2) assert.Len(t, newChain.constructors, 4) chained, err := newChain.Then(testApp) require.NoError(t, err) conn := &myWriter{} chained.ServeTCP(conn) assert.Equal(t, "t1\nt2\nt3\nt4\napp\n", string(conn.data)) } func TestAppendRespectsImmutability(t *testing.T) { chain := NewChain(tagMiddleware("")) newChain := chain.Append(tagMiddleware("")) if &chain.constructors[0] == &newChain.constructors[0] { t.Error("Append does not respect immutability") } } func TestExtendAddsHandlersCorrectly(t *testing.T) { chain1 := NewChain(tagMiddleware("t1\n"), tagMiddleware("t2\n")) chain2 := NewChain(tagMiddleware("t3\n"), tagMiddleware("t4\n")) newChain := chain1.Extend(chain2) assert.Len(t, chain1.constructors, 2) assert.Len(t, chain2.constructors, 2) assert.Len(t, newChain.constructors, 4) chained, err := newChain.Then(testApp) require.NoError(t, err) conn := &myWriter{} chained.ServeTCP(conn) assert.Equal(t, "t1\nt2\nt3\nt4\napp\n", string(conn.data)) } func TestExtendRespectsImmutability(t *testing.T) { chain := NewChain(tagMiddleware("")) newChain := chain.Extend(NewChain(tagMiddleware(""))) if &chain.constructors[0] == &newChain.constructors[0] { t.Error("Extend does not respect immutability") } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/wrr_load_balancer.go
pkg/tcp/wrr_load_balancer.go
package tcp import ( "context" "errors" "sync" "github.com/rs/zerolog/log" ) var errNoServersInPool = errors.New("no servers in the pool") type server struct { Handler name string weight int } // WRRLoadBalancer is a naive RoundRobin load balancer for TCP services. type WRRLoadBalancer struct { // serversMu is a mutex to protect the handlers slice and the status. serversMu sync.Mutex servers []server // status is a record of which child services of the Balancer are healthy, keyed // by name of child service. A service is initially added to the map when it is // created via Add, and it is later removed or added to the map as needed, // through the SetStatus method. status map[string]struct{} // updaters is the list of hooks that are run (to update the Balancer parent(s)), whenever the Balancer status changes. // No mutex is needed, as it is modified only during the configuration build. updaters []func(bool) index int currentWeight int wantsHealthCheck bool } // NewWRRLoadBalancer creates a new WRRLoadBalancer. func NewWRRLoadBalancer(wantsHealthCheck bool) *WRRLoadBalancer { return &WRRLoadBalancer{ status: make(map[string]struct{}), index: -1, wantsHealthCheck: wantsHealthCheck, } } // ServeTCP forwards the connection to the right service. func (b *WRRLoadBalancer) ServeTCP(conn WriteCloser) { next, err := b.nextServer() if err != nil { if !errors.Is(err, errNoServersInPool) { log.Error().Err(err).Msg("Error during load balancing") } _ = conn.Close() return } next.ServeTCP(conn) } // Add appends a server to the existing list with a name and weight. func (b *WRRLoadBalancer) Add(name string, handler Handler, weight *int) { w := 1 if weight != nil { w = *weight } b.serversMu.Lock() b.servers = append(b.servers, server{Handler: handler, name: name, weight: w}) b.status[name] = struct{}{} b.serversMu.Unlock() } // SetStatus sets status (UP or DOWN) of a target server. func (b *WRRLoadBalancer) SetStatus(ctx context.Context, childName string, up bool) { b.serversMu.Lock() defer b.serversMu.Unlock() upBefore := len(b.status) > 0 status := "DOWN" if up { status = "UP" } log.Ctx(ctx).Debug().Msgf("Setting status of %s to %v", childName, status) if up { b.status[childName] = struct{}{} } else { delete(b.status, childName) } upAfter := len(b.status) > 0 status = "DOWN" if upAfter { status = "UP" } // No Status Change if upBefore == upAfter { // We're still with the same status, no need to propagate log.Ctx(ctx).Debug().Msgf("Still %s, no need to propagate", status) return } // Status Change log.Ctx(ctx).Debug().Msgf("Propagating new %s status", status) for _, fn := range b.updaters { fn(upAfter) } } func (b *WRRLoadBalancer) RegisterStatusUpdater(fn func(up bool)) error { if !b.wantsHealthCheck { return errors.New("healthCheck not enabled in config for this weighted service") } b.updaters = append(b.updaters, fn) return nil } func (b *WRRLoadBalancer) nextServer() (Handler, error) { b.serversMu.Lock() defer b.serversMu.Unlock() if len(b.servers) == 0 || len(b.status) == 0 { return nil, errNoServersInPool } // The algo below may look messy, but is actually very simple // it calculates the GCD and subtracts it on every iteration, what interleaves servers // and allows us not to build an iterator every time we readjust weights. // Maximum weight across all enabled servers. maximum := b.maxWeight() if maximum == 0 { return nil, errors.New("all servers have 0 weight") } // GCD across all enabled servers gcd := b.weightGcd() for { b.index = (b.index + 1) % len(b.servers) if b.index == 0 { b.currentWeight -= gcd if b.currentWeight <= 0 { b.currentWeight = maximum } } srv := b.servers[b.index] if _, ok := b.status[srv.name]; ok && srv.weight >= b.currentWeight { return srv, nil } } } func (b *WRRLoadBalancer) maxWeight() int { maximum := -1 for _, s := range b.servers { if s.weight > maximum { maximum = s.weight } } return maximum } func (b *WRRLoadBalancer) weightGcd() int { divisor := -1 for _, s := range b.servers { if divisor == -1 { divisor = s.weight } else { divisor = gcd(divisor, s.weight) } } return divisor } func gcd(a, b int) int { for b != 0 { a, b = b, a%b } return a }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/proxy_test.go
pkg/tcp/proxy_test.go
package tcp import ( "bytes" "io" "net" "testing" "time" "github.com/stretchr/testify/require" ) func TestCloseWrite(t *testing.T) { backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) go fakeServer(t, backendListener) _, port, err := net.SplitHostPort(backendListener.Addr().String()) require.NoError(t, err) dialer := tcpDialer{&net.Dialer{}, 10 * time.Millisecond, nil} proxy, err := NewProxy(":"+port, dialer) require.NoError(t, err) proxyListener, err := net.Listen("tcp", ":0") require.NoError(t, err) go func() { for { conn, err := proxyListener.Accept() require.NoError(t, err) proxy.ServeTCP(conn.(*net.TCPConn)) } }() _, port, err = net.SplitHostPort(proxyListener.Addr().String()) require.NoError(t, err) conn, err := net.Dial("tcp", ":"+port) require.NoError(t, err) _, err = conn.Write([]byte("ping\n")) require.NoError(t, err) err = conn.(*net.TCPConn).CloseWrite() require.NoError(t, err) var buf []byte buffer := bytes.NewBuffer(buf) n, err := io.Copy(buffer, conn) require.NoError(t, err) require.Equal(t, int64(4), n) require.Equal(t, "PONG", buffer.String()) } func fakeServer(t *testing.T, listener net.Listener) { t.Helper() for { conn, err := listener.Accept() require.NoError(t, err) for { withErr := false buf := make([]byte, 64) if _, err := conn.Read(buf); err != nil { withErr = true } if string(buf[:4]) == "ping" { time.Sleep(1 * time.Millisecond) if _, err := conn.Write([]byte("PONG")); err != nil { _ = conn.Close() return } } if withErr { _ = conn.Close() return } } } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/chain.go
pkg/tcp/chain.go
package tcp import ( "errors" ) // Constructor A constructor for a piece of TCP middleware. // Some TCP middleware use this constructor out of the box, // so in most cases you can just pass somepackage.New. type Constructor func(Handler) (Handler, error) // Chain is a chain for TCP handlers. // Chain acts as a list of tcp.Handler constructors. // Chain is effectively immutable: // once created, it will always hold // the same set of constructors in the same order. type Chain struct { constructors []Constructor } // NewChain creates a new TCP chain, // memorizing the given list of TCP middleware constructors. // New serves no other function, // constructors are only called upon a call to Then(). func NewChain(constructors ...Constructor) Chain { return Chain{constructors: constructors} } // Then adds an handler at the end of the chain. func (c Chain) Then(h Handler) (Handler, error) { if h == nil { return nil, errors.New("cannot add a nil handler to the chain") } for i := range c.constructors { handler, err := c.constructors[len(c.constructors)-1-i](h) if err != nil { return nil, err } h = handler } return h, nil } // Append extends a chain, adding the specified constructors // as the last ones in the request flow. // // Append returns a new chain, leaving the original one untouched. // // stdChain := tcp.NewChain(m1, m2) // extChain := stdChain.Append(m3, m4) // // requests in stdChain go m1 -> m2 // // requests in extChain go m1 -> m2 -> m3 -> m4 func (c Chain) Append(constructors ...Constructor) Chain { newCons := make([]Constructor, 0, len(c.constructors)+len(constructors)) newCons = append(newCons, c.constructors...) newCons = append(newCons, constructors...) return Chain{newCons} } // Extend extends a chain by adding the specified chain // as the last one in the request flow. // // Extend returns a new chain, leaving the original one untouched. // // stdChain := tcp.NewChain(m1, m2) // ext1Chain := tcp.NewChain(m3, m4) // ext2Chain := stdChain.Extend(ext1Chain) // // requests in stdChain go m1 -> m2 // // requests in ext1Chain go m3 -> m4 // // requests in ext2Chain go m1 -> m2 -> m3 -> m4 // // Another example: // // aHtmlAfterNosurf := tcp.NewChain(m2) // aHtml := tcp.NewChain(m1, func(h tcp.Handler) tcp.Handler { // csrf := nosurf.New(h) // csrf.SetFailureHandler(aHtmlAfterNosurf.ThenFunc(csrfFail)) // return csrf // }).Extend(aHtmlAfterNosurf) // // requests to aHtml hitting nosurfs success handler go m1 -> nosurf -> m2 -> target-handler // // requests to aHtml hitting nosurfs failure handler go m1 -> nosurf -> m2 -> csrfFail func (c Chain) Extend(chain Chain) Chain { return c.Append(chain.constructors...) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/dialer_test.go
pkg/tcp/dialer_test.go
package tcp import ( "bytes" "crypto/rand" "crypto/rsa" "crypto/tls" "crypto/x509" "crypto/x509/pkix" "errors" "io" "math/big" "net" "net/url" "testing" "time" "github.com/pires/go-proxyproto" "github.com/spiffe/go-spiffe/v2/bundle/x509bundle" "github.com/spiffe/go-spiffe/v2/spiffeid" "github.com/spiffe/go-spiffe/v2/spiffetls/tlsconfig" "github.com/spiffe/go-spiffe/v2/svid/x509svid" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" traefiktls "github.com/traefik/traefik/v3/pkg/tls" "github.com/traefik/traefik/v3/pkg/types" ) // LocalhostCert is a PEM-encoded TLS cert // for host example.com, www.example.com // expiring at Jan 29 16:00:00 2084 GMT. // go run $GOROOT/src/crypto/tls/generate_cert.go --rsa-bits 1024 --host example.com,www.example.com --ca --start-date "Jan 1 00:00:00 1970" --duration=1000000h var LocalhostCert = []byte(`-----BEGIN CERTIFICATE----- MIICDDCCAXWgAwIBAgIQH20JmcOlcRWHNuf62SYwszANBgkqhkiG9w0BAQsFADAS MRAwDgYDVQQKEwdBY21lIENvMCAXDTcwMDEwMTAwMDAwMFoYDzIwODQwMTI5MTYw MDAwWjASMRAwDgYDVQQKEwdBY21lIENvMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCB iQKBgQC0qINy3F4oq6viDnlpDDE5J08iSRGggg6EylJKBKZfphEG2ufgK78Dufl3 +7b0LlEY2AeZHwviHODqC9a6ihj1ZYQk0/djAh+OeOhFEWu+9T/VP8gVFarFqT8D Opy+hrG7YJivUIzwb4fmJQRI7FajzsnGyM6LiXLU+0qzb7ZO/QIDAQABo2EwXzAO BgNVHQ8BAf8EBAMCAqQwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDwYDVR0TAQH/BAUw AwEB/zAnBgNVHREEIDAeggtleGFtcGxlLmNvbYIPd3d3LmV4YW1wbGUuY29tMA0G CSqGSIb3DQEBCwUAA4GBAB+eluoQYzyyMfeEEAOtlldevx5MtDENT05NB0WI+91R we7mX8lv763u0XuCWPxbHszhclI6FFjoQef0Z1NYLRm8ZRq58QqWDFZ3E6wdDK+B +OWvkW+hRavo6R9LzIZPfbv8yBo4M9PK/DXw8hLqH7VkkI+Gh793iH7Ugd4A7wvT -----END CERTIFICATE-----`) // LocalhostKey is the private key for localhostCert. var LocalhostKey = []byte(`-----BEGIN PRIVATE KEY----- MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBALSog3LcXiirq+IO eWkMMTknTyJJEaCCDoTKUkoEpl+mEQba5+ArvwO5+Xf7tvQuURjYB5kfC+Ic4OoL 1rqKGPVlhCTT92MCH4546EURa771P9U/yBUVqsWpPwM6nL6GsbtgmK9QjPBvh+Yl BEjsVqPOycbIzouJctT7SrNvtk79AgMBAAECgYB1wMT1MBgbkFIXpXGTfAP1id61 rUTVBxCpkypx3ngHLjo46qRq5Hi72BN4FlTY8fugIudI8giP2FztkMvkiLDc4m0p Gn+QMJzjlBjjTuNLvLy4aSmNRLIC3mtbx9PdU71DQswEpJHFj/vmsxbuSrG1I1YE r1reuSo2ow6fOAjXLQJBANpz+RkOiPSPuvl+gi1sp2pLuynUJVDVqWZi386YRpfg DiKCLpqwqYDkOozm/fwFALvwXKGmsyyL43HO8eI+2NsCQQDTtY32V+02GPecdsyq msK06EPVTSaYwj9Mm+q709KsmYFHLXDqXjcKV4UgKYKRPz7my1fXodMmGmfuh1a3 /HMHAkEAmOQKN0tA90mRJwUvvvMIyRBv0fq0kzq28P3KfiF9ZtZdjjFmxMVYHOmf QPZ6VGR7+w1jB5BQXqEZcpHQIPSzeQJBAIy9tZJ/AYNlNbcegxEnsSjy/6VdlLsY 51vWi0Yym2uC4R6gZuBnoc+OP0ISVmqY0Qg9RjhjrCs4gr9f2ZaWjSECQCxqZMq1 3viJ8BGCC0m/5jv1EHur3YgwphYCkf4Li6DKwIdMLk1WXkTcPIY3V2Jqj8rPEB5V rqPRSAtd/h6oZbs= -----END PRIVATE KEY-----`) // openssl req -newkey rsa:2048 \ // -new -nodes -x509 \ // -days 3650 \ // -out cert.pem \ // -keyout key.pem \ // -subj "/CN=example.com" // -addext "subjectAltName = DNS:example.com" var mTLSCert = []byte(`-----BEGIN CERTIFICATE----- MIIDJTCCAg2gAwIBAgIUYKnGcLnmMosOSKqTn4ydAMURE4gwDQYJKoZIhvcNAQEL BQAwFjEUMBIGA1UEAwwLZXhhbXBsZS5jb20wHhcNMjAwODEzMDkyNzIwWhcNMzAw ODExMDkyNzIwWjAWMRQwEgYDVQQDDAtleGFtcGxlLmNvbTCCASIwDQYJKoZIhvcN AQEBBQADggEPADCCAQoCggEBAOAe+QM1c9lZ2TPRgoiuPAq2A3Pfu+i82lmqrTJ0 PR2Cx1fPbccCUTFJPlxSDiaMrwtvqw1yP9L2Pu/vJK5BY4YDVDtFGKjpRBau1otJ iY50O5qMo3sfLqR4/1VsQGlLVZYLD3dyc4ZTmOp8+7tJ2SyGorojbIKfimZT7XD7 dzrVr4h4Gn+SzzOnoKyx29uaNRP+XuMYHmHyQcJE03pUGhkTOvMwBlF96QdQ9WG0 D+1CxRciEsZXE+imKBHoaTgrTkpnFHzsrIEw+OHQYf30zuT/k/lkgv1vqEwINHjz W2VeTur5eqVvA7zZdoEXMRy7BUvh/nZk5AXkXAmZLn0eUg8CAwEAAaNrMGkwHQYD VR0OBBYEFEDrbhPDt+hi3ZOzk6S/CFAVHwk0MB8GA1UdIwQYMBaAFEDrbhPDt+hi 3ZOzk6S/CFAVHwk0MA8GA1UdEwEB/wQFMAMBAf8wFgYDVR0RBA8wDYILZXhhbXBs ZS5jb20wDQYJKoZIhvcNAQELBQADggEBAG/JRJWeUNx2mDJAk8W7Syq3gmQB7s9f +yY/XVRJZGahOPilABqFpC6GVn2HWuvuOqy8/RGk9ja5abKVXqE6YKrljqo3XfzB KQcOz4SFirpkHvNCiEcK3kggN3wJWqL2QyXAxWldBBBCO9yx7a3cux31C//sTUOG xq4JZDg171U1UOpfN1t0BFMdt05XZFEM247N7Dcf7HoXwAa7eyLKgtKWqPDqGrFa fvGDDKK9X/KVsU2x9V3pG+LsJg7ogUnSyD2r5G1F3Y8OVs2T/783PaN0M35fDL38 09VbsxA2GasOHZrghUzT4UvZWWZbWEmG975hFYvdj6DlK9K0s5TdKIs= -----END CERTIFICATE-----`) var mTLSKey = []byte(`-----BEGIN PRIVATE KEY----- MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDgHvkDNXPZWdkz 0YKIrjwKtgNz37vovNpZqq0ydD0dgsdXz23HAlExST5cUg4mjK8Lb6sNcj/S9j7v 7ySuQWOGA1Q7RRio6UQWrtaLSYmOdDuajKN7Hy6keP9VbEBpS1WWCw93cnOGU5jq fPu7SdkshqK6I2yCn4pmU+1w+3c61a+IeBp/ks8zp6CssdvbmjUT/l7jGB5h8kHC RNN6VBoZEzrzMAZRfekHUPVhtA/tQsUXIhLGVxPopigR6Gk4K05KZxR87KyBMPjh 0GH99M7k/5P5ZIL9b6hMCDR481tlXk7q+XqlbwO82XaBFzEcuwVL4f52ZOQF5FwJ mS59HlIPAgMBAAECggEAAKLV3hZ2v7UrkqQTlMO50+X0WI3YAK8Yh4yedTgzPDQ0 0KD8FMaC6HrmvGhXNfDMRmIIwD8Ew1qDjzbEieIRoD2+LXTivwf6c34HidmplEfs K2IezKin/zuArgNio2ndUlGxt4sRnN373x5/sGZjQWcYayLSmgRN5kByuhFco0Qa oSrXcXNUlb+KgRQXPDU4+M35tPHvLdyg+tko/m/5uK9dc9MNvGZHOMBKg0VNURJb V1l3dR+evwvpqHzBvWiqN/YOiUUvIxlFKA35hJkfCl7ivFs4CLqqFNCKDao95fWe s0UR9iMakT48jXV76IfwZnyX10OhIWzKls5trjDL8QKBgQD3thQJ8e0FL9y1W+Ph mCdEaoffSPkgSn64wIsQ9bMmv4y+KYBK5AhqaHgYm4LgW4x1+CURNFu+YFEyaNNA kNCXFyRX3Em3vxcShP5jIqg+f07mtXPKntWP/zBeKQWgdHX371oFTfaAlNuKX/7S n0jBYjr4Iof1bnquMQvUoHCYWwKBgQDnntFU9/AQGaQIvhfeU1XKFkQ/BfhIsd27 RlmiCi0ee9Ce74cMAhWr/9yg0XUxzrh+Ui1xnkMVTZ5P8tWIxROokznLUTGJA5rs zB+ovCPFZcquTwNzn7SBnpHTR0OqJd8sd89P5ST2SqufeSF/gGi5sTs4EocOLCpZ EPVIfm47XQKBgB4d5RHQeCDJUOw739jtxthqm1pqZN+oLwAHaOEG/mEXqOT15sM0 NlG5oeBcB+1/M/Sj1t3gn8blrvmSBR00fifgiGqmPdA5S3TU9pjW/d2bXNxv80QP S6fWPusz0ZtQjYc3cppygCXh808/nJu/AfmBF+pTSHRumjvTery/RPFBAoGBAMi/ zCta4cTylEvHhqR5kiefePMu120aTFYeuV1KeKStJ7o5XNE5lVMIZk80e+D5jMpf q2eIhhgWuBoPHKh4N3uqbzMbYlWgvEx09xOmTVKv0SWW8iTqzOZza2y1nZ4BSRcf mJ1ku86EFZAYysHZp+saA3usA0ZzXRjpK87zVdM5AoGBAOSqI+t48PnPtaUDFdpd taNNVDbcecJatm3w8VDWnarahfWe66FIqc9wUkqekqAgwZLa0AGdUalvXfGrHfNs PtvuNc5EImfSkuPBYLBslNxtjbBvAYgacEdY+gRhn2TeIUApnND58lCWsKbNHLFZ ajIPbTY+Fe9OTOFTN48ujXNn -----END PRIVATE KEY-----`) func TestConflictingConfig(t *testing.T) { dialerManager := NewDialerManager(nil) dynamicConf := map[string]*dynamic.TCPServersTransport{ "test": { TLS: &dynamic.TLSClientConfig{ ServerName: "foobar", Spiffe: &dynamic.Spiffe{}, }, }, } dialerManager.Update(dynamicConf) _, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{ServersTransport: "test"}, false) require.Error(t, err) } func TestNoTLS(t *testing.T) { backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) defer backendListener.Close() go fakeServer(t, backendListener) _, port, err := net.SplitHostPort(backendListener.Addr().String()) require.NoError(t, err) dialerManager := NewDialerManager(nil) dynamicConf := map[string]*dynamic.TCPServersTransport{ "test": { TLS: &dynamic.TLSClientConfig{}, }, } dialerManager.Update(dynamicConf) dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{ServersTransport: "test"}, false) require.NoError(t, err) conn, err := dialer.Dial("tcp", ":"+port, nil) require.NoError(t, err) _, err = conn.Write([]byte("ping\n")) require.NoError(t, err) buf := make([]byte, 64) n, err := conn.Read(buf) require.NoError(t, err) assert.Equal(t, 4, n) assert.Equal(t, "PONG", string(buf[:4])) err = conn.Close() require.NoError(t, err) } func TestTLS(t *testing.T) { cert, err := tls.X509KeyPair(LocalhostCert, LocalhostKey) require.NoError(t, err) backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) defer backendListener.Close() tlsListener := tls.NewListener(backendListener, &tls.Config{Certificates: []tls.Certificate{cert}}) defer tlsListener.Close() go fakeServer(t, tlsListener) _, port, err := net.SplitHostPort(tlsListener.Addr().String()) require.NoError(t, err) dialerManager := NewDialerManager(nil) dynamicConf := map[string]*dynamic.TCPServersTransport{ "test": { TLS: &dynamic.TLSClientConfig{ ServerName: "example.com", RootCAs: []types.FileOrContent{types.FileOrContent(LocalhostCert)}, }, }, } dialerManager.Update(dynamicConf) dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{ServersTransport: "test"}, true) require.NoError(t, err) conn, err := dialer.Dial("tcp", ":"+port, nil) require.NoError(t, err) _, err = conn.Write([]byte("ping\n")) require.NoError(t, err) err = conn.(*tls.Conn).CloseWrite() require.NoError(t, err) var buf []byte buffer := bytes.NewBuffer(buf) n, err := io.Copy(buffer, conn) require.NoError(t, err) assert.Equal(t, int64(4), n) assert.Equal(t, "PONG", buffer.String()) } func TestTLSWithInsecureSkipVerify(t *testing.T) { cert, err := tls.X509KeyPair(LocalhostCert, LocalhostKey) require.NoError(t, err) backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) defer backendListener.Close() tlsListener := tls.NewListener(backendListener, &tls.Config{Certificates: []tls.Certificate{cert}}) defer tlsListener.Close() go fakeServer(t, tlsListener) _, port, err := net.SplitHostPort(tlsListener.Addr().String()) require.NoError(t, err) dialerManager := NewDialerManager(nil) dynamicConf := map[string]*dynamic.TCPServersTransport{ "test": { TLS: &dynamic.TLSClientConfig{ ServerName: "bad-domain.com", RootCAs: []types.FileOrContent{types.FileOrContent(LocalhostCert)}, InsecureSkipVerify: true, }, }, } dialerManager.Update(dynamicConf) dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{ServersTransport: "test"}, true) require.NoError(t, err) conn, err := dialer.Dial("tcp", ":"+port, nil) require.NoError(t, err) _, err = conn.Write([]byte("ping\n")) require.NoError(t, err) err = conn.(*tls.Conn).CloseWrite() require.NoError(t, err) var buf []byte buffer := bytes.NewBuffer(buf) n, err := io.Copy(buffer, conn) require.NoError(t, err) assert.Equal(t, int64(4), n) assert.Equal(t, "PONG", buffer.String()) } func TestMTLS(t *testing.T) { cert, err := tls.X509KeyPair(LocalhostCert, LocalhostKey) require.NoError(t, err) clientPool := x509.NewCertPool() clientPool.AppendCertsFromPEM(mTLSCert) backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) defer backendListener.Close() tlsListener := tls.NewListener(backendListener, &tls.Config{ // For TLS Certificates: []tls.Certificate{cert}, // For mTLS ClientAuth: tls.RequireAndVerifyClientCert, ClientCAs: clientPool, }) defer tlsListener.Close() go fakeServer(t, tlsListener) _, port, err := net.SplitHostPort(tlsListener.Addr().String()) require.NoError(t, err) dialerManager := NewDialerManager(nil) dynamicConf := map[string]*dynamic.TCPServersTransport{ "test": { TLS: &dynamic.TLSClientConfig{ ServerName: "example.com", // For TLS RootCAs: []types.FileOrContent{types.FileOrContent(LocalhostCert)}, // For mTLS Certificates: traefiktls.Certificates{ traefiktls.Certificate{ CertFile: types.FileOrContent(mTLSCert), KeyFile: types.FileOrContent(mTLSKey), }, }, }, }, } dialerManager.Update(dynamicConf) dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{ServersTransport: "test"}, true) require.NoError(t, err) conn, err := dialer.Dial("tcp", ":"+port, nil) require.NoError(t, err) _, err = conn.Write([]byte("ping\n")) require.NoError(t, err) err = conn.(*tls.Conn).CloseWrite() require.NoError(t, err) var buf []byte buffer := bytes.NewBuffer(buf) n, err := io.Copy(buffer, conn) require.NoError(t, err) assert.Equal(t, int64(4), n) assert.Equal(t, "PONG", buffer.String()) } func TestSpiffeMTLS(t *testing.T) { backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) defer backendListener.Close() trustDomain := spiffeid.RequireTrustDomainFromString("spiffe://traefik.test") pki := newFakeSpiffePKI(t, trustDomain) serverSVID := pki.genSVID(t, spiffeid.RequireFromPath(trustDomain, "/server")) require.NoError(t, err) serverSource := fakeSpiffeSource{ svid: serverSVID, bundle: pki.bundle, } // go-spiffe's `tlsconfig.MTLSServerConfig` (that should be used here) does not set a certificate on // the returned `tls.Config` and relies instead on `GetCertificate` being always called. // But it turns out that `StartTLS` from `httptest.Server`, enforces a default certificate // if no certificate is previously set on the configured TLS config. // It makes the test server always serve the httptest default certificate, and not the SPIFFE certificate, // as GetCertificate is in that case never called (there's a default cert, and SNI is not used). // To bypass this issue, we're manually extracting the server ceritificate from the server SVID // and use another initialization method that forces serving the server SPIFFE certificate. serverCert, err := tlsconfig.GetCertificate(&serverSource)(nil) require.NoError(t, err) tlsListener := tls.NewListener(backendListener, tlsconfig.MTLSWebServerConfig( serverCert, &serverSource, tlsconfig.AuthorizeAny(), )) defer tlsListener.Close() _, port, err := net.SplitHostPort(tlsListener.Addr().String()) require.NoError(t, err) clientSVID := pki.genSVID(t, spiffeid.RequireFromPath(trustDomain, "/client")) clientSource := fakeSpiffeSource{ svid: clientSVID, bundle: pki.bundle, } testCases := []struct { desc string config dynamic.Spiffe clientSource SpiffeX509Source wantError bool }{ { desc: "supports SPIFFE mTLS", config: dynamic.Spiffe{}, clientSource: &clientSource, }, { desc: "allows expected server SPIFFE ID", config: dynamic.Spiffe{ IDs: []string{"spiffe://traefik.test/server"}, }, clientSource: &clientSource, }, { desc: "blocks unexpected server SPIFFE ID", config: dynamic.Spiffe{ IDs: []string{"spiffe://traefik.test/not-server"}, }, clientSource: &clientSource, wantError: true, }, { desc: "allows expected server trust domain", config: dynamic.Spiffe{ TrustDomain: "spiffe://traefik.test", }, clientSource: &clientSource, }, { desc: "denies unexpected server trust domain", config: dynamic.Spiffe{ TrustDomain: "spiffe://not-traefik.test", }, clientSource: &clientSource, wantError: true, }, { desc: "spiffe IDs allowlist takes precedence", config: dynamic.Spiffe{ IDs: []string{"spiffe://traefik.test/not-server"}, TrustDomain: "spiffe://not-traefik.test", }, clientSource: &clientSource, wantError: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { go fakeServer(t, tlsListener) dialerManager := NewDialerManager(test.clientSource) dynamicConf := map[string]*dynamic.TCPServersTransport{ "test": { TLS: &dynamic.TLSClientConfig{ Spiffe: &test.config, }, }, } dialerManager.Update(dynamicConf) dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{ServersTransport: "test"}, true) require.NoError(t, err) conn, err := dialer.Dial("tcp", ":"+port, nil) if test.wantError { require.Error(t, err) return } require.NoError(t, err) _, err = conn.Write([]byte("ping\n")) require.NoError(t, err) err = conn.(*tls.Conn).CloseWrite() require.NoError(t, err) var buf []byte buffer := bytes.NewBuffer(buf) n, err := io.Copy(buffer, conn) require.NoError(t, err) assert.Equal(t, int64(4), n) assert.Equal(t, "PONG", buffer.String()) }) } } func TestProxyProtocol(t *testing.T) { testCases := []struct { desc string version int }{ { desc: "proxy protocol v1", version: 1, }, { desc: "proxy protocol v2", version: 2, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) var version int var localAddr, remoteAddr string proxyBackendListener := proxyproto.Listener{ Listener: backendListener, ValidateHeader: func(h *proxyproto.Header) error { version = int(h.Version) localAddr = h.DestinationAddr.String() remoteAddr = h.SourceAddr.String() return nil }, Policy: func(upstream net.Addr) (proxyproto.Policy, error) { switch test.version { case 1, 2: return proxyproto.USE, nil default: return proxyproto.REQUIRE, errors.New("unsupported version") } }, } defer proxyBackendListener.Close() go fakeServer(t, &proxyBackendListener) _, port, err := net.SplitHostPort(backendListener.Addr().String()) require.NoError(t, err) dialerManager := NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{ "test": { ProxyProtocol: &dynamic.ProxyProtocol{ Version: test.version, }, }, }) dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{ServersTransport: "test"}, false) require.NoError(t, err) clientConn := &fakeClientConn{ localAddr: &net.TCPAddr{ IP: net.ParseIP("2.2.2.2"), Port: 12345, }, remoteAddr: &net.TCPAddr{ IP: net.ParseIP("1.1.1.1"), Port: 12345, }, } conn, err := dialer.Dial("tcp", ":"+port, clientConn) require.NoError(t, err) defer conn.Close() _, err = conn.Write([]byte("ping")) require.NoError(t, err) buf := make([]byte, 64) n, err := conn.Read(buf) require.NoError(t, err) assert.Equal(t, 4, n) assert.Equal(t, "PONG", string(buf[:4])) assert.Equal(t, test.version, version) assert.Equal(t, "2.2.2.2:12345", localAddr) assert.Equal(t, "1.1.1.1:12345", remoteAddr) }) } } func TestProxyProtocolWithTLS(t *testing.T) { testCases := []struct { desc string version int }{ { desc: "proxy protocol v1", version: 1, }, { desc: "proxy protocol v2", version: 2, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { cert, err := tls.X509KeyPair(LocalhostCert, LocalhostKey) require.NoError(t, err) backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) var version int var localAddr, remoteAddr string proxyBackendListener := proxyproto.Listener{ Listener: backendListener, ValidateHeader: func(h *proxyproto.Header) error { version = int(h.Version) localAddr = h.DestinationAddr.String() remoteAddr = h.SourceAddr.String() return nil }, Policy: func(upstream net.Addr) (proxyproto.Policy, error) { switch test.version { case 1, 2: return proxyproto.USE, nil default: return proxyproto.REQUIRE, errors.New("unsupported version") } }, } defer proxyBackendListener.Close() go func() { conn, err := proxyBackendListener.Accept() require.NoError(t, err) defer conn.Close() // Now wrap with TLS and perform handshake tlsConn := tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{cert}}) defer tlsConn.Close() err = tlsConn.Handshake() require.NoError(t, err) buf := make([]byte, 64) n, err := tlsConn.Read(buf) require.NoError(t, err) if bytes.Equal(buf[:n], []byte("ping")) { _, _ = tlsConn.Write([]byte("PONG")) } }() _, port, err := net.SplitHostPort(backendListener.Addr().String()) require.NoError(t, err) dialerManager := NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{ "test": { TLS: &dynamic.TLSClientConfig{ ServerName: "example.com", RootCAs: []types.FileOrContent{types.FileOrContent(LocalhostCert)}, InsecureSkipVerify: true, }, ProxyProtocol: &dynamic.ProxyProtocol{ Version: test.version, }, }, }) dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{ ServersTransport: "test", }, true) require.NoError(t, err) clientConn := &fakeClientConn{ localAddr: &net.TCPAddr{ IP: net.ParseIP("2.2.2.2"), Port: 12345, }, remoteAddr: &net.TCPAddr{ IP: net.ParseIP("1.1.1.1"), Port: 12345, }, } conn, err := dialer.Dial("tcp", ":"+port, clientConn) require.NoError(t, err) defer conn.Close() _, err = conn.Write([]byte("ping")) require.NoError(t, err) buf := make([]byte, 64) n, err := conn.Read(buf) require.NoError(t, err) assert.Equal(t, 4, n) assert.Equal(t, "PONG", string(buf[:4])) assert.Equal(t, test.version, version) assert.Equal(t, "2.2.2.2:12345", localAddr) assert.Equal(t, "1.1.1.1:12345", remoteAddr) }) } } func TestProxyProtocolDisabled(t *testing.T) { backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) defer backendListener.Close() go func() { conn, err := backendListener.Accept() require.NoError(t, err) defer conn.Close() buf := make([]byte, 64) n, err := conn.Read(buf) require.NoError(t, err) if bytes.Equal(buf[:n], []byte("ping")) { _, _ = conn.Write([]byte("PONG")) } }() _, port, err := net.SplitHostPort(backendListener.Addr().String()) require.NoError(t, err) // No proxy protocol configuration. dialerManager := NewDialerManager(nil) dialerManager.Update(map[string]*dynamic.TCPServersTransport{ "test": {}, }) dialer, err := dialerManager.Build(&dynamic.TCPServersLoadBalancer{ServersTransport: "test"}, false) require.NoError(t, err) conn, err := dialer.Dial("tcp", ":"+port, nil) require.NoError(t, err) _, err = conn.Write([]byte("ping")) require.NoError(t, err) buf := make([]byte, 64) n, err := conn.Read(buf) require.NoError(t, err) assert.Equal(t, 4, n) assert.Equal(t, "PONG", string(buf[:4])) } type fakeClientConn struct { remoteAddr *net.TCPAddr localAddr *net.TCPAddr } func (f fakeClientConn) LocalAddr() net.Addr { return f.localAddr } func (f fakeClientConn) RemoteAddr() net.Addr { return f.remoteAddr } // fakeSpiffePKI simulates a SPIFFE aware PKI and allows generating multiple valid SVIDs. type fakeSpiffePKI struct { caPrivateKey *rsa.PrivateKey bundle *x509bundle.Bundle } func newFakeSpiffePKI(t *testing.T, trustDomain spiffeid.TrustDomain) fakeSpiffePKI { t.Helper() caPrivateKey, err := rsa.GenerateKey(rand.Reader, 2048) require.NoError(t, err) caTemplate := x509.Certificate{ SerialNumber: big.NewInt(2000), Subject: pkix.Name{ Organization: []string{"spiffe"}, }, URIs: []*url.URL{spiffeid.RequireFromPath(trustDomain, "/ca").URL()}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), SubjectKeyId: []byte("ca"), KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, BasicConstraintsValid: true, IsCA: true, PublicKey: caPrivateKey.Public(), } caCertDER, err := x509.CreateCertificate( rand.Reader, &caTemplate, &caTemplate, caPrivateKey.Public(), caPrivateKey, ) require.NoError(t, err) bundle, err := x509bundle.ParseRaw( trustDomain, caCertDER, ) require.NoError(t, err) return fakeSpiffePKI{ bundle: bundle, caPrivateKey: caPrivateKey, } } func (f *fakeSpiffePKI) genSVID(t *testing.T, id spiffeid.ID) *x509svid.SVID { t.Helper() privateKey, err := rsa.GenerateKey(rand.Reader, 2048) require.NoError(t, err) template := x509.Certificate{ SerialNumber: big.NewInt(200001), URIs: []*url.URL{id.URL()}, NotBefore: time.Now(), NotAfter: time.Now().Add(time.Hour), SubjectKeyId: []byte("svid"), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{ x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth, }, BasicConstraintsValid: true, PublicKey: privateKey.PublicKey, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, } certDER, err := x509.CreateCertificate( rand.Reader, &template, f.bundle.X509Authorities()[0], privateKey.Public(), f.caPrivateKey, ) require.NoError(t, err) keyPKCS8, err := x509.MarshalPKCS8PrivateKey(privateKey) require.NoError(t, err) svid, err := x509svid.ParseRaw(certDER, keyPKCS8) require.NoError(t, err) return svid } // fakeSpiffeSource allows retrieving statically an SVID and its associated bundle. type fakeSpiffeSource struct { bundle *x509bundle.Bundle svid *x509svid.SVID } func (s *fakeSpiffeSource) GetX509BundleForTrustDomain(trustDomain spiffeid.TrustDomain) (*x509bundle.Bundle, error) { return s.bundle, nil } func (s *fakeSpiffeSource) GetX509SVID() (*x509svid.SVID, error) { return s.svid, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/handler.go
pkg/tcp/handler.go
package tcp import ( "net" ) // Handler is the TCP Handlers interface. type Handler interface { ServeTCP(conn WriteCloser) } // The HandlerFunc type is an adapter to allow the use of // ordinary functions as handlers. type HandlerFunc func(conn WriteCloser) // ServeTCP serves tcp. func (f HandlerFunc) ServeTCP(conn WriteCloser) { f(conn) } // WriteCloser describes a net.Conn with a CloseWrite method. type WriteCloser interface { net.Conn // CloseWrite on a network connection, indicates that the issuer of the call // has terminated sending on that connection. // It corresponds to sending a FIN packet. CloseWrite() error }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/wrr_load_balancer_test.go
pkg/tcp/wrr_load_balancer_test.go
package tcp import ( "net" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestWRRLoadBalancer_LoadBalancing(t *testing.T) { testCases := []struct { desc string serversWeight map[string]int totalCall int expectedWrite map[string]int expectedClose int }{ { desc: "RoundRobin", serversWeight: map[string]int{ "h1": 1, "h2": 1, }, totalCall: 4, expectedWrite: map[string]int{ "h1": 2, "h2": 2, }, }, { desc: "WeighedRoundRobin", serversWeight: map[string]int{ "h1": 3, "h2": 1, }, totalCall: 4, expectedWrite: map[string]int{ "h1": 3, "h2": 1, }, }, { desc: "WeighedRoundRobin with more call", serversWeight: map[string]int{ "h1": 3, "h2": 1, }, totalCall: 16, expectedWrite: map[string]int{ "h1": 12, "h2": 4, }, }, { desc: "WeighedRoundRobin with one 0 weight server", serversWeight: map[string]int{ "h1": 3, "h2": 0, }, totalCall: 16, expectedWrite: map[string]int{ "h1": 16, }, }, { desc: "WeighedRoundRobin with all servers with 0 weight", serversWeight: map[string]int{ "h1": 0, "h2": 0, "h3": 0, }, totalCall: 10, expectedWrite: map[string]int{}, expectedClose: 10, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() balancer := NewWRRLoadBalancer(false) for server, weight := range test.serversWeight { balancer.Add(server, HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte(server)) require.NoError(t, err) }), &weight) } conn := &fakeConn{writeCall: make(map[string]int)} for range test.totalCall { balancer.ServeTCP(conn) } assert.Equal(t, test.expectedWrite, conn.writeCall) assert.Equal(t, test.expectedClose, conn.closeCall) }) } } func TestWRRLoadBalancer_NoServiceUp(t *testing.T) { balancer := NewWRRLoadBalancer(false) balancer.Add("first", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("first")) require.NoError(t, err) }), pointer(1)) balancer.Add("second", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("second")) require.NoError(t, err) }), pointer(1)) balancer.SetStatus(t.Context(), "first", false) balancer.SetStatus(t.Context(), "second", false) conn := &fakeConn{writeCall: make(map[string]int)} balancer.ServeTCP(conn) assert.Empty(t, conn.writeCall) assert.Equal(t, 1, conn.closeCall) } func TestWRRLoadBalancer_OneServerDown(t *testing.T) { balancer := NewWRRLoadBalancer(false) balancer.Add("first", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("first")) require.NoError(t, err) }), pointer(1)) balancer.Add("second", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("second")) require.NoError(t, err) }), pointer(1)) balancer.SetStatus(t.Context(), "second", false) conn := &fakeConn{writeCall: make(map[string]int)} for range 3 { balancer.ServeTCP(conn) } assert.Equal(t, 3, conn.writeCall["first"]) } func TestWRRLoadBalancer_DownThenUp(t *testing.T) { balancer := NewWRRLoadBalancer(false) balancer.Add("first", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("first")) require.NoError(t, err) }), pointer(1)) balancer.Add("second", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("second")) require.NoError(t, err) }), pointer(1)) balancer.SetStatus(t.Context(), "second", false) conn := &fakeConn{writeCall: make(map[string]int)} for range 3 { balancer.ServeTCP(conn) } assert.Equal(t, 3, conn.writeCall["first"]) balancer.SetStatus(t.Context(), "second", true) conn = &fakeConn{writeCall: make(map[string]int)} for range 2 { balancer.ServeTCP(conn) } assert.Equal(t, 1, conn.writeCall["first"]) assert.Equal(t, 1, conn.writeCall["second"]) } func TestWRRLoadBalancer_Propagate(t *testing.T) { balancer1 := NewWRRLoadBalancer(true) balancer1.Add("first", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("first")) require.NoError(t, err) }), pointer(1)) balancer1.Add("second", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("second")) require.NoError(t, err) }), pointer(1)) balancer2 := NewWRRLoadBalancer(true) balancer2.Add("third", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("third")) require.NoError(t, err) }), pointer(1)) balancer2.Add("fourth", HandlerFunc(func(conn WriteCloser) { _, err := conn.Write([]byte("fourth")) require.NoError(t, err) }), pointer(1)) topBalancer := NewWRRLoadBalancer(true) topBalancer.Add("balancer1", balancer1, pointer(1)) _ = balancer1.RegisterStatusUpdater(func(up bool) { topBalancer.SetStatus(t.Context(), "balancer1", up) }) topBalancer.Add("balancer2", balancer2, pointer(1)) _ = balancer2.RegisterStatusUpdater(func(up bool) { topBalancer.SetStatus(t.Context(), "balancer2", up) }) conn := &fakeConn{writeCall: make(map[string]int)} for range 8 { topBalancer.ServeTCP(conn) } assert.Equal(t, 2, conn.writeCall["first"]) assert.Equal(t, 2, conn.writeCall["second"]) assert.Equal(t, 2, conn.writeCall["third"]) assert.Equal(t, 2, conn.writeCall["fourth"]) // fourth gets downed, but balancer2 still up since third is still up. balancer2.SetStatus(t.Context(), "fourth", false) conn = &fakeConn{writeCall: make(map[string]int)} for range 8 { topBalancer.ServeTCP(conn) } assert.Equal(t, 2, conn.writeCall["first"]) assert.Equal(t, 2, conn.writeCall["second"]) assert.Equal(t, 4, conn.writeCall["third"]) assert.Equal(t, 0, conn.writeCall["fourth"]) // third gets downed, and the propagation triggers balancer2 to be marked as // down as well for topBalancer. balancer2.SetStatus(t.Context(), "third", false) conn = &fakeConn{writeCall: make(map[string]int)} for range 8 { topBalancer.ServeTCP(conn) } assert.Equal(t, 4, conn.writeCall["first"]) assert.Equal(t, 4, conn.writeCall["second"]) assert.Equal(t, 0, conn.writeCall["third"]) assert.Equal(t, 0, conn.writeCall["fourth"]) } func pointer[T any](v T) *T { return &v } type fakeConn struct { writeCall map[string]int closeCall int } func (f *fakeConn) Read(b []byte) (n int, err error) { panic("implement me") } func (f *fakeConn) Write(b []byte) (n int, err error) { f.writeCall[string(b)]++ return len(b), nil } func (f *fakeConn) Close() error { f.closeCall++ return nil } func (f *fakeConn) LocalAddr() net.Addr { panic("implement me") } func (f *fakeConn) RemoteAddr() net.Addr { panic("implement me") } func (f *fakeConn) SetDeadline(t time.Time) error { panic("implement me") } func (f *fakeConn) SetReadDeadline(t time.Time) error { panic("implement me") } func (f *fakeConn) SetWriteDeadline(t time.Time) error { panic("implement me") } func (f *fakeConn) CloseWrite() error { panic("implement me") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/proxy_windows.go
pkg/tcp/proxy_windows.go
//go:build windows // +build windows package tcp import ( "errors" "net" "syscall" ) // isReadConnResetError reports whether err is a connection reset error during a read operation. func isReadConnResetError(err error) bool { var oerr *net.OpError return errors.As(err, &oerr) && oerr.Op == "read" && errors.Is(err, syscall.WSAECONNRESET) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/tls.go
pkg/tcp/tls.go
package tcp import ( "crypto/tls" ) // TLSHandler handles TLS connections. type TLSHandler struct { Next Handler Config *tls.Config } // ServeTCP terminates the TLS connection. func (t *TLSHandler) ServeTCP(conn WriteCloser) { t.Next.ServeTCP(tls.Server(conn, t.Config)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/tcp/proxy_unix.go
pkg/tcp/proxy_unix.go
//go:build !windows // +build !windows package tcp import ( "errors" "net" "syscall" ) // isReadConnResetError reports whether err is a connection reset error during a read operation. func isReadConnResetError(err error) bool { var oerr *net.OpError return errors.As(err, &oerr) && oerr.Op == "read" && errors.Is(err, syscall.ECONNRESET) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/ping/ping.go
pkg/ping/ping.go
package ping import ( "context" "fmt" "net/http" ) // Handler expose ping routes. type Handler struct { EntryPoint string `description:"EntryPoint" json:"entryPoint,omitempty" toml:"entryPoint,omitempty" yaml:"entryPoint,omitempty" export:"true"` ManualRouting bool `description:"Manual routing" json:"manualRouting,omitempty" toml:"manualRouting,omitempty" yaml:"manualRouting,omitempty" export:"true"` TerminatingStatusCode int `description:"Terminating status code" json:"terminatingStatusCode,omitempty" toml:"terminatingStatusCode,omitempty" yaml:"terminatingStatusCode,omitempty" export:"true"` terminating bool } // SetDefaults sets the default values. func (h *Handler) SetDefaults() { h.EntryPoint = "traefik" h.TerminatingStatusCode = http.StatusServiceUnavailable } // WithContext causes the ping endpoint to serve non 200 responses. func (h *Handler) WithContext(ctx context.Context) { go func() { <-ctx.Done() h.terminating = true }() } func (h *Handler) ServeHTTP(response http.ResponseWriter, request *http.Request) { statusCode := http.StatusOK if h.terminating { statusCode = h.TerminatingStatusCode } response.WriteHeader(statusCode) fmt.Fprint(response, http.StatusText(statusCode)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/smart_builder.go
pkg/proxy/smart_builder.go
package proxy import ( "crypto/tls" "fmt" "net/http" "net/url" "time" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/proxy/fast" "github.com/traefik/traefik/v3/pkg/proxy/httputil" "github.com/traefik/traefik/v3/pkg/server/service" ) // TransportManager manages transport used for backend communications. type TransportManager interface { Get(name string) (*dynamic.ServersTransport, error) GetRoundTripper(name string) (http.RoundTripper, error) GetTLSConfig(name string) (*tls.Config, error) } // SmartBuilder is a proxy builder which returns a fast proxy or httputil proxy corresponding // to the ServersTransport configuration. type SmartBuilder struct { fastProxyBuilder *fast.ProxyBuilder proxyBuilder service.ProxyBuilder transportManager httputil.TransportManager } // NewSmartBuilder creates and returns a new SmartBuilder instance. func NewSmartBuilder(transportManager TransportManager, proxyBuilder service.ProxyBuilder, fastProxyConfig static.FastProxyConfig) *SmartBuilder { return &SmartBuilder{ fastProxyBuilder: fast.NewProxyBuilder(transportManager, fastProxyConfig), proxyBuilder: proxyBuilder, transportManager: transportManager, } } // Update is the handler called when the dynamic configuration is updated. func (b *SmartBuilder) Update(newConfigs map[string]*dynamic.ServersTransport) { b.fastProxyBuilder.Update(newConfigs) } // Build builds an HTTP proxy for the given URL using the ServersTransport with the given name. func (b *SmartBuilder) Build(configName string, targetURL *url.URL, passHostHeader, preservePath bool, flushInterval time.Duration) (http.Handler, error) { serversTransport, err := b.transportManager.Get(configName) if err != nil { return nil, fmt.Errorf("getting ServersTransport: %w", err) } // The fast proxy implementation cannot handle HTTP/2 requests for now. // For the https scheme we cannot guess if the backend communication will use HTTP2, // thus we check if HTTP/2 is disabled to use the fast proxy implementation when this is possible. if targetURL.Scheme == "h2c" || (targetURL.Scheme == "https" && !serversTransport.DisableHTTP2) { return b.proxyBuilder.Build(configName, targetURL, passHostHeader, preservePath, flushInterval) } return b.fastProxyBuilder.Build(configName, targetURL, passHostHeader, preservePath) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/smart_builder_test.go
pkg/proxy/smart_builder_test.go
package proxy import ( "encoding/pem" "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/static" "github.com/traefik/traefik/v3/pkg/proxy/httputil" "github.com/traefik/traefik/v3/pkg/server/service" "github.com/traefik/traefik/v3/pkg/testhelpers" "github.com/traefik/traefik/v3/pkg/types" "golang.org/x/net/http2" "golang.org/x/net/http2/h2c" ) func TestSmartBuilder_Build(t *testing.T) { tests := []struct { desc string serversTransport dynamic.ServersTransport fastProxyConfig static.FastProxyConfig https bool h2c bool wantFastProxy bool }{ { desc: "fastproxy", fastProxyConfig: static.FastProxyConfig{Debug: true}, wantFastProxy: true, }, { desc: "fastproxy with https and without DisableHTTP2", https: true, fastProxyConfig: static.FastProxyConfig{Debug: true}, wantFastProxy: false, }, { desc: "fastproxy with https and DisableHTTP2", https: true, serversTransport: dynamic.ServersTransport{DisableHTTP2: true}, fastProxyConfig: static.FastProxyConfig{Debug: true}, wantFastProxy: true, }, { desc: "fastproxy with h2c", h2c: true, fastProxyConfig: static.FastProxyConfig{Debug: true}, wantFastProxy: false, }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() var callCount int handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { callCount++ if test.wantFastProxy { assert.Contains(t, r.Header, "X-Traefik-Fast-Proxy") } else { assert.NotContains(t, r.Header, "X-Traefik-Fast-Proxy") } }) var server *httptest.Server if test.https { server = httptest.NewUnstartedServer(handler) server.EnableHTTP2 = false server.StartTLS() certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: server.TLS.Certificates[0].Certificate[0]}) test.serversTransport.RootCAs = []types.FileOrContent{ types.FileOrContent(certPEM), } } else { server = httptest.NewServer(h2c.NewHandler(handler, &http2.Server{})) } t.Cleanup(func() { server.Close() }) targetURL := testhelpers.MustParseURL(server.URL) if test.h2c { targetURL.Scheme = "h2c" } serversTransports := map[string]*dynamic.ServersTransport{ "test": &test.serversTransport, } transportManager := service.NewTransportManager(nil) transportManager.Update(serversTransports) httpProxyBuilder := httputil.NewProxyBuilder(transportManager, nil) proxyBuilder := NewSmartBuilder(transportManager, httpProxyBuilder, test.fastProxyConfig) proxyHandler, err := proxyBuilder.Build("test", targetURL, false, false, time.Second) require.NoError(t, err) rw := httptest.NewRecorder() proxyHandler.ServeHTTP(rw, httptest.NewRequest(http.MethodGet, "/", http.NoBody)) assert.Equal(t, 1, callCount) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/fast/connpool.go
pkg/proxy/fast/connpool.go
package fast import ( "bufio" "errors" "fmt" "io" "net" "net/http" "net/http/httputil" "strings" "sync" "sync/atomic" "time" "github.com/rs/zerolog/log" "github.com/valyala/fasthttp" ) // rwWithUpgrade contains a ResponseWriter and an upgradeHandler, // used to upgrade the connection (e.g. Websockets). type rwWithUpgrade struct { ReqMethod string RW http.ResponseWriter Upgrade upgradeHandler } // conn is an enriched net.Conn. type conn struct { net.Conn RWCh chan rwWithUpgrade ErrCh chan error br *bufio.Reader idleAt time.Time // the last time it was marked as idle. idleTimeout time.Duration responseHeaderTimeout time.Duration expectedResponse atomic.Bool broken atomic.Bool upgraded atomic.Bool closeMu sync.Mutex closed bool closeErr error bufferPool *pool[[]byte] limitedReaderPool *pool[*io.LimitedReader] } // Read reads data from the connection. // Overrides conn Read to use the buffered reader. func (c *conn) Read(b []byte) (n int, err error) { return c.br.Read(b) } // Close closes the connection. // Ensures that connection is closed only once, // to avoid duplicate close error. func (c *conn) Close() error { c.closeMu.Lock() defer c.closeMu.Unlock() if c.closed { return c.closeErr } c.closed = true c.closeErr = c.Conn.Close() return c.closeErr } // isStale returns whether the connection is in an invalid state (i.e. expired/broken). func (c *conn) isStale() bool { expTime := c.idleAt.Add(c.idleTimeout) return c.idleTimeout > 0 && time.Now().After(expTime) || c.broken.Load() } // isUpgraded returns whether this connection has been upgraded (e.g. Websocket). // An upgraded connection should not be reused and putted back in the connection pool. func (c *conn) isUpgraded() bool { return c.upgraded.Load() } // readLoop handles the successive HTTP response read operations on the connection, // and watches for unsolicited bytes or connection errors when idle. func (c *conn) readLoop() { defer c.Close() for { _, err := c.br.Peek(1) if err != nil { select { // An error occurred while a response was expected to be handled. case <-c.RWCh: c.ErrCh <- err // An error occurred on an idle connection. default: c.broken.Store(true) } return } // Unsolicited response received on an idle connection. if !c.expectedResponse.Load() { c.broken.Store(true) return } r := <-c.RWCh if err = c.handleResponse(r); err != nil { c.ErrCh <- err return } c.expectedResponse.Store(false) c.ErrCh <- nil } } func (c *conn) handleResponse(r rwWithUpgrade) error { res := fasthttp.AcquireResponse() defer fasthttp.ReleaseResponse(res) res.Header.SetNoDefaultContentType(true) for { var ( timer *time.Timer errTimeout atomic.Pointer[timeoutError] ) if c.responseHeaderTimeout > 0 { timer = time.AfterFunc(c.responseHeaderTimeout, func() { errTimeout.Store(&timeoutError{errors.New("timeout awaiting response headers")}) c.Close() // This close call is needed to interrupt the read operation below when the timeout is over. }) } res.Header.SetNoDefaultContentType(true) if err := res.Header.Read(c.br); err != nil { if c.responseHeaderTimeout > 0 { if errT := errTimeout.Load(); errT != nil { return errT } } return err } if timer != nil { timer.Stop() } fixPragmaCacheControl(&res.Header) resCode := res.StatusCode() is1xx := 100 <= resCode && resCode <= 199 // treat 101 as a terminal status, see issue 26161 is1xxNonTerminal := is1xx && resCode != http.StatusSwitchingProtocols if is1xxNonTerminal { removeConnectionHeaders(&res.Header) h := r.RW.Header() for _, header := range hopHeaders { res.Header.Del(header) } res.Header.VisitAll(func(key, value []byte) { r.RW.Header().Add(string(key), string(value)) }) r.RW.WriteHeader(res.StatusCode()) // Clear headers, it's not automatically done by ResponseWriter.WriteHeader() for 1xx responses for k := range h { delete(h, k) } res.Reset() res.Header.SetNoDefaultContentType(true) continue } break } announcedTrailers := res.Header.Peek("Trailer") // Deal with 101 Switching Protocols responses: (WebSocket, h2c, etc) if res.StatusCode() == http.StatusSwitchingProtocols { r.Upgrade(r.RW, res, c) c.upgraded.Store(true) // As the connection has been upgraded, it cannot be added back to the pool. return nil } removeConnectionHeaders(&res.Header) for _, header := range hopHeaders { res.Header.Del(header) } if len(announcedTrailers) > 0 { res.Header.Add("Trailer", string(announcedTrailers)) } res.Header.VisitAll(func(key, value []byte) { r.RW.Header().Add(string(key), string(value)) }) r.RW.WriteHeader(res.StatusCode()) if noResponseBodyExpected(r.ReqMethod) { return nil } // When a body is not allowed for a given status code the body is ignored. // The connection will be marked as broken by the next Peek in the readloop. if !isBodyAllowedForStatus(res.StatusCode()) { return nil } contentLength := res.Header.ContentLength() if contentLength == 0 { return nil } // Chunked response, Content-Length is set to -1 by FastProxy when "Transfer-Encoding: chunked" header is received. if contentLength == -1 { cbr := httputil.NewChunkedReader(c.br) b := c.bufferPool.Get() if b == nil { b = make([]byte, bufferSize) } defer c.bufferPool.Put(b) if _, err := io.CopyBuffer(&writeFlusher{r.RW}, cbr, b); err != nil { return err } res.Header.Reset() res.Header.SetNoDefaultContentType(true) if err := res.Header.ReadTrailer(c.br); err != nil { return err } if res.Header.Len() > 0 { var announcedTrailersKey []string if len(announcedTrailers) > 0 { announcedTrailersKey = strings.Split(string(announcedTrailers), ",") } res.Header.VisitAll(func(key, value []byte) { for _, s := range announcedTrailersKey { if strings.EqualFold(s, strings.TrimSpace(string(key))) { r.RW.Header().Add(string(key), string(value)) return } } r.RW.Header().Add(http.TrailerPrefix+string(key), string(value)) }) } return nil } // Response without Content-Length header. // The message body length is determined by the number of bytes received prior to the server closing the connection. if contentLength == -2 { b := c.bufferPool.Get() if b == nil { b = make([]byte, bufferSize) } defer c.bufferPool.Put(b) if _, err := io.CopyBuffer(r.RW, c.br, b); err != nil { return err } return nil } // Response with a valid Content-Length header. brl := c.limitedReaderPool.Get() if brl == nil { brl = &io.LimitedReader{} } defer c.limitedReaderPool.Put(brl) brl.R = c.br brl.N = int64(res.Header.ContentLength()) b := c.bufferPool.Get() if b == nil { b = make([]byte, bufferSize) } defer c.bufferPool.Put(b) if _, err := io.CopyBuffer(r.RW, brl, b); err != nil { return err } return nil } // connPool is a net.Conn pool implementation using channels. type connPool struct { dialer func() (net.Conn, error) idleConns chan *conn idleConnTimeout time.Duration responseHeaderTimeout time.Duration ticker *time.Ticker bufferPool pool[[]byte] limitedReaderPool pool[*io.LimitedReader] doneCh chan struct{} } // newConnPool creates a new connPool. func newConnPool(maxIdleConn int, idleConnTimeout, responseHeaderTimeout time.Duration, dialer func() (net.Conn, error)) *connPool { c := &connPool{ dialer: dialer, idleConns: make(chan *conn, maxIdleConn), idleConnTimeout: idleConnTimeout, responseHeaderTimeout: responseHeaderTimeout, doneCh: make(chan struct{}), } if idleConnTimeout > 0 { c.ticker = time.NewTicker(c.idleConnTimeout / 2) go func() { for { select { case <-c.ticker.C: c.cleanIdleConns() case <-c.doneCh: return } } }() } return c } // Close closes stop the cleanIdleConn goroutine. func (c *connPool) Close() { if c.idleConnTimeout > 0 { close(c.doneCh) c.ticker.Stop() } } // AcquireConn returns an idle net.Conn from the pool. func (c *connPool) AcquireConn() (*conn, error) { for { co, err := c.acquireConn() if err != nil { return nil, err } if !co.isStale() { return co, nil } // As the acquired conn is stale we can close it // without putting it again into the pool. if err := co.Close(); err != nil { log.Debug(). Err(err). Msg("Unexpected error while closing the connection") } } } // ReleaseConn releases the given net.Conn to the pool. func (c *connPool) ReleaseConn(co *conn) { // An upgraded connection cannot be safely reused for another roundTrip, // thus we are not putting it back to the pool. if co.isUpgraded() { return } co.idleAt = time.Now() c.releaseConn(co) } // cleanIdleConns is a routine cleaning the expired connections at a regular basis. func (c *connPool) cleanIdleConns() { for { select { case co := <-c.idleConns: if !co.isStale() { c.releaseConn(co) return } if err := co.Close(); err != nil { log.Debug(). Err(err). Msg("Unexpected error while closing the connection") } default: return } } } func (c *connPool) acquireConn() (*conn, error) { select { case co := <-c.idleConns: return co, nil default: errCh := make(chan error, 1) go c.askForNewConn(errCh) select { case co := <-c.idleConns: return co, nil case err := <-errCh: return nil, err } } } func (c *connPool) releaseConn(co *conn) { select { case c.idleConns <- co: // Hitting the default case means that we have reached the maximum number of idle // connections, so we can close it. default: if err := co.Close(); err != nil { log.Debug(). Err(err). Msg("Unexpected error while releasing the connection") } } } func (c *connPool) askForNewConn(errCh chan<- error) { co, err := c.dialer() if err != nil { errCh <- fmt.Errorf("create conn: %w", err) return } newConn := &conn{ Conn: co, br: bufio.NewReaderSize(co, bufioSize), idleAt: time.Now(), idleTimeout: c.idleConnTimeout, responseHeaderTimeout: c.responseHeaderTimeout, RWCh: make(chan rwWithUpgrade), ErrCh: make(chan error), bufferPool: &c.bufferPool, limitedReaderPool: &c.limitedReaderPool, } go newConn.readLoop() c.releaseConn(newConn) } // isBodyAllowedForStatus reports whether a given response status code permits a body. // See RFC 7230, section 3.3. // From https://github.com/golang/go/blame/master/src/net/http/transfer.go#L459 func isBodyAllowedForStatus(status int) bool { switch { case status >= 100 && status <= 199: return false case status == 204: return false case status == 304: return false } return true } // noResponseBodyExpected reports whether a given request method permits a body. // From https://github.com/golang/go/blame/master/src/net/http/transfer.go#L250 func noResponseBodyExpected(requestMethod string) bool { return requestMethod == "HEAD" }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/fast/proxy.go
pkg/proxy/fast/proxy.go
package fast import ( "bufio" "bytes" "encoding/base64" "fmt" "io" "net" "net/http" "net/http/httptrace" "net/url" "strings" "sync" "github.com/rs/zerolog/log" proxyhttputil "github.com/traefik/traefik/v3/pkg/proxy/httputil" "github.com/valyala/fasthttp" "golang.org/x/net/http/httpguts" ) const ( bufferSize = 32 * 1024 bufioSize = 64 * 1024 ) var hopHeaders = []string{ "Connection", "Proxy-Connection", // non-standard but still sent by libcurl and rejected by e.g. google "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", "Te", // canonicalized version of "TE" "Trailer", // not Trailers per URL above; https://www.rfc-editor.org/errata_search.php?eid=4522 "Transfer-Encoding", "Upgrade", } type pool[T any] struct { pool sync.Pool } func (p *pool[T]) Get() T { if tmp := p.pool.Get(); tmp != nil { return tmp.(T) } var res T return res } func (p *pool[T]) Put(x T) { p.pool.Put(x) } type writeDetector struct { net.Conn written bool } func (w *writeDetector) Write(p []byte) (int, error) { n, err := w.Conn.Write(p) if n > 0 { w.written = true } return n, err } type writeFlusher struct { io.Writer } func (w *writeFlusher) Write(b []byte) (int, error) { n, err := w.Writer.Write(b) if f, ok := w.Writer.(http.Flusher); ok { f.Flush() } return n, err } type timeoutError struct { error } func (t timeoutError) Timeout() bool { return true } func (t timeoutError) Temporary() bool { return false } // ReverseProxy is the FastProxy reverse proxy implementation. type ReverseProxy struct { debug bool connPool *connPool writerPool pool[*bufio.Writer] proxyAuth string targetURL *url.URL passHostHeader bool preservePath bool } // NewReverseProxy creates a new ReverseProxy. func NewReverseProxy(targetURL, proxyURL *url.URL, debug, passHostHeader, preservePath bool, connPool *connPool) (*ReverseProxy, error) { var proxyAuth string if proxyURL != nil && proxyURL.User != nil && targetURL.Scheme == "http" { username := proxyURL.User.Username() password, _ := proxyURL.User.Password() proxyAuth = "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password)) } return &ReverseProxy{ debug: debug, passHostHeader: passHostHeader, preservePath: preservePath, targetURL: targetURL, proxyAuth: proxyAuth, connPool: connPool, }, nil } func (p *ReverseProxy) ServeHTTP(rw http.ResponseWriter, req *http.Request) { if req.Body != nil { defer req.Body.Close() } outReq := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(outReq) // This is not required as the headers are already normalized by net/http. outReq.Header.DisableNormalizing() for k, v := range req.Header { for _, s := range v { outReq.Header.Add(k, s) } } removeConnectionHeaders(&outReq.Header) for _, header := range hopHeaders { outReq.Header.Del(header) } if p.proxyAuth != "" { outReq.Header.Set("Proxy-Authorization", p.proxyAuth) } if httpguts.HeaderValuesContainsToken(req.Header["Te"], "trailers") { outReq.Header.Set("Te", "trailers") } if p.debug { outReq.Header.Set("X-Traefik-Fast-Proxy", "enabled") } reqUpType := upgradeType(req.Header) if !isGraphic(reqUpType) { proxyhttputil.ErrorHandler(rw, req, fmt.Errorf("client tried to switch to invalid protocol %q", reqUpType)) return } if reqUpType != "" { outReq.Header.Set("Connection", "Upgrade") outReq.Header.Set("Upgrade", reqUpType) if strings.EqualFold(reqUpType, "websocket") { cleanWebSocketHeaders(&outReq.Header) } } u2 := new(url.URL) *u2 = *req.URL u2.Scheme = p.targetURL.Scheme u2.Host = p.targetURL.Host u := req.URL if req.RequestURI != "" { parsedURL, err := url.ParseRequestURI(req.RequestURI) if err == nil { u = parsedURL } } u2.Path = u.Path u2.RawPath = u.RawPath if p.preservePath { u2.Path, u2.RawPath = proxyhttputil.JoinURLPath(p.targetURL, u) } u2.RawQuery = strings.ReplaceAll(u.RawQuery, ";", "&") outReq.SetHost(u2.Host) outReq.Header.SetHost(u2.Host) if p.passHostHeader { outReq.Header.SetHost(req.Host) } outReq.SetRequestURI(u2.RequestURI()) outReq.SetBodyStream(req.Body, int(req.ContentLength)) outReq.Header.SetMethod(req.Method) if !proxyhttputil.ShouldNotAppendXFF(req.Context()) { if clientIP, _, err := net.SplitHostPort(req.RemoteAddr); err == nil { // If we aren't the first proxy retain prior // X-Forwarded-For information as a comma+space // separated list and fold multiple headers into one. prior, ok := req.Header["X-Forwarded-For"] if len(prior) > 0 { clientIP = strings.Join(prior, ", ") + ", " + clientIP } omit := ok && prior == nil // Go Issue 38079: nil now means don't populate the header if !omit { outReq.Header.Set("X-Forwarded-For", clientIP) } } } if err := p.roundTrip(rw, req, outReq, reqUpType); err != nil { proxyhttputil.ErrorHandler(rw, req, err) } } // Note that unlike the net/http RoundTrip: // - we are not supporting "100 Continue" response to forward them as-is to the client. // - we are not asking for compressed response automatically. That is because this will add an extra cost when the // client is asking for an uncompressed response, as we will have to un-compress it, and nowadays most clients are // already asking for compressed response (allowing "passthrough" compression). func (p *ReverseProxy) roundTrip(rw http.ResponseWriter, req *http.Request, outReq *fasthttp.Request, reqUpType string) error { ctx := req.Context() trace := httptrace.ContextClientTrace(ctx) var co *conn for { select { case <-ctx.Done(): return ctx.Err() default: } var err error co, err = p.connPool.AcquireConn() if err != nil { return fmt.Errorf("acquire connection: %w", err) } // Before writing the request, // we mark the conn as expecting to handle a response. co.expectedResponse.Store(true) wd := &writeDetector{Conn: co} // TODO: do not wait to write the full request before reading the response (to handle "100 Continue"). // TODO: this is currently impossible with fasthttp to write the request partially (headers only). // Currently, writing the request fully is a mandatory step before handling the response. err = p.writeRequest(wd, outReq) if wd.written && trace != nil && trace.WroteRequest != nil { // WroteRequest hook is used by the tracing middleware to detect if the request has been written. trace.WroteRequest(httptrace.WroteRequestInfo{}) } if err == nil { break } log.Ctx(ctx).Debug().Err(err).Msg("Error while writing request") co.Close() if wd.written && !isReplayable(req) { return err } } // Sending the responseWriter unlocks the connection readLoop, to handle the response. co.RWCh <- rwWithUpgrade{ ReqMethod: req.Method, RW: rw, Upgrade: upgradeResponseHandler(req.Context(), reqUpType), } if err := <-co.ErrCh; err != nil { return err } p.connPool.ReleaseConn(co) return nil } func (p *ReverseProxy) writeRequest(co net.Conn, outReq *fasthttp.Request) error { bw := p.writerPool.Get() if bw == nil { bw = bufio.NewWriterSize(co, bufioSize) } defer p.writerPool.Put(bw) bw.Reset(co) if err := outReq.Write(bw); err != nil { return err } return bw.Flush() } // isReplayable returns whether the request is replayable. func isReplayable(req *http.Request) bool { if req.Body == nil || req.Body == http.NoBody { switch req.Method { case http.MethodGet, http.MethodHead, http.MethodOptions, http.MethodTrace: return true } // The Idempotency-Key, while non-standard, is widely used to // mean a POST or other request is idempotent. See // https://golang.org/issue/19943#issuecomment-421092421 if _, ok := req.Header["Idempotency-Key"]; ok { return true } if _, ok := req.Header["X-Idempotency-Key"]; ok { return true } } return false } // isGraphic returns whether s is ASCII and printable according to // https://tools.ietf.org/html/rfc20#section-4.2. func isGraphic(s string) bool { for i := range len(s) { if s[i] < ' ' || s[i] > '~' { return false } } return true } type fasthttpHeader interface { Peek(key string) []byte Set(key string, value string) SetCanonical(key []byte, value []byte) DelBytes(key []byte) Del(key string) ConnectionUpgrade() bool } // removeConnectionHeaders removes hop-by-hop headers listed in the "Connection" header of h. // See RFC 7230, section 6.1. func removeConnectionHeaders(h fasthttpHeader) { f := h.Peek(fasthttp.HeaderConnection) for _, sf := range bytes.Split(f, []byte{','}) { if sf = bytes.TrimSpace(sf); len(sf) > 0 { h.DelBytes(sf) } } } // RFC 7234, section 5.4: Should treat Pragma: no-cache like Cache-Control: no-cache. func fixPragmaCacheControl(header fasthttpHeader) { if pragma := header.Peek("Pragma"); bytes.Equal(pragma, []byte("no-cache")) { if len(header.Peek("Cache-Control")) == 0 { header.Set("Cache-Control", "no-cache") } } } // cleanWebSocketHeaders Even if the websocket RFC says that headers should be case-insensitive, // some servers need Sec-WebSocket-Key, Sec-WebSocket-Extensions, Sec-WebSocket-Accept, // Sec-WebSocket-Protocol and Sec-WebSocket-Version to be case-sensitive. // https://tools.ietf.org/html/rfc6455#page-20 func cleanWebSocketHeaders(headers fasthttpHeader) { secWebsocketKey := headers.Peek("Sec-Websocket-Key") if len(secWebsocketKey) > 0 { headers.SetCanonical([]byte("Sec-WebSocket-Key"), secWebsocketKey) headers.Del("Sec-Websocket-Key") } secWebsocketExtensions := headers.Peek("Sec-Websocket-Extensions") if len(secWebsocketExtensions) > 0 { headers.SetCanonical([]byte("Sec-WebSocket-Extensions"), secWebsocketExtensions) headers.Del("Sec-Websocket-Extensions") } secWebsocketAccept := headers.Peek("Sec-Websocket-Accept") if len(secWebsocketAccept) > 0 { headers.SetCanonical([]byte("Sec-WebSocket-Accept"), secWebsocketAccept) headers.Del("Sec-Websocket-Accept") } secWebsocketProtocol := headers.Peek("Sec-Websocket-Protocol") if len(secWebsocketProtocol) > 0 { headers.SetCanonical([]byte("Sec-WebSocket-Protocol"), secWebsocketProtocol) headers.Del("Sec-Websocket-Protocol") } secWebsocketVersion := headers.Peek("Sec-Websocket-Version") if len(secWebsocketVersion) > 0 { headers.SetCanonical([]byte("Sec-WebSocket-Version"), secWebsocketVersion) headers.Del("Sec-Websocket-Version") } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/fast/dialer.go
pkg/proxy/fast/dialer.go
package fast import ( "bufio" "context" "crypto/tls" "encoding/base64" "errors" "net" "net/http" "net/url" "strings" "time" "golang.org/x/net/proxy" ) const ( schemeHTTP = "http" schemeHTTPS = "https" schemeSocks5 = "socks5" ) type dialer interface { Dial(network, addr string) (c net.Conn, err error) } type dialerFunc func(network, addr string) (net.Conn, error) func (d dialerFunc) Dial(network, addr string) (net.Conn, error) { return d(network, addr) } type dialerConfig struct { DialKeepAlive time.Duration DialTimeout time.Duration ProxyURL *url.URL HTTP bool TLS bool } func newDialer(cfg dialerConfig, tlsConfig *tls.Config) dialer { if cfg.ProxyURL == nil { return buildDialer(cfg, tlsConfig, cfg.TLS) } proxyDialer := buildDialer(cfg, tlsConfig, cfg.ProxyURL.Scheme == "https") proxyAddr := addrFromURL(cfg.ProxyURL) switch { case cfg.ProxyURL.Scheme == schemeSocks5: var auth *proxy.Auth if u := cfg.ProxyURL.User; u != nil { auth = &proxy.Auth{User: u.Username()} auth.Password, _ = u.Password() } // SOCKS5 implementation do not return errors. socksDialer, _ := proxy.SOCKS5("tcp", proxyAddr, auth, proxyDialer) return dialerFunc(func(network, targetAddr string) (net.Conn, error) { co, err := socksDialer.Dial("tcp", targetAddr) if err != nil { return nil, err } if cfg.TLS { c := &tls.Config{} if tlsConfig != nil { c = tlsConfig.Clone() } if c.ServerName == "" { host, _, _ := net.SplitHostPort(targetAddr) c.ServerName = host } return tls.Client(co, c), nil } return co, nil }) case cfg.HTTP && !cfg.TLS: // Nothing to do the Proxy-Authorization header will be added by the ReverseProxy. default: hdr := make(http.Header) if u := cfg.ProxyURL.User; u != nil { username := u.Username() password, _ := u.Password() auth := username + ":" + password hdr.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(auth))) } return dialerFunc(func(network, targetAddr string) (net.Conn, error) { conn, err := proxyDialer.Dial("tcp", proxyAddr) if err != nil { return nil, err } connectReq := &http.Request{ Method: http.MethodConnect, URL: &url.URL{Opaque: targetAddr}, Host: targetAddr, Header: hdr, } connectCtx, cancel := context.WithTimeout(context.Background(), 1*time.Minute) defer cancel() didReadResponse := make(chan struct{}) // closed after CONNECT write+read is done or fails var resp *http.Response // Write the CONNECT request & read the response. go func() { defer close(didReadResponse) err = connectReq.Write(conn) if err != nil { return } // Okay to use and discard buffered reader here, because // TLS server will not speak until spoken to. br := bufio.NewReader(conn) resp, err = http.ReadResponse(br, connectReq) }() select { case <-connectCtx.Done(): conn.Close() <-didReadResponse return nil, connectCtx.Err() case <-didReadResponse: // resp or err now set } if err != nil { conn.Close() return nil, err } if resp.StatusCode != http.StatusOK { _, statusText, ok := strings.Cut(resp.Status, " ") conn.Close() if !ok { return nil, errors.New("unknown status code") } return nil, errors.New(statusText) } c := &tls.Config{} if tlsConfig != nil { c = tlsConfig.Clone() } if c.ServerName == "" { host, _, _ := net.SplitHostPort(targetAddr) c.ServerName = host } return tls.Client(conn, c), nil }) } return dialerFunc(func(network, addr string) (net.Conn, error) { return proxyDialer.Dial("tcp", proxyAddr) }) } func buildDialer(cfg dialerConfig, tlsConfig *tls.Config, isTLS bool) dialer { dialer := &net.Dialer{ Timeout: cfg.DialTimeout, KeepAlive: cfg.DialKeepAlive, } if !isTLS { return dialer } return &tls.Dialer{ NetDialer: dialer, Config: tlsConfig, } } func addrFromURL(u *url.URL) string { addr := u.Host if u.Port() == "" { switch u.Scheme { case schemeHTTP: return addr + ":80" case schemeHTTPS: return addr + ":443" } } return addr }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/fast/proxy_websocket_test.go
pkg/proxy/fast/proxy_websocket_test.go
package fast import ( "bufio" "crypto/sha1" "crypto/tls" "encoding/base64" "errors" "fmt" "net" "net/http" "net/http/httptest" "net/url" "testing" "time" gorillawebsocket "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/testhelpers" "github.com/valyala/fasthttp" "golang.org/x/net/websocket" ) const dialTimeout = time.Second func TestWebSocketUpgradeCase(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { challengeKey := r.Header.Get("Sec-Websocket-Key") hijacker, ok := w.(http.Hijacker) require.True(t, ok) c, _, err := hijacker.Hijack() require.NoError(t, err) // Force answer with "Connection: upgrade" in lowercase. _, err = c.Write([]byte("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: upgrade\r\nSec-WebSocket-Accept: " + computeAcceptKey(challengeKey) + "\r\n\n")) require.NoError(t, err) })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) proxyAddr := proxy.Listener.Addr().String() _, conn, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), ).open() require.NoError(t, err) conn.Close() } func TestCleanWebSocketHeaders(t *testing.T) { // Asserts that no headers are sent if the request contain anything. req := fasthttp.AcquireRequest() defer fasthttp.ReleaseRequest(req) cleanWebSocketHeaders(&req.Header) want := "GET / HTTP/1.1\r\n\r\n" assert.Equal(t, want, req.Header.String()) // Asserts that the Sec-WebSocket-* is enforced. req.Reset() req.Header.Set("Sec-Websocket-Key", "key") req.Header.Set("Sec-Websocket-Extensions", "extensions") req.Header.Set("Sec-Websocket-Accept", "accept") req.Header.Set("Sec-Websocket-Protocol", "protocol") req.Header.Set("Sec-Websocket-Version", "version") cleanWebSocketHeaders(&req.Header) want = "GET / HTTP/1.1\r\nSec-WebSocket-Key: key\r\nSec-WebSocket-Extensions: extensions\r\nSec-WebSocket-Accept: accept\r\nSec-WebSocket-Protocol: protocol\r\nSec-WebSocket-Version: version\r\n\r\n" assert.Equal(t, want, req.Header.String()) } func TestWebSocketTCPClose(t *testing.T) { errChan := make(chan error, 1) upgrader := gorillawebsocket.Upgrader{} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { _, _, err := c.ReadMessage() if err != nil { errChan <- err break } } })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) proxyAddr := proxy.Listener.Addr().String() _, conn, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), ).open() require.NoError(t, err) conn.Close() serverErr := <-errChan var wsErr *gorillawebsocket.CloseError require.ErrorAs(t, serverErr, &wsErr) assert.Equal(t, 1006, wsErr.Code) } func TestWebSocketPingPong(t *testing.T) { upgrader := gorillawebsocket.Upgrader{ HandshakeTimeout: 10 * time.Second, CheckOrigin: func(*http.Request) bool { return true }, } mux := http.NewServeMux() mux.HandleFunc("/ws", func(writer http.ResponseWriter, request *http.Request) { ws, err := upgrader.Upgrade(writer, request, nil) require.NoError(t, err) ws.SetPingHandler(func(appData string) error { err = ws.WriteMessage(gorillawebsocket.PongMessage, []byte(appData+"Pong")) require.NoError(t, err) return nil }) _, _, _ = ws.ReadMessage() }) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { mux.ServeHTTP(w, req) })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) serverAddr := proxy.Listener.Addr().String() headers := http.Header{} webSocketURL := "ws://" + serverAddr + "/ws" headers.Add("Origin", webSocketURL) conn, resp, err := gorillawebsocket.DefaultDialer.Dial(webSocketURL, headers) require.NoError(t, err, "Error during Dial with response: %+v", resp) defer conn.Close() goodErr := fmt.Errorf("signal: %s", "Good data") badErr := fmt.Errorf("signal: %s", "Bad data") conn.SetPongHandler(func(data string) error { if data == "PingPong" { return goodErr } return badErr }) err = conn.WriteControl(gorillawebsocket.PingMessage, []byte("Ping"), time.Now().Add(time.Second)) require.NoError(t, err) _, _, err = conn.ReadMessage() if !errors.Is(err, goodErr) { require.NoError(t, err) } } func TestWebSocketEcho(t *testing.T) { mux := http.NewServeMux() mux.Handle("/ws", websocket.Handler(func(conn *websocket.Conn) { msg := make([]byte, 4) n, err := conn.Read(msg) require.NoError(t, err) _, err = conn.Write(msg[:n]) require.NoError(t, err) err = conn.Close() require.NoError(t, err) })) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { mux.ServeHTTP(w, req) })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) serverAddr := proxy.Listener.Addr().String() headers := http.Header{} webSocketURL := "ws://" + serverAddr + "/ws" headers.Add("Origin", webSocketURL) conn, resp, err := gorillawebsocket.DefaultDialer.Dial(webSocketURL, headers) require.NoError(t, err, "Error during Dial with response: %+v", resp) err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK")) require.NoError(t, err) _, msg, err := conn.ReadMessage() require.NoError(t, err) assert.Equal(t, "OK", string(msg)) err = conn.Close() require.NoError(t, err) } func TestWebSocketPassHost(t *testing.T) { testCases := []struct { desc string passHost bool expected string }{ { desc: "PassHost false", passHost: false, }, { desc: "PassHost true", passHost: true, expected: "example.com", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { mux := http.NewServeMux() mux.Handle("/ws", websocket.Handler(func(conn *websocket.Conn) { req := conn.Request() if test.passHost { require.Equal(t, test.expected, req.Host) } else { require.NotEqual(t, test.expected, req.Host) } msg := make([]byte, 4) n, err := conn.Read(msg) require.NoError(t, err) _, err = conn.Write(msg[:n]) require.NoError(t, err) err = conn.Close() require.NoError(t, err) })) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { mux.ServeHTTP(w, req) })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) serverAddr := proxy.Listener.Addr().String() headers := http.Header{} webSocketURL := "ws://" + serverAddr + "/ws" headers.Add("Origin", webSocketURL) headers.Add("Host", "example.com") conn, resp, err := gorillawebsocket.DefaultDialer.Dial(webSocketURL, headers) require.NoError(t, err, "Error during Dial with response: %+v", resp) err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK")) require.NoError(t, err) _, msg, err := conn.ReadMessage() require.NoError(t, err) assert.Equal(t, "OK", string(msg)) err = conn.Close() require.NoError(t, err) }) } } func TestWebSocketServerWithoutCheckOrigin(t *testing.T) { upgrader := gorillawebsocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("ok"), withOrigin("http://127.0.0.2"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketRequestWithOrigin(t *testing.T) { upgrader := gorillawebsocket.Upgrader{} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { mt, message, err := c.ReadMessage() if err != nil { break } err = c.WriteMessage(mt, message) if err != nil { break } } })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() _, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("echo"), withOrigin("http://127.0.0.2"), ).send() require.EqualError(t, err, "bad status") resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("ok"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketRequestWithQueryParams(t *testing.T) { upgrader := gorillawebsocket.Upgrader{} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer conn.Close() assert.Equal(t, "test", r.URL.Query().Get("query")) for { mt, message, err := conn.ReadMessage() if err != nil { break } err = conn.WriteMessage(mt, message) if err != nil { break } } })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws?query=test"), withData("ok"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketRequestWithHeadersInResponseWriter(t *testing.T) { mux := http.NewServeMux() mux.Handle("/ws", websocket.Handler(func(conn *websocket.Conn) { _ = conn.Close() })) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { mux.ServeHTTP(w, req) })) defer srv.Close() u := parseURI(t, srv.URL) f, err := NewReverseProxy(u, nil, true, false, false, newConnPool(1, 0, 0, func() (net.Conn, error) { return net.Dial("tcp", u.Host) })) require.NoError(t, err) proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { req.URL = parseURI(t, srv.URL) w.Header().Set("HEADER-KEY", "HEADER-VALUE") f.ServeHTTP(w, req) })) defer proxy.Close() serverAddr := proxy.Listener.Addr().String() headers := http.Header{} webSocketURL := "ws://" + serverAddr + "/ws" headers.Add("Origin", webSocketURL) conn, resp, err := gorillawebsocket.DefaultDialer.Dial(webSocketURL, headers) require.NoError(t, err, "Error during Dial with response: %+v", err, resp) defer conn.Close() assert.Equal(t, "HEADER-VALUE", resp.Header.Get("HEADER-KEY")) } func TestWebSocketRequestWithEncodedChar(t *testing.T) { upgrader := gorillawebsocket.Upgrader{} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer conn.Close() assert.Equal(t, "/%3A%2F%2F", r.URL.EscapedPath()) for { mt, message, err := conn.ReadMessage() if err != nil { break } err = conn.WriteMessage(mt, message) if err != nil { break } } })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/%3A%2F%2F"), withData("ok"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketUpgradeFailed(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/ws", func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusBadRequest) }) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { mux.ServeHTTP(w, req) })) defer srv.Close() u := parseURI(t, srv.URL) f, err := NewReverseProxy(u, nil, true, false, false, newConnPool(1, 0, 0, func() (net.Conn, error) { return net.Dial("tcp", u.Host) })) require.NoError(t, err) proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { path := req.URL.Path // keep the original path if path != "/ws" { w.WriteHeader(http.StatusOK) return } // Set new backend URL req.URL = parseURI(t, srv.URL) req.URL.Path = path f.ServeHTTP(w, req) })) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() conn, err := net.DialTimeout("tcp", proxyAddr, dialTimeout) require.NoError(t, err) defer conn.Close() req, err := http.NewRequest(http.MethodGet, "ws://127.0.0.1/ws", nil) require.NoError(t, err) req.Header.Add("upgrade", "websocket") req.Header.Add("Connection", "upgrade") err = req.Write(conn) require.NoError(t, err) // First request works with 400 br := bufio.NewReader(conn) resp, err := http.ReadResponse(br, req) require.NoError(t, err) assert.Equal(t, 400, resp.StatusCode) } func TestForwardsWebsocketTraffic(t *testing.T) { mux := http.NewServeMux() mux.Handle("/ws", websocket.Handler(func(conn *websocket.Conn) { _, err := conn.Write([]byte("ok")) require.NoError(t, err) err = conn.Close() require.NoError(t, err) })) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { mux.ServeHTTP(w, req) })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("echo"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketTransferTLSConfig(t *testing.T) { srv := createTLSWebsocketServer() defer srv.Close() proxyWithoutTLSConfig := createProxyWithForwarder(t, srv.URL, createConnectionPool(srv.URL, nil)) defer proxyWithoutTLSConfig.Close() proxyAddr := proxyWithoutTLSConfig.Listener.Addr().String() _, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("ok"), ).send() require.EqualError(t, err, "bad status") pool := createConnectionPool(srv.URL, &tls.Config{InsecureSkipVerify: true}) proxyWithTLSConfig := createProxyWithForwarder(t, srv.URL, pool) defer proxyWithTLSConfig.Close() proxyAddr = proxyWithTLSConfig.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("ok"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func createTLSWebsocketServer() *httptest.Server { upgrader := gorillawebsocket.Upgrader{} srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer conn.Close() for { mt, message, err := conn.ReadMessage() if err != nil { break } err = conn.WriteMessage(mt, message) if err != nil { break } } })) return srv } type websocketRequestOpt func(w *websocketRequest) func withServer(server string) websocketRequestOpt { return func(w *websocketRequest) { w.ServerAddr = server } } func withPath(path string) websocketRequestOpt { return func(w *websocketRequest) { w.Path = path } } func withData(data string) websocketRequestOpt { return func(w *websocketRequest) { w.Data = data } } func withOrigin(origin string) websocketRequestOpt { return func(w *websocketRequest) { w.Origin = origin } } func newWebsocketRequest(opts ...websocketRequestOpt) *websocketRequest { wsrequest := &websocketRequest{} for _, opt := range opts { opt(wsrequest) } if wsrequest.Origin == "" { wsrequest.Origin = "http://" + wsrequest.ServerAddr } if wsrequest.Config == nil { wsrequest.Config, _ = websocket.NewConfig(fmt.Sprintf("ws://%s%s", wsrequest.ServerAddr, wsrequest.Path), wsrequest.Origin) } return wsrequest } type websocketRequest struct { ServerAddr string Path string Data string Origin string Config *websocket.Config } func (w *websocketRequest) send() (string, error) { conn, _, err := w.open() if err != nil { return "", err } defer conn.Close() if _, err := conn.Write([]byte(w.Data)); err != nil { return "", err } msg := make([]byte, 512) var n int n, err = conn.Read(msg) if err != nil { return "", err } received := string(msg[:n]) return received, nil } func (w *websocketRequest) open() (*websocket.Conn, net.Conn, error) { client, err := net.DialTimeout("tcp", w.ServerAddr, dialTimeout) if err != nil { return nil, nil, err } conn, err := websocket.NewClient(w.Config, client) if err != nil { return nil, nil, err } return conn, client, err } func parseURI(t *testing.T, uri string) *url.URL { t.Helper() out, err := url.ParseRequestURI(uri) require.NoError(t, err) return out } func createConnectionPool(target string, tlsConfig *tls.Config) *connPool { u := testhelpers.MustParseURL(target) return newConnPool(200, 0, 0, func() (net.Conn, error) { if tlsConfig != nil { return tls.Dial("tcp", u.Host, tlsConfig) } return net.Dial("tcp", u.Host) }) } func createProxyWithForwarder(t *testing.T, uri string, pool *connPool) *httptest.Server { t.Helper() u := parseURI(t, uri) proxy, err := NewReverseProxy(u, nil, false, true, false, pool) require.NoError(t, err) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { path := req.URL.Path // keep the original path // Set new backend URL req.URL = u req.URL.Path = path proxy.ServeHTTP(w, req) })) t.Cleanup(srv.Close) return srv } func computeAcceptKey(challengeKey string) string { h := sha1.New() // #nosec G401 -- (CWE-326) https://datatracker.ietf.org/doc/html/rfc6455#page-54 h.Write([]byte(challengeKey)) h.Write([]byte("258EAFA5-E914-47DA-95CA-C5AB0DC85B11")) return base64.StdEncoding.EncodeToString(h.Sum(nil)) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/fast/proxy_test.go
pkg/proxy/fast/proxy_test.go
package fast import ( "crypto/tls" "crypto/x509" "encoding/base64" "fmt" "io" "net" "net/http" "net/http/httptest" "net/http/httputil" "net/url" "testing" "time" "github.com/armon/go-socks5" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/static" proxyhttputil "github.com/traefik/traefik/v3/pkg/proxy/httputil" "github.com/traefik/traefik/v3/pkg/testhelpers" ) const ( proxyHTTP = "http" proxyHTTPS = "https" proxySocks5 = "socks" ) type authCreds struct { user string password string } func TestProxyFromEnvironment(t *testing.T) { testCases := []struct { desc string proxyType string tls bool auth *authCreds }{ { desc: "Proxy HTTP with HTTP Backend", proxyType: proxyHTTP, }, { desc: "Proxy HTTP with HTTP backend and proxy auth", proxyType: proxyHTTP, tls: false, auth: &authCreds{ user: "user", password: "password", }, }, { desc: "Proxy HTTP with HTTPS backend", proxyType: proxyHTTP, tls: true, }, { desc: "Proxy HTTP with HTTPS backend and proxy auth", proxyType: proxyHTTP, tls: true, auth: &authCreds{ user: "user", password: "password", }, }, { desc: "Proxy HTTPS with HTTP backend", proxyType: proxyHTTPS, }, { desc: "Proxy HTTPS with HTTP backend and proxy auth", proxyType: proxyHTTPS, tls: false, auth: &authCreds{ user: "user", password: "password", }, }, { desc: "Proxy HTTPS with HTTPS backend", proxyType: proxyHTTPS, tls: true, }, { desc: "Proxy HTTPS with HTTPS backend and proxy auth", proxyType: proxyHTTPS, tls: true, auth: &authCreds{ user: "user", password: "password", }, }, { desc: "Proxy Socks5 with HTTP backend", proxyType: proxySocks5, }, { desc: "Proxy Socks5 with HTTP backend and proxy auth", proxyType: proxySocks5, auth: &authCreds{ user: "user", password: "password", }, }, { desc: "Proxy Socks5 with HTTPS backend", proxyType: proxySocks5, tls: true, }, { desc: "Proxy Socks5 with HTTPS backend and proxy auth", proxyType: proxySocks5, tls: true, auth: &authCreds{ user: "user", password: "password", }, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { var backendServer *httptest.Server if test.tls { backendServer = httptest.NewTLSServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { _, _ = rw.Write([]byte("backendTLS")) })) } else { backendServer = httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { _, _ = rw.Write([]byte("backend")) })) } t.Cleanup(backendServer.Close) var proxyCalled bool proxyHandler := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { proxyCalled = true if test.auth != nil { proxyAuth := "Basic " + base64.StdEncoding.EncodeToString([]byte(test.auth.user+":"+test.auth.password)) require.Equal(t, proxyAuth, req.Header.Get("Proxy-Authorization")) } if req.Method != http.MethodConnect { proxy := httputil.NewSingleHostReverseProxy(testhelpers.MustParseURL("http://" + req.Host)) proxy.ServeHTTP(rw, req) return } // CONNECT method conn, err := net.Dial("tcp", req.Host) require.NoError(t, err) hj, ok := rw.(http.Hijacker) require.True(t, ok) rw.WriteHeader(http.StatusOK) connHj, _, err := hj.Hijack() require.NoError(t, err) defer func() { _ = connHj.Close() _ = conn.Close() }() errCh := make(chan error, 1) go func() { _, err = io.Copy(connHj, conn) errCh <- err }() go func() { _, err = io.Copy(conn, connHj) errCh <- err }() <-errCh // Wait for one of the copy operations to finish }) var proxyURL string var proxyCert *x509.Certificate switch test.proxyType { case proxySocks5: ln, err := net.Listen("tcp", ":0") require.NoError(t, err) proxyURL = fmt.Sprintf("socks5://%s", ln.Addr()) go func() { conn, err := ln.Accept() require.NoError(t, err) proxyCalled = true conf := &socks5.Config{} if test.auth != nil { conf.Credentials = socks5.StaticCredentials{test.auth.user: test.auth.password} } server, err := socks5.New(conf) require.NoError(t, err) // We are not checking the error, because ServeConn is blocked until the client or the backend // connection is closed which, in some cases, raises a connection reset by peer error. _ = server.ServeConn(conn) err = ln.Close() require.NoError(t, err) }() case proxyHTTP: proxyServer := httptest.NewServer(proxyHandler) t.Cleanup(proxyServer.Close) proxyURL = proxyServer.URL case proxyHTTPS: proxyServer := httptest.NewTLSServer(proxyHandler) t.Cleanup(proxyServer.Close) proxyURL = proxyServer.URL proxyCert = proxyServer.Certificate() } certPool := x509.NewCertPool() if proxyCert != nil { certPool.AddCert(proxyCert) } if backendServer.Certificate() != nil { certPool.AddCert(backendServer.Certificate()) } builder := NewProxyBuilder(&transportManagerMock{tlsConfig: &tls.Config{RootCAs: certPool}}, static.FastProxyConfig{}) builder.proxy = func(req *http.Request) (*url.URL, error) { u, err := url.Parse(proxyURL) if err != nil { return nil, err } if test.auth != nil { u.User = url.UserPassword(test.auth.user, test.auth.password) } return u, nil } reverseProxy, err := builder.Build("foo", testhelpers.MustParseURL(backendServer.URL), false, false) require.NoError(t, err) reverseProxyServer := httptest.NewServer(reverseProxy) t.Cleanup(reverseProxyServer.Close) client := http.Client{Timeout: 5 * time.Second} resp, err := client.Get(reverseProxyServer.URL) require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) body, err := io.ReadAll(resp.Body) require.NoError(t, err) if test.tls { assert.Equal(t, "backendTLS", string(body)) } else { assert.Equal(t, "backend", string(body)) } assert.True(t, proxyCalled) }) } } func TestPreservePath(t *testing.T) { var callCount int server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { callCount++ assert.Equal(t, "/base/foo/bar", req.URL.Path) assert.Equal(t, "/base/foo%2Fbar", req.URL.RawPath) })) t.Cleanup(server.Close) builder := NewProxyBuilder(&transportManagerMock{}, static.FastProxyConfig{}) serverURL, err := url.JoinPath(server.URL, "base") require.NoError(t, err) proxyHandler, err := builder.Build("", testhelpers.MustParseURL(serverURL), true, true) require.NoError(t, err) req := httptest.NewRequest(http.MethodGet, "/foo%2Fbar", http.NoBody) res := httptest.NewRecorder() proxyHandler.ServeHTTP(res, req) assert.Equal(t, 1, callCount) assert.Equal(t, http.StatusOK, res.Code) } func TestHeadRequest(t *testing.T) { var callCount int server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { callCount++ assert.Equal(t, http.MethodHead, req.Method) rw.Header().Set("Content-Length", "42") })) t.Cleanup(server.Close) builder := NewProxyBuilder(&transportManagerMock{}, static.FastProxyConfig{}) serverURL, err := url.JoinPath(server.URL) require.NoError(t, err) proxyHandler, err := builder.Build("", testhelpers.MustParseURL(serverURL), true, true) require.NoError(t, err) req := httptest.NewRequest(http.MethodHead, "/", http.NoBody) res := httptest.NewRecorder() proxyHandler.ServeHTTP(res, req) assert.Equal(t, 1, callCount) assert.Equal(t, http.StatusOK, res.Code) } func TestNoContentLength(t *testing.T) { backendListener, err := net.Listen("tcp", ":0") require.NoError(t, err) t.Cleanup(func() { _ = backendListener.Close() }) go func() { t.Helper() conn, err := backendListener.Accept() require.NoError(t, err) _, err = conn.Write([]byte("HTTP/1.1 200 OK\r\n\r\nfoo")) require.NoError(t, err) // CloseWrite the connection to signal the end of the response. if v, ok := conn.(interface{ CloseWrite() error }); ok { err = v.CloseWrite() require.NoError(t, err) } }() builder := NewProxyBuilder(&transportManagerMock{}, static.FastProxyConfig{}) serverURL := "http://" + backendListener.Addr().String() proxyHandler, err := builder.Build("", testhelpers.MustParseURL(serverURL), true, true) require.NoError(t, err) req := httptest.NewRequest(http.MethodGet, "/", http.NoBody) res := httptest.NewRecorder() proxyHandler.ServeHTTP(res, req) assert.Equal(t, http.StatusOK, res.Code) assert.Equal(t, "foo", res.Body.String()) } func TestTransferEncodingChunked(t *testing.T) { backendServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { flusher, ok := rw.(http.Flusher) require.True(t, ok) for i := range 3 { _, err := fmt.Fprintf(rw, "chunk %d\n", i) require.NoError(t, err) flusher.Flush() } })) t.Cleanup(backendServer.Close) builder := NewProxyBuilder(&transportManagerMock{}, static.FastProxyConfig{}) proxyHandler, err := builder.Build("", testhelpers.MustParseURL(backendServer.URL), true, true) require.NoError(t, err) proxyServer := httptest.NewServer(proxyHandler) t.Cleanup(proxyServer.Close) req, err := http.NewRequest(http.MethodGet, proxyServer.URL, http.NoBody) require.NoError(t, err) res, err := http.DefaultClient.Do(req) require.NoError(t, err) t.Cleanup(func() { _ = res.Body.Close() }) assert.Equal(t, http.StatusOK, res.StatusCode) assert.Equal(t, []string{"chunked"}, res.TransferEncoding) body, err := io.ReadAll(res.Body) require.NoError(t, err) assert.Equal(t, "chunk 0\nchunk 1\nchunk 2\n", string(body)) } func TestXForwardedFor(t *testing.T) { testCases := []struct { desc string notAppendXFF bool incomingXFF string expectedXFF string expectedXFFNotPresent bool }{ { desc: "appends RemoteAddr when notAppendXFF is false", notAppendXFF: false, incomingXFF: "", expectedXFF: "192.0.2.1", }, { desc: "appends RemoteAddr to existing XFF when notAppendXFF is false", notAppendXFF: false, incomingXFF: "203.0.113.1", expectedXFF: "203.0.113.1, 192.0.2.1", }, { desc: "does not append RemoteAddr when notAppendXFF is true and no incoming XFF", notAppendXFF: true, incomingXFF: "", expectedXFFNotPresent: true, }, { desc: "preserves existing XFF when notAppendXFF is true", notAppendXFF: true, incomingXFF: "203.0.113.1", expectedXFF: "203.0.113.1", }, { desc: "preserves multiple XFF values when notAppendXFF is true", notAppendXFF: true, incomingXFF: "203.0.113.1, 198.51.100.1", expectedXFF: "203.0.113.1, 198.51.100.1", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { var receivedXFF string var xffPresent bool server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { receivedXFF = req.Header.Get("X-Forwarded-For") xffPresent = req.Header.Get("X-Forwarded-For") != "" || len(req.Header["X-Forwarded-For"]) > 0 rw.WriteHeader(http.StatusOK) })) t.Cleanup(server.Close) builder := NewProxyBuilder(&transportManagerMock{}, static.FastProxyConfig{}) proxyHandler, err := builder.Build("", testhelpers.MustParseURL(server.URL), true, false) require.NoError(t, err) ctx := t.Context() if test.notAppendXFF { ctx = proxyhttputil.SetNotAppendXFF(ctx) } req := httptest.NewRequest(http.MethodGet, "/", http.NoBody) req = req.WithContext(ctx) req.RemoteAddr = "192.0.2.1:12345" if test.incomingXFF != "" { req.Header.Set("X-Forwarded-For", test.incomingXFF) } res := httptest.NewRecorder() proxyHandler.ServeHTTP(res, req) assert.Equal(t, http.StatusOK, res.Code) if test.expectedXFFNotPresent { assert.False(t, xffPresent, "X-Forwarded-For header should not be present") } else { assert.Equal(t, test.expectedXFF, receivedXFF) } }) } } type transportManagerMock struct { tlsConfig *tls.Config } func (r *transportManagerMock) GetTLSConfig(_ string) (*tls.Config, error) { return r.tlsConfig, nil } func (r *transportManagerMock) Get(_ string) (*dynamic.ServersTransport, error) { return &dynamic.ServersTransport{}, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/fast/connpool_test.go
pkg/proxy/fast/connpool_test.go
package fast import ( "net" "runtime" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestConnPool_ConnReuse(t *testing.T) { testCases := []struct { desc string poolFn func(pool *connPool) expected int }{ { desc: "One connection", poolFn: func(pool *connPool) { c1, _ := pool.AcquireConn() pool.ReleaseConn(c1) }, expected: 1, }, { desc: "Two connections with release", poolFn: func(pool *connPool) { c1, _ := pool.AcquireConn() pool.ReleaseConn(c1) c2, _ := pool.AcquireConn() pool.ReleaseConn(c2) }, expected: 1, }, { desc: "Two concurrent connections", poolFn: func(pool *connPool) { c1, _ := pool.AcquireConn() c2, _ := pool.AcquireConn() pool.ReleaseConn(c1) pool.ReleaseConn(c2) }, expected: 2, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() var connAlloc int dialer := func() (net.Conn, error) { connAlloc++ return &net.TCPConn{}, nil } pool := newConnPool(2, 0, 0, dialer) test.poolFn(pool) assert.Equal(t, test.expected, connAlloc) }) } } func TestConnPool_MaxIdleConn(t *testing.T) { testCases := []struct { desc string poolFn func(pool *connPool) maxIdleConn int expected int }{ { desc: "One connection", poolFn: func(pool *connPool) { c1, _ := pool.AcquireConn() pool.ReleaseConn(c1) }, maxIdleConn: 1, expected: 1, }, { desc: "Multiple connections with defered release", poolFn: func(pool *connPool) { for range 7 { c, _ := pool.AcquireConn() defer pool.ReleaseConn(c) } }, maxIdleConn: 5, expected: 5, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() var keepOpenedConn int dialer := func() (net.Conn, error) { keepOpenedConn++ return &mockConn{ doneCh: make(chan struct{}), closeFn: func() error { keepOpenedConn-- return nil }, }, nil } pool := newConnPool(test.maxIdleConn, 0, 0, dialer) test.poolFn(pool) assert.Equal(t, test.expected, keepOpenedConn) }) } } func TestGC(t *testing.T) { // TODO: make the test stable if possible. t.Skip("This test is flaky") var isDestroyed bool pools := map[string]*connPool{} dialer := func() (net.Conn, error) { c := &mockConn{closeFn: func() error { return nil }} return c, nil } pools["test"] = newConnPool(10, 1*time.Second, 0, dialer) runtime.SetFinalizer(pools["test"], func(p *connPool) { isDestroyed = true }) c, err := pools["test"].AcquireConn() require.NoError(t, err) pools["test"].ReleaseConn(c) pools["test"].Close() delete(pools, "test") runtime.GC() require.True(t, isDestroyed) } type mockConn struct { closeFn func() error doneCh chan struct{} // makes sure that the readLoop is blocking avoiding close. } func (m *mockConn) Read(_ []byte) (n int, err error) { <-m.doneCh return 0, nil } func (m *mockConn) Write(_ []byte) (n int, err error) { panic("implement me") } func (m *mockConn) Close() error { defer close(m.doneCh) if m.closeFn != nil { return m.closeFn() } return nil } func (m *mockConn) LocalAddr() net.Addr { panic("implement me") } func (m *mockConn) RemoteAddr() net.Addr { panic("implement me") } func (m *mockConn) SetDeadline(_ time.Time) error { panic("implement me") } func (m *mockConn) SetReadDeadline(_ time.Time) error { panic("implement me") } func (m *mockConn) SetWriteDeadline(_ time.Time) error { panic("implement me") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/fast/builder.go
pkg/proxy/fast/builder.go
package fast import ( "crypto/tls" "fmt" "net" "net/http" "net/url" "reflect" "time" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/config/static" ) // TransportManager manages transport used for backend communications. type TransportManager interface { Get(name string) (*dynamic.ServersTransport, error) GetTLSConfig(name string) (*tls.Config, error) } // ProxyBuilder handles the connection pools for the FastProxy proxies. type ProxyBuilder struct { debug bool transportManager TransportManager // lock isn't needed because ProxyBuilder is not called concurrently. pools map[string]map[string]*connPool proxy func(*http.Request) (*url.URL, error) // not goroutine safe. configs map[string]*dynamic.ServersTransport } // NewProxyBuilder creates a new ProxyBuilder. func NewProxyBuilder(transportManager TransportManager, config static.FastProxyConfig) *ProxyBuilder { return &ProxyBuilder{ debug: config.Debug, transportManager: transportManager, pools: make(map[string]map[string]*connPool), proxy: http.ProxyFromEnvironment, configs: make(map[string]*dynamic.ServersTransport), } } // Update updates all the round-tripper corresponding to the given configs. // This method must not be used concurrently. func (r *ProxyBuilder) Update(newConfigs map[string]*dynamic.ServersTransport) { for configName := range r.configs { if _, ok := newConfigs[configName]; !ok { for _, c := range r.pools[configName] { c.Close() } delete(r.pools, configName) } } for newConfigName, newConfig := range newConfigs { if !reflect.DeepEqual(newConfig, r.configs[newConfigName]) { for _, c := range r.pools[newConfigName] { c.Close() } delete(r.pools, newConfigName) } } r.configs = newConfigs } // Build builds a new ReverseProxy with the given configuration. func (r *ProxyBuilder) Build(cfgName string, targetURL *url.URL, passHostHeader, preservePath bool) (http.Handler, error) { proxyURL, err := r.proxy(&http.Request{URL: targetURL}) if err != nil { return nil, fmt.Errorf("getting proxy: %w", err) } cfg, err := r.transportManager.Get(cfgName) if err != nil { return nil, fmt.Errorf("getting ServersTransport: %w", err) } tlsConfig, err := r.transportManager.GetTLSConfig(cfgName) if err != nil { return nil, fmt.Errorf("getting TLS config: %w", err) } pool := r.getPool(cfgName, cfg, tlsConfig, targetURL, proxyURL) return NewReverseProxy(targetURL, proxyURL, r.debug, passHostHeader, preservePath, pool) } func (r *ProxyBuilder) getPool(cfgName string, config *dynamic.ServersTransport, tlsConfig *tls.Config, targetURL *url.URL, proxyURL *url.URL) *connPool { pool, ok := r.pools[cfgName] if !ok { pool = make(map[string]*connPool) r.pools[cfgName] = pool } if connPool, ok := pool[targetURL.String()]; ok { return connPool } idleConnTimeout := 90 * time.Second dialTimeout := 30 * time.Second var responseHeaderTimeout time.Duration if config.ForwardingTimeouts != nil { idleConnTimeout = time.Duration(config.ForwardingTimeouts.IdleConnTimeout) dialTimeout = time.Duration(config.ForwardingTimeouts.DialTimeout) responseHeaderTimeout = time.Duration(config.ForwardingTimeouts.ResponseHeaderTimeout) } proxyDialer := newDialer(dialerConfig{ DialKeepAlive: 0, DialTimeout: dialTimeout, HTTP: true, TLS: targetURL.Scheme == "https", ProxyURL: proxyURL, }, tlsConfig) connPool := newConnPool(config.MaxIdleConnsPerHost, idleConnTimeout, responseHeaderTimeout, func() (net.Conn, error) { return proxyDialer.Dial("tcp", addrFromURL(targetURL)) }) r.pools[cfgName][targetURL.String()] = connPool return connPool }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/fast/upgrade.go
pkg/proxy/fast/upgrade.go
package fast import ( "context" "fmt" "io" "net" "net/http" "strings" "github.com/traefik/traefik/v3/pkg/proxy/httputil" "github.com/valyala/fasthttp" "golang.org/x/net/http/httpguts" ) // switchProtocolCopier exists so goroutines proxying data back and // forth have nice names in stacks. type switchProtocolCopier struct { user, backend io.ReadWriter } func (c switchProtocolCopier) copyFromBackend(errCh chan<- error) { _, err := io.Copy(c.user, c.backend) errCh <- err } func (c switchProtocolCopier) copyToBackend(errCh chan<- error) { _, err := io.Copy(c.backend, c.user) errCh <- err } type upgradeHandler func(rw http.ResponseWriter, res *fasthttp.Response, backConn net.Conn) func upgradeResponseHandler(ctx context.Context, reqUpType string) upgradeHandler { return func(rw http.ResponseWriter, res *fasthttp.Response, backConn net.Conn) { resUpType := upgradeTypeFastHTTP(&res.Header) if !strings.EqualFold(reqUpType, resUpType) { httputil.ErrorHandlerWithContext(ctx, rw, fmt.Errorf("backend tried to switch protocol %q when %q was requested", resUpType, reqUpType)) backConn.Close() return } hj, ok := rw.(http.Hijacker) if !ok { httputil.ErrorHandlerWithContext(ctx, rw, fmt.Errorf("can't switch protocols using non-Hijacker ResponseWriter type %T", rw)) backConn.Close() return } backConnCloseCh := make(chan bool) go func() { // Ensure that the cancellation of a request closes the backend. // See issue https://golang.org/issue/35559. select { case <-ctx.Done(): case <-backConnCloseCh: } _ = backConn.Close() }() defer close(backConnCloseCh) conn, brw, err := hj.Hijack() if err != nil { httputil.ErrorHandlerWithContext(ctx, rw, fmt.Errorf("hijack failed on protocol switch: %w", err)) return } defer conn.Close() for k, values := range rw.Header() { for _, v := range values { res.Header.Add(k, v) } } if err := res.Header.Write(brw.Writer); err != nil { httputil.ErrorHandlerWithContext(ctx, rw, fmt.Errorf("response write: %w", err)) return } if err := brw.Flush(); err != nil { httputil.ErrorHandlerWithContext(ctx, rw, fmt.Errorf("response flush: %w", err)) return } errCh := make(chan error, 1) spc := switchProtocolCopier{user: conn, backend: backConn} go spc.copyToBackend(errCh) go spc.copyFromBackend(errCh) <-errCh } } func upgradeType(h http.Header) string { if !httpguts.HeaderValuesContainsToken(h["Connection"], "Upgrade") { return "" } return h.Get("Upgrade") } func upgradeTypeFastHTTP(h fasthttpHeader) string { if !h.ConnectionUpgrade() { return "" } return string(h.Peek("Upgrade")) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/httputil/observability_test.go
pkg/proxy/httputil/observability_test.go
package httputil import ( "net/http" "net/http/httptest" "testing" "time" "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v3/pkg/middlewares/observability" "github.com/traefik/traefik/v3/pkg/observability/metrics" otypes "github.com/traefik/traefik/v3/pkg/observability/types" "go.opentelemetry.io/otel/attribute" sdkmetric "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/metric/metricdata" "go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest" ) func TestObservabilityRoundTripper_metrics(t *testing.T) { tests := []struct { desc string serverURL string statusCode int wantAttributes attribute.Set }{ { desc: "not found status", serverURL: "http://www.test.com", statusCode: http.StatusNotFound, wantAttributes: attribute.NewSet( attribute.Key("error.type").String("404"), attribute.Key("http.request.method").String("GET"), attribute.Key("http.response.status_code").Int(404), attribute.Key("network.protocol.name").String("http/1.1"), attribute.Key("network.protocol.version").String("1.1"), attribute.Key("server.address").String("www.test.com"), attribute.Key("server.port").Int(80), attribute.Key("url.scheme").String("http"), ), }, { desc: "created status", serverURL: "https://www.test.com", statusCode: http.StatusCreated, wantAttributes: attribute.NewSet( attribute.Key("http.request.method").String("GET"), attribute.Key("http.response.status_code").Int(201), attribute.Key("network.protocol.name").String("http/1.1"), attribute.Key("network.protocol.version").String("1.1"), attribute.Key("server.address").String("www.test.com"), attribute.Key("server.port").Int(443), attribute.Key("url.scheme").String("http"), ), }, } for _, test := range tests { t.Run(test.desc, func(t *testing.T) { t.Parallel() var cfg otypes.OTLP (&cfg).SetDefaults() cfg.AddRoutersLabels = true cfg.PushInterval = ptypes.Duration(10 * time.Millisecond) rdr := sdkmetric.NewManualReader() meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(rdr)) // force the meter provider with manual reader to collect metrics for the test. metrics.SetMeterProvider(meterProvider) semConvMetricRegistry, err := metrics.NewSemConvMetricRegistry(t.Context(), &cfg) require.NoError(t, err) require.NotNil(t, semConvMetricRegistry) req := httptest.NewRequest(http.MethodGet, test.serverURL+"/search?q=Opentelemetry", nil) req.RemoteAddr = "10.0.0.1:1234" req.Header.Set("User-Agent", "rt-test") req.Header.Set("X-Forwarded-Proto", "http") // Injection of the observability variables in the request context. req = req.WithContext(observability.WithObservability(req.Context(), observability.Observability{ SemConvMetricsEnabled: true, })) ort := newObservabilityRoundTripper(semConvMetricRegistry, mockRoundTripper{statusCode: test.statusCode}) _, err = ort.RoundTrip(req) require.NoError(t, err) got := metricdata.ResourceMetrics{} err = rdr.Collect(t.Context(), &got) require.NoError(t, err) require.Len(t, got.ScopeMetrics, 1) expected := metricdata.Metrics{ Name: "http.client.request.duration", Description: "Duration of HTTP client requests.", Unit: "s", Data: metricdata.Histogram[float64]{ DataPoints: []metricdata.HistogramDataPoint[float64]{ { Attributes: test.wantAttributes, Count: 1, Bounds: []float64{0.005, 0.01, 0.025, 0.05, 0.075, 0.1, 0.25, 0.5, 0.75, 1, 2.5, 5, 7.5, 10}, BucketCounts: []uint64{0x1, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, Min: metricdata.NewExtrema[float64](1), Max: metricdata.NewExtrema[float64](1), Sum: 1, }, }, Temporality: metricdata.CumulativeTemporality, }, } metricdatatest.AssertEqual[metricdata.Metrics](t, expected, got.ScopeMetrics[0].Metrics[0], metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue()) }) } } type mockRoundTripper struct { statusCode int } func (m mockRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) { return &http.Response{StatusCode: m.statusCode}, nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/httputil/proxy.go
pkg/proxy/httputil/proxy.go
package httputil import ( "context" "crypto/tls" "errors" "io" stdlog "log" "net" "net/http" "net/http/httputil" "net/url" "strings" "time" "github.com/rs/zerolog" "github.com/rs/zerolog/log" "github.com/traefik/traefik/v3/pkg/observability/logs" "golang.org/x/net/http/httpguts" ) type key string const ( // StatusClientClosedRequest non-standard HTTP status code for client disconnection. StatusClientClosedRequest = 499 // StatusClientClosedRequestText non-standard HTTP status for client disconnection. StatusClientClosedRequestText = "Client Closed Request" notAppendXFFKey key = "NotAppendXFF" ) // SetNotAppendXFF indicates xff should not be appended. func SetNotAppendXFF(ctx context.Context) context.Context { return context.WithValue(ctx, notAppendXFFKey, true) } // ShouldNotAppendXFF returns whether X-Forwarded-For should not be appended. func ShouldNotAppendXFF(ctx context.Context) bool { val := ctx.Value(notAppendXFFKey) if val == nil { return false } notAppendXFF, ok := val.(bool) if !ok { return false } return notAppendXFF } func buildSingleHostProxy(target *url.URL, passHostHeader bool, preservePath bool, flushInterval time.Duration, roundTripper http.RoundTripper, bufferPool httputil.BufferPool) http.Handler { return &httputil.ReverseProxy{ Rewrite: rewriteRequestBuilder(target, passHostHeader, preservePath), Transport: roundTripper, FlushInterval: flushInterval, BufferPool: bufferPool, ErrorLog: stdlog.New(logs.NoLevel(log.Logger, zerolog.DebugLevel), "", 0), ErrorHandler: ErrorHandler, } } func rewriteRequestBuilder(target *url.URL, passHostHeader bool, preservePath bool) func(*httputil.ProxyRequest) { return func(pr *httputil.ProxyRequest) { copyForwardedHeader(pr.Out.Header, pr.In.Header) if !ShouldNotAppendXFF(pr.In.Context()) { if clientIP, _, err := net.SplitHostPort(pr.In.RemoteAddr); err == nil { // If we aren't the first proxy retain prior // X-Forwarded-For information as a comma+space // separated list and fold multiple headers into one. prior, ok := pr.Out.Header["X-Forwarded-For"] omit := ok && prior == nil // Issue 38079: nil now means don't populate the header if len(prior) > 0 { clientIP = strings.Join(prior, ", ") + ", " + clientIP } if !omit { pr.Out.Header.Set("X-Forwarded-For", clientIP) } } } pr.Out.URL.Scheme = target.Scheme pr.Out.URL.Host = target.Host u := pr.Out.URL if pr.Out.RequestURI != "" { parsedURL, err := url.ParseRequestURI(pr.Out.RequestURI) if err == nil { u = parsedURL } } pr.Out.URL.Path = u.Path pr.Out.URL.RawPath = u.RawPath if preservePath { pr.Out.URL.Path, pr.Out.URL.RawPath = JoinURLPath(target, u) } // If a plugin/middleware adds semicolons in query params, they should be urlEncoded. pr.Out.URL.RawQuery = strings.ReplaceAll(u.RawQuery, ";", "&") pr.Out.RequestURI = "" // Outgoing request should not have RequestURI pr.Out.Proto = "HTTP/1.1" pr.Out.ProtoMajor = 1 pr.Out.ProtoMinor = 1 // Do not pass client Host header unless option PassHostHeader is set. if !passHostHeader { pr.Out.Host = pr.Out.URL.Host } if isWebSocketUpgrade(pr.Out) { cleanWebSocketHeaders(pr.Out) } } } // copyForwardedHeader copies header that are removed by the reverseProxy when a rewriteRequest is used. func copyForwardedHeader(dst, src http.Header) { prior, ok := src["X-Forwarded-For"] if ok { dst["X-Forwarded-For"] = prior } prior, ok = src["Forwarded"] if ok { dst["Forwarded"] = prior } prior, ok = src["X-Forwarded-Host"] if ok { dst["X-Forwarded-Host"] = prior } prior, ok = src["X-Forwarded-Proto"] if ok { dst["X-Forwarded-Proto"] = prior } } // cleanWebSocketHeaders Even if the websocket RFC says that headers should be case-insensitive, // some servers need Sec-WebSocket-Key, Sec-WebSocket-Extensions, Sec-WebSocket-Accept, // Sec-WebSocket-Protocol and Sec-WebSocket-Version to be case-sensitive. // https://tools.ietf.org/html/rfc6455#page-20 func cleanWebSocketHeaders(req *http.Request) { req.Header["Sec-WebSocket-Key"] = req.Header["Sec-Websocket-Key"] delete(req.Header, "Sec-Websocket-Key") req.Header["Sec-WebSocket-Extensions"] = req.Header["Sec-Websocket-Extensions"] delete(req.Header, "Sec-Websocket-Extensions") req.Header["Sec-WebSocket-Accept"] = req.Header["Sec-Websocket-Accept"] delete(req.Header, "Sec-Websocket-Accept") req.Header["Sec-WebSocket-Protocol"] = req.Header["Sec-Websocket-Protocol"] delete(req.Header, "Sec-Websocket-Protocol") req.Header["Sec-WebSocket-Version"] = req.Header["Sec-Websocket-Version"] delete(req.Header, "Sec-Websocket-Version") } func isWebSocketUpgrade(req *http.Request) bool { return httpguts.HeaderValuesContainsToken(req.Header["Connection"], "Upgrade") && strings.EqualFold(req.Header.Get("Upgrade"), "websocket") } // ErrorHandler is the http.Handler called when something goes wrong when forwarding the request. func ErrorHandler(w http.ResponseWriter, req *http.Request, err error) { ErrorHandlerWithContext(req.Context(), w, err) } // ErrorHandlerWithContext is the http.Handler called when something goes wrong when forwarding the request. func ErrorHandlerWithContext(ctx context.Context, w http.ResponseWriter, err error) { statusCode := ComputeStatusCode(err) logger := log.Ctx(ctx) // Log the error with error level if it is a TLS error related to configuration. if isTLSConfigError(err) { logger.Error().Err(err).Msgf("%d %s", statusCode, statusText(statusCode)) } else { logger.Debug().Err(err).Msgf("%d %s", statusCode, statusText(statusCode)) } w.WriteHeader(statusCode) if _, werr := w.Write([]byte(statusText(statusCode))); werr != nil { logger.Debug().Err(werr).Msg("Error while writing status code") } } func statusText(statusCode int) string { if statusCode == StatusClientClosedRequest { return StatusClientClosedRequestText } return http.StatusText(statusCode) } // isTLSConfigError returns true if the error is a TLS error which is related to configuration. // We assume that if the error is a tls.RecordHeaderError or a tls.CertificateVerificationError, // it is related to configuration, because the client should not send a TLS request to a non-TLS server, // and the client configuration should allow to verify the server certificate. func isTLSConfigError(err error) bool { // tls.RecordHeaderError is returned when the client sends a TLS request to a non-TLS server. var recordHeaderErr tls.RecordHeaderError if errors.As(err, &recordHeaderErr) { return true } // tls.CertificateVerificationError is returned when the server certificate cannot be verified. var certVerificationErr *tls.CertificateVerificationError return errors.As(err, &certVerificationErr) } // ComputeStatusCode computes the HTTP status code according to the given error. func ComputeStatusCode(err error) int { switch { case errors.Is(err, io.EOF): return http.StatusBadGateway case errors.Is(err, context.Canceled): return StatusClientClosedRequest default: var netErr net.Error if errors.As(err, &netErr) { if netErr.Timeout() { return http.StatusGatewayTimeout } return http.StatusBadGateway } } return http.StatusInternalServerError } // JoinURLPath computes the joined path and raw path of the given URLs. // From https://github.com/golang/go/blob/b521ebb55a9b26c8824b219376c7f91f7cda6ec2/src/net/http/httputil/reverseproxy.go#L221 func JoinURLPath(a, b *url.URL) (path, rawpath string) { if a.RawPath == "" && b.RawPath == "" { return singleJoiningSlash(a.Path, b.Path), "" } // Same as singleJoiningSlash, but uses EscapedPath to determine // whether a slash should be added apath := a.EscapedPath() bpath := b.EscapedPath() aslash := strings.HasSuffix(apath, "/") bslash := strings.HasPrefix(bpath, "/") switch { case aslash && bslash: return a.Path + b.Path[1:], apath + bpath[1:] case !aslash && !bslash: return a.Path + "/" + b.Path, apath + "/" + bpath } return a.Path + b.Path, apath + bpath } func singleJoiningSlash(a, b string) string { aslash := strings.HasSuffix(a, "/") bslash := strings.HasPrefix(b, "/") switch { case aslash && bslash: return a + b[1:] case !aslash && !bslash: return a + "/" + b } return a + b }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/httputil/proxy_websocket_test.go
pkg/proxy/httputil/proxy_websocket_test.go
package httputil import ( "bufio" "bytes" "crypto/tls" "errors" "fmt" "net" "net/http" "net/http/httptest" "testing" "time" gorillawebsocket "github.com/gorilla/websocket" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/testhelpers" "golang.org/x/net/websocket" ) const dialTimeout = time.Second func TestWebSocketTCPClose(t *testing.T) { errChan := make(chan error, 1) upgrader := gorillawebsocket.Upgrader{} srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer c.Close() for { _, _, err := c.ReadMessage() if err != nil { errChan <- err break } } })) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) proxyAddr := proxy.Listener.Addr().String() _, conn, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), ).open() require.NoError(t, err) conn.Close() serverErr := <-errChan var wsErr *gorillawebsocket.CloseError require.ErrorAs(t, serverErr, &wsErr) assert.Equal(t, 1006, wsErr.Code) } func TestWebSocketPingPong(t *testing.T) { upgrader := gorillawebsocket.Upgrader{ HandshakeTimeout: 10 * time.Second, CheckOrigin: func(*http.Request) bool { return true }, } mux := http.NewServeMux() mux.HandleFunc("/ws", func(writer http.ResponseWriter, request *http.Request) { ws, err := upgrader.Upgrade(writer, request, nil) require.NoError(t, err) ws.SetPingHandler(func(appData string) error { err = ws.WriteMessage(gorillawebsocket.PongMessage, []byte(appData+"Pong")) require.NoError(t, err) return nil }) _, _, _ = ws.ReadMessage() }) srv := httptest.NewServer(mux) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) serverAddr := proxy.Listener.Addr().String() headers := http.Header{} webSocketURL := "ws://" + serverAddr + "/ws" headers.Add("Origin", webSocketURL) conn, resp, err := gorillawebsocket.DefaultDialer.Dial(webSocketURL, headers) require.NoError(t, err, "Error during Dial with response: %+v", resp) defer conn.Close() goodErr := fmt.Errorf("signal: %s", "Good data") badErr := fmt.Errorf("signal: %s", "Bad data") conn.SetPongHandler(func(data string) error { if data == "PingPong" { return goodErr } return badErr }) err = conn.WriteControl(gorillawebsocket.PingMessage, []byte("Ping"), time.Now().Add(time.Second)) require.NoError(t, err) _, _, err = conn.ReadMessage() if !errors.Is(err, goodErr) { require.NoError(t, err) } } func TestWebSocketEcho(t *testing.T) { mux := http.NewServeMux() mux.Handle("/ws", websocket.Handler(func(conn *websocket.Conn) { msg := make([]byte, 4) n, err := conn.Read(msg) require.NoError(t, err) _, err = conn.Write(msg[:n]) require.NoError(t, err) err = conn.Close() require.NoError(t, err) })) srv := httptest.NewServer(mux) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) serverAddr := proxy.Listener.Addr().String() headers := http.Header{} webSocketURL := "ws://" + serverAddr + "/ws" headers.Add("Origin", webSocketURL) conn, resp, err := gorillawebsocket.DefaultDialer.Dial(webSocketURL, headers) require.NoError(t, err, "Error during Dial with response: %+v", resp) err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK")) require.NoError(t, err) _, msg, err := conn.ReadMessage() require.NoError(t, err) assert.Equal(t, "OK", string(msg)) err = conn.Close() require.NoError(t, err) } func TestWebSocketPassHost(t *testing.T) { testCases := []struct { desc string passHost bool expected string }{ { desc: "PassHost false", passHost: false, }, { desc: "PassHost true", passHost: true, expected: "example.com", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { mux := http.NewServeMux() mux.Handle("/ws", websocket.Handler(func(conn *websocket.Conn) { req := conn.Request() if test.passHost { require.Equal(t, test.expected, req.Host) } else { require.NotEqual(t, test.expected, req.Host) } msg := make([]byte, 4) n, err := conn.Read(msg) require.NoError(t, err) _, err = conn.Write(msg[:n]) require.NoError(t, err) err = conn.Close() require.NoError(t, err) })) srv := httptest.NewServer(mux) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) serverAddr := proxy.Listener.Addr().String() headers := http.Header{} webSocketURL := "ws://" + serverAddr + "/ws" headers.Add("Origin", webSocketURL) headers.Add("Host", "example.com") conn, resp, err := gorillawebsocket.DefaultDialer.Dial(webSocketURL, headers) require.NoError(t, err, "Error during Dial with response: %+v", resp) err = conn.WriteMessage(gorillawebsocket.TextMessage, []byte("OK")) require.NoError(t, err) _, msg, err := conn.ReadMessage() require.NoError(t, err) assert.Equal(t, "OK", string(msg)) err = conn.Close() require.NoError(t, err) }) } } func TestWebSocketServerWithoutCheckOrigin(t *testing.T) { upgrader := gorillawebsocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }} srv := createServer(t, upgrader, func(*http.Request) {}) proxy := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("ok"), withOrigin("http://127.0.0.2"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketRequestWithOrigin(t *testing.T) { srv := createServer(t, gorillawebsocket.Upgrader{}, func(*http.Request) {}) proxy := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() _, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("echo"), withOrigin("http://127.0.0.2"), ).send() require.EqualError(t, err, "bad status") resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("ok"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketRequestWithQueryParams(t *testing.T) { srv := createServer(t, gorillawebsocket.Upgrader{}, func(r *http.Request) { assert.Equal(t, "test", r.URL.Query().Get("query")) }) proxy := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws?query=test"), withData("ok"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketRequestWithHeadersInResponseWriter(t *testing.T) { mux := http.NewServeMux() mux.Handle("/ws", websocket.Handler(func(conn *websocket.Conn) { conn.Close() })) srv := httptest.NewServer(mux) defer srv.Close() transportManager := &transportManagerMock{ roundTrippers: map[string]http.RoundTripper{ "default@internal": &http.Transport{}, }, } p, err := NewProxyBuilder(transportManager, nil).Build("default@internal", testhelpers.MustParseURL(srv.URL), true, false, 0) require.NoError(t, err) proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { req.URL = testhelpers.MustParseURL(srv.URL) w.Header().Set("HEADER-KEY", "HEADER-VALUE") p.ServeHTTP(w, req) })) defer proxy.Close() serverAddr := proxy.Listener.Addr().String() headers := http.Header{} webSocketURL := "ws://" + serverAddr + "/ws" headers.Add("Origin", webSocketURL) conn, resp, err := gorillawebsocket.DefaultDialer.Dial(webSocketURL, headers) require.NoError(t, err, "Error during Dial with response: %+v", err, resp) defer conn.Close() assert.Equal(t, "HEADER-VALUE", resp.Header.Get("HEADER-KEY")) } func TestWebSocketRequestWithEncodedChar(t *testing.T) { srv := createServer(t, gorillawebsocket.Upgrader{}, func(r *http.Request) { assert.Equal(t, "/%3A%2F%2F", r.URL.EscapedPath()) }) proxy := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/%3A%2F%2F"), withData("ok"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketUpgradeFailed(t *testing.T) { mux := http.NewServeMux() mux.HandleFunc("/ws", func(w http.ResponseWriter, req *http.Request) { w.WriteHeader(http.StatusBadRequest) }) srv := httptest.NewServer(mux) defer srv.Close() transportManager := &transportManagerMock{ roundTrippers: map[string]http.RoundTripper{ "default@internal": &http.Transport{}, }, } p, err := NewProxyBuilder(transportManager, nil).Build("default@internal", testhelpers.MustParseURL(srv.URL), true, false, 0) require.NoError(t, err) proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { path := req.URL.Path // keep the original path if path == "/ws" { // Set new backend URL req.URL = testhelpers.MustParseURL(srv.URL) req.URL.Path = path p.ServeHTTP(w, req) } else { w.WriteHeader(http.StatusOK) } })) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() conn, err := net.DialTimeout("tcp", proxyAddr, dialTimeout) require.NoError(t, err) defer conn.Close() req, err := http.NewRequest(http.MethodGet, "ws://127.0.0.1/ws", nil) require.NoError(t, err) req.Header.Add("upgrade", "websocket") req.Header.Add("Connection", "upgrade") err = req.Write(conn) require.NoError(t, err) // First request works with 400 br := bufio.NewReader(conn) resp, err := http.ReadResponse(br, req) require.NoError(t, err) assert.Equal(t, 400, resp.StatusCode) } func TestForwardsWebsocketTraffic(t *testing.T) { mux := http.NewServeMux() mux.Handle("/ws", websocket.Handler(func(conn *websocket.Conn) { _, err := conn.Write([]byte("ok")) require.NoError(t, err) err = conn.Close() require.NoError(t, err) })) srv := httptest.NewServer(mux) defer srv.Close() proxy := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) defer proxy.Close() proxyAddr := proxy.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("echo"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestWebSocketTransferTLSConfig(t *testing.T) { srv := createTLSWebsocketServer() defer srv.Close() proxyWithoutTLSConfig := createProxyWithForwarder(t, srv.URL, http.DefaultTransport) defer proxyWithoutTLSConfig.Close() proxyAddr := proxyWithoutTLSConfig.Listener.Addr().String() _, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("ok"), ).send() require.EqualError(t, err, "bad status") transport := &http.Transport{ TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, } proxyWithTLSConfig := createProxyWithForwarder(t, srv.URL, transport) defer proxyWithTLSConfig.Close() proxyAddr = proxyWithTLSConfig.Listener.Addr().String() resp, err := newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("ok"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) // Don't alter default transport to prevent side effects on other tests. defaultTransport := http.DefaultTransport.(*http.Transport).Clone() defaultTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true} proxyWithTLSConfigFromDefaultTransport := createProxyWithForwarder(t, srv.URL, defaultTransport) defer proxyWithTLSConfig.Close() proxyAddr = proxyWithTLSConfigFromDefaultTransport.Listener.Addr().String() resp, err = newWebsocketRequest( withServer(proxyAddr), withPath("/ws"), withData("ok"), ).send() require.NoError(t, err) assert.Equal(t, "ok", resp) } func TestCleanWebSocketHeaders(t *testing.T) { // Asserts that no headers are sent if the request contain anything. req := httptest.NewRequest(http.MethodGet, "/", http.NoBody) req.Header.Del("User-Agent") cleanWebSocketHeaders(req) b := bytes.NewBuffer(nil) err := req.Header.Write(b) require.NoError(t, err) assert.Empty(t, b) // Asserts that the Sec-WebSocket-* is enforced. req.Header.Set("Sec-Websocket-Key", "key") req.Header.Set("Sec-Websocket-Extensions", "extensions") req.Header.Set("Sec-Websocket-Accept", "accept") req.Header.Set("Sec-Websocket-Protocol", "protocol") req.Header.Set("Sec-Websocket-Version", "version") cleanWebSocketHeaders(req) want := http.Header{ "Sec-WebSocket-Key": {"key"}, "Sec-WebSocket-Extensions": {"extensions"}, "Sec-WebSocket-Accept": {"accept"}, "Sec-WebSocket-Protocol": {"protocol"}, "Sec-WebSocket-Version": {"version"}, } assert.Equal(t, want, req.Header) } func createTLSWebsocketServer() *httptest.Server { var upgrader gorillawebsocket.Upgrader return httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { return } defer conn.Close() for { mt, message, err := conn.ReadMessage() if err != nil { break } err = conn.WriteMessage(mt, message) if err != nil { break } } })) } type websocketRequestOpt func(w *websocketRequest) func withServer(server string) websocketRequestOpt { return func(w *websocketRequest) { w.ServerAddr = server } } func withPath(path string) websocketRequestOpt { return func(w *websocketRequest) { w.Path = path } } func withData(data string) websocketRequestOpt { return func(w *websocketRequest) { w.Data = data } } func withOrigin(origin string) websocketRequestOpt { return func(w *websocketRequest) { w.Origin = origin } } func newWebsocketRequest(opts ...websocketRequestOpt) *websocketRequest { wsrequest := &websocketRequest{} for _, opt := range opts { opt(wsrequest) } if wsrequest.Origin == "" { wsrequest.Origin = "http://" + wsrequest.ServerAddr } if wsrequest.Config == nil { wsrequest.Config, _ = websocket.NewConfig(fmt.Sprintf("ws://%s%s", wsrequest.ServerAddr, wsrequest.Path), wsrequest.Origin) } return wsrequest } type websocketRequest struct { ServerAddr string Path string Data string Origin string Config *websocket.Config } func (w *websocketRequest) send() (string, error) { conn, _, err := w.open() if err != nil { return "", err } defer conn.Close() if _, err := conn.Write([]byte(w.Data)); err != nil { return "", err } msg := make([]byte, 512) var n int n, err = conn.Read(msg) if err != nil { return "", err } received := string(msg[:n]) return received, nil } func (w *websocketRequest) open() (*websocket.Conn, net.Conn, error) { client, err := net.DialTimeout("tcp", w.ServerAddr, dialTimeout) if err != nil { return nil, nil, err } conn, err := websocket.NewClient(w.Config, client) if err != nil { return nil, nil, err } return conn, client, err } func createProxyWithForwarder(t *testing.T, uri string, transport http.RoundTripper) *httptest.Server { t.Helper() u := testhelpers.MustParseURL(uri) transportManager := &transportManagerMock{ roundTrippers: map[string]http.RoundTripper{"fwd": transport}, } p, err := NewProxyBuilder(transportManager, nil).Build("fwd", u, true, false, 0) require.NoError(t, err) srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { // keep the original path path := req.URL.Path // Set new backend URL req.URL = u req.URL.Path = path p.ServeHTTP(w, req) })) t.Cleanup(srv.Close) return srv } func createServer(t *testing.T, upgrader gorillawebsocket.Upgrader, check func(*http.Request)) *httptest.Server { t.Helper() srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { conn, err := upgrader.Upgrade(w, r, nil) if err != nil { t.Logf("Error during upgrade: %v", err) return } defer conn.Close() check(r) for { mt, message, err := conn.ReadMessage() if err != nil { t.Logf("Error during read: %v", err) break } err = conn.WriteMessage(mt, message) if err != nil { t.Logf("Error during write: %v", err) break } } })) t.Cleanup(srv.Close) return srv }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/httputil/bufferpool.go
pkg/proxy/httputil/bufferpool.go
package httputil import "sync" const bufferSize = 32 * 1024 type bufferPool struct { pool sync.Pool } func newBufferPool() *bufferPool { b := &bufferPool{ pool: sync.Pool{}, } b.pool.New = func() interface{} { return make([]byte, bufferSize) } return b } func (b *bufferPool) Get() []byte { return b.pool.Get().([]byte) } func (b *bufferPool) Put(bytes []byte) { b.pool.Put(bytes) }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/httputil/proxy_test.go
pkg/proxy/httputil/proxy_test.go
package httputil import ( "crypto/tls" "errors" "net/http" "net/http/httptest" "net/http/httputil" "net/url" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/testhelpers" ) func Test_rewriteRequestBuilder(t *testing.T) { tests := []struct { name string target *url.URL passHostHeader bool preservePath bool incomingURL string expectedScheme string expectedHost string expectedPath string expectedRawPath string expectedQuery string notAppendXFF bool }{ { name: "Basic proxy", target: testhelpers.MustParseURL("http://example.com"), passHostHeader: false, preservePath: false, incomingURL: "http://localhost/test?param=value", expectedScheme: "http", expectedHost: "example.com", expectedPath: "/test", expectedQuery: "param=value", }, { name: "Basic proxy - notAppendXFF", target: testhelpers.MustParseURL("http://example.com"), passHostHeader: false, preservePath: false, incomingURL: "http://localhost/test?param=value", expectedScheme: "http", expectedHost: "example.com", expectedPath: "/test", expectedQuery: "param=value", notAppendXFF: true, }, { name: "HTTPS target", target: testhelpers.MustParseURL("https://secure.example.com"), passHostHeader: false, preservePath: false, incomingURL: "http://localhost/secure", expectedScheme: "https", expectedHost: "secure.example.com", expectedPath: "/secure", }, { name: "PassHostHeader", target: testhelpers.MustParseURL("http://example.com"), passHostHeader: true, preservePath: false, incomingURL: "http://original.host/test", expectedScheme: "http", expectedHost: "original.host", expectedPath: "/test", }, { name: "Preserve path", target: testhelpers.MustParseURL("http://example.com/base"), passHostHeader: false, preservePath: true, incomingURL: "http://localhost/foo%2Fbar", expectedScheme: "http", expectedHost: "example.com", expectedPath: "/base/foo/bar", expectedRawPath: "/base/foo%2Fbar", }, { name: "Handle semicolons in query", target: testhelpers.MustParseURL("http://example.com"), passHostHeader: false, preservePath: false, incomingURL: "http://localhost/test?param1=value1;param2=value2", expectedScheme: "http", expectedHost: "example.com", expectedPath: "/test", expectedQuery: "param1=value1&param2=value2", }, } for _, test := range tests { t.Run(test.name, func(t *testing.T) { t.Parallel() rewriteRequest := rewriteRequestBuilder(test.target, test.passHostHeader, test.preservePath) ctx := t.Context() if test.notAppendXFF { ctx = SetNotAppendXFF(ctx) } reqIn := httptest.NewRequest(http.MethodGet, test.incomingURL, http.NoBody) reqIn = reqIn.WithContext(ctx) reqIn.Header.Add("X-Forwarded-For", "1.2.3.4") reqIn.RemoteAddr = "127.0.0.1:1234" reqOut := httptest.NewRequest(http.MethodGet, test.incomingURL, http.NoBody) pr := &httputil.ProxyRequest{ In: reqIn, Out: reqOut, } rewriteRequest(pr) if test.notAppendXFF { assert.Equal(t, "1.2.3.4", reqOut.Header.Get("X-Forwarded-For")) } else { // When not disabled, X-Forwarded-For should have RemoteAddr appended assert.Equal(t, "1.2.3.4, 127.0.0.1", reqOut.Header.Get("X-Forwarded-For")) } assert.Equal(t, test.expectedScheme, reqOut.URL.Scheme) assert.Equal(t, test.expectedHost, reqOut.Host) assert.Equal(t, test.expectedPath, reqOut.URL.Path) assert.Equal(t, test.expectedRawPath, reqOut.URL.RawPath) assert.Equal(t, test.expectedQuery, reqOut.URL.RawQuery) assert.Empty(t, reqOut.RequestURI) assert.Equal(t, "HTTP/1.1", reqOut.Proto) assert.Equal(t, 1, reqOut.ProtoMajor) assert.Equal(t, 1, reqOut.ProtoMinor) assert.False(t, !test.passHostHeader && reqOut.Host != reqOut.URL.Host) }) } } func Test_isTLSConfigError(t *testing.T) { testCases := []struct { desc string err error expected bool }{ { desc: "nil", }, { desc: "TLS ECHRejectionError", err: &tls.ECHRejectionError{}, }, { desc: "TLS AlertError", err: tls.AlertError(0), }, { desc: "Random error", err: errors.New("random error"), }, { desc: "TLS RecordHeaderError", err: tls.RecordHeaderError{}, expected: true, }, { desc: "TLS CertificateVerificationError", err: &tls.CertificateVerificationError{}, expected: true, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() actual := isTLSConfigError(test.err) require.Equal(t, test.expected, actual) }) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/httputil/builder.go
pkg/proxy/httputil/builder.go
package httputil import ( "crypto/tls" "fmt" "net/http" "net/url" "time" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/observability/metrics" ) // TransportManager manages transport used for backend communications. type TransportManager interface { Get(name string) (*dynamic.ServersTransport, error) GetRoundTripper(name string) (http.RoundTripper, error) GetTLSConfig(name string) (*tls.Config, error) } // ProxyBuilder handles the http.RoundTripper for httputil reverse proxies. type ProxyBuilder struct { bufferPool *bufferPool transportManager TransportManager semConvMetricsRegistry *metrics.SemConvMetricsRegistry } // NewProxyBuilder creates a new ProxyBuilder. func NewProxyBuilder(transportManager TransportManager, semConvMetricsRegistry *metrics.SemConvMetricsRegistry) *ProxyBuilder { return &ProxyBuilder{ bufferPool: newBufferPool(), transportManager: transportManager, semConvMetricsRegistry: semConvMetricsRegistry, } } // Update does nothing. func (r *ProxyBuilder) Update(_ map[string]*dynamic.ServersTransport) {} // Build builds a new httputil.ReverseProxy with the given configuration. func (r *ProxyBuilder) Build(cfgName string, targetURL *url.URL, passHostHeader, preservePath bool, flushInterval time.Duration) (http.Handler, error) { roundTripper, err := r.transportManager.GetRoundTripper(cfgName) if err != nil { return nil, fmt.Errorf("getting RoundTripper: %w", err) } // Wrapping the roundTripper with the Tracing roundTripper, // to create, if necessary, the reverseProxy client span and the semConv client metric. roundTripper = newObservabilityRoundTripper(r.semConvMetricsRegistry, roundTripper) return buildSingleHostProxy(targetURL, passHostHeader, preservePath, flushInterval, roundTripper, r.bufferPool), nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/httputil/observability.go
pkg/proxy/httputil/observability.go
package httputil import ( "context" "fmt" "net" "net/http" "strconv" "strings" "time" "github.com/traefik/traefik/v3/pkg/middlewares/observability" "github.com/traefik/traefik/v3/pkg/observability/metrics" "github.com/traefik/traefik/v3/pkg/observability/tracing" "go.opentelemetry.io/otel/attribute" semconv "go.opentelemetry.io/otel/semconv/v1.37.0" "go.opentelemetry.io/otel/semconv/v1.37.0/httpconv" "go.opentelemetry.io/otel/trace" ) type wrapper struct { semConvMetricRegistry *metrics.SemConvMetricsRegistry rt http.RoundTripper } func newObservabilityRoundTripper(semConvMetricRegistry *metrics.SemConvMetricsRegistry, rt http.RoundTripper) http.RoundTripper { return &wrapper{ semConvMetricRegistry: semConvMetricRegistry, rt: rt, } } func (t *wrapper) RoundTrip(req *http.Request) (*http.Response, error) { start := time.Now() var span trace.Span var tracingCtx context.Context var tracer *tracing.Tracer if tracer = tracing.TracerFromContext(req.Context()); tracer != nil && observability.TracingEnabled(req.Context()) { tracingCtx, span = tracer.Start(req.Context(), "ReverseProxy", trace.WithSpanKind(trace.SpanKindClient)) defer span.End() req = req.WithContext(tracingCtx) tracer.CaptureClientRequest(span, req) tracing.InjectContextIntoCarrier(req) } var statusCode int var headers http.Header response, err := t.rt.RoundTrip(req) if err != nil { statusCode = ComputeStatusCode(err) } if response != nil { statusCode = response.StatusCode headers = response.Header } if tracer != nil { tracer.CaptureResponse(span, headers, statusCode, trace.SpanKindClient) } end := time.Now() // Ending the span as soon as the response is handled because we want to use the same end time for the trace and the metric. // If any errors happen earlier, this span will be close by the defer instruction. if span != nil { span.End(trace.WithTimestamp(end)) } if !observability.SemConvMetricsEnabled(req.Context()) || t.semConvMetricRegistry == nil { return response, err } var attrs []attribute.KeyValue if statusCode < 100 || statusCode >= 600 { attrs = append(attrs, attribute.Key("error.type").String(fmt.Sprintf("Invalid HTTP status code %d", statusCode))) } else if statusCode >= 400 { attrs = append(attrs, attribute.Key("error.type").String(strconv.Itoa(statusCode))) } attrs = append(attrs, semconv.HTTPRequestMethodKey.String(req.Method)) attrs = append(attrs, semconv.HTTPResponseStatusCode(statusCode)) attrs = append(attrs, semconv.NetworkProtocolName(strings.ToLower(req.Proto))) attrs = append(attrs, semconv.NetworkProtocolVersion(observability.Proto(req.Proto))) var serverPort int _, port, splitErr := net.SplitHostPort(req.URL.Host) if splitErr != nil { switch req.URL.Scheme { case "http": serverPort = 80 attrs = append(attrs, semconv.ServerPort(serverPort)) case "https": serverPort = 443 attrs = append(attrs, semconv.ServerPort(serverPort)) } } else { serverPort, _ := strconv.Atoi(port) attrs = append(attrs, semconv.ServerPort(serverPort)) } attrs = append(attrs, semconv.URLScheme(req.Header.Get("X-Forwarded-Proto"))) t.semConvMetricRegistry.HTTPClientRequestDuration().Record(req.Context(), end.Sub(start).Seconds(), httpconv.RequestMethodAttr(req.Method), req.URL.Host, serverPort, attrs...) return response, err }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/proxy/httputil/builder_test.go
pkg/proxy/httputil/builder_test.go
package httputil import ( "crypto/tls" "errors" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/traefik/traefik/v3/pkg/config/dynamic" "github.com/traefik/traefik/v3/pkg/testhelpers" ) func TestEscapedPath(t *testing.T) { var gotEscapedPath string srv := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { gotEscapedPath = req.URL.EscapedPath() })) transportManager := &transportManagerMock{ roundTrippers: map[string]http.RoundTripper{"default": &http.Transport{}}, } p, err := NewProxyBuilder(transportManager, nil).Build("default", testhelpers.MustParseURL(srv.URL), true, false, 0) require.NoError(t, err) proxy := httptest.NewServer(http.HandlerFunc(p.ServeHTTP)) _, err = http.Get(proxy.URL + "/%3A%2F%2F") require.NoError(t, err) assert.Equal(t, "/%3A%2F%2F", gotEscapedPath) } type transportManagerMock struct { roundTrippers map[string]http.RoundTripper } func (t *transportManagerMock) GetRoundTripper(name string) (http.RoundTripper, error) { roundTripper, ok := t.roundTrippers[name] if !ok { return nil, errors.New("no transport for " + name) } return roundTripper, nil } func (t *transportManagerMock) GetTLSConfig(_ string) (*tls.Config, error) { panic("implement me") } func (t *transportManagerMock) Get(_ string) (*dynamic.ServersTransport, error) { panic("implement me") }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/ip/checker.go
pkg/ip/checker.go
package ip import ( "errors" "fmt" "net" "net/netip" "strings" ) // Checker allows to check that addresses are in a trusted IPs. type Checker struct { authorizedIPs []*net.IP authorizedIPsNet []*net.IPNet } // NewChecker builds a new Checker given a list of CIDR-Strings to trusted IPs. func NewChecker(trustedIPs []string) (*Checker, error) { if len(trustedIPs) == 0 { return nil, errors.New("no trusted IPs provided") } checker := &Checker{} for _, ipMask := range trustedIPs { if ipAddr := net.ParseIP(ipMask); ipAddr != nil { checker.authorizedIPs = append(checker.authorizedIPs, &ipAddr) continue } _, ipAddr, err := net.ParseCIDR(ipMask) if err != nil { return nil, fmt.Errorf("parsing CIDR trusted IPs %s: %w", ipAddr, err) } checker.authorizedIPsNet = append(checker.authorizedIPsNet, ipAddr) } return checker, nil } // IsAuthorized checks if provided request is authorized by the trusted IPs. func (ip *Checker) IsAuthorized(addr string) error { var invalidMatches []string host, _, err := net.SplitHostPort(addr) if err != nil { host = addr } ok, err := ip.Contains(host) if err != nil { return err } if !ok { invalidMatches = append(invalidMatches, addr) return fmt.Errorf("%q matched none of the trusted IPs", strings.Join(invalidMatches, ", ")) } return nil } // Contains checks if provided address is in the trusted IPs. func (ip *Checker) Contains(addr string) (bool, error) { if len(addr) == 0 { return false, errors.New("empty IP address") } ipAddr, err := parseIP(addr) if err != nil { return false, fmt.Errorf("unable to parse address: %s: %w", addr, err) } return ip.ContainsIP(ipAddr), nil } // ContainsIP checks if provided address is in the trusted IPs. func (ip *Checker) ContainsIP(addr net.IP) bool { for _, authorizedIP := range ip.authorizedIPs { if authorizedIP.Equal(addr) { return true } } for _, authorizedNet := range ip.authorizedIPsNet { if authorizedNet.Contains(addr) { return true } } return false } func parseIP(addr string) (net.IP, error) { parsedAddr, err := netip.ParseAddr(addr) if err != nil { return nil, fmt.Errorf("can't parse IP from address %s", addr) } ip := parsedAddr.As16() return ip[:], nil }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/ip/checker_test.go
pkg/ip/checker_test.go
package ip import ( "net" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestIsAuthorized(t *testing.T) { testCases := []struct { desc string allowList []string remoteAddr string authorized bool }{ { desc: "remoteAddr not in range", allowList: []string{"1.2.3.4/24"}, remoteAddr: "10.2.3.1:123", authorized: false, }, { desc: "remoteAddr in range", allowList: []string{"1.2.3.4/24"}, remoteAddr: "1.2.3.1:123", authorized: true, }, { desc: "octal ip in remoteAddr", allowList: []string{"127.2.3.4/24"}, remoteAddr: "0127.2.3.1:123", authorized: false, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() ipChecker, err := NewChecker(test.allowList) require.NoError(t, err) err = ipChecker.IsAuthorized(test.remoteAddr) if test.authorized { require.NoError(t, err) } else { require.Error(t, err) } }) } } func TestNew(t *testing.T) { testCases := []struct { desc string trustedIPs []string expectedAuthorizedIPs []*net.IPNet errMessage string }{ { desc: "nil trusted IPs", trustedIPs: nil, expectedAuthorizedIPs: nil, errMessage: "no trusted IPs provided", }, { desc: "empty trusted IPs", trustedIPs: []string{}, expectedAuthorizedIPs: nil, errMessage: "no trusted IPs provided", }, { desc: "trusted IPs containing empty string", trustedIPs: []string{ "1.2.3.4/24", "", "fe80::/16", }, expectedAuthorizedIPs: nil, errMessage: "parsing CIDR trusted IPs <nil>: invalid CIDR address: ", }, { desc: "trusted IPs containing only an empty string", trustedIPs: []string{ "", }, expectedAuthorizedIPs: nil, errMessage: "parsing CIDR trusted IPs <nil>: invalid CIDR address: ", }, { desc: "trusted IPs containing an invalid string", trustedIPs: []string{ "foo", }, expectedAuthorizedIPs: nil, errMessage: "parsing CIDR trusted IPs <nil>: invalid CIDR address: foo", }, { desc: "IPv4 & IPv6 trusted IPs", trustedIPs: []string{ "1.2.3.4/24", "fe80::/16", }, expectedAuthorizedIPs: []*net.IPNet{ {IP: net.IPv4(1, 2, 3, 0).To4(), Mask: net.IPv4Mask(255, 255, 255, 0)}, {IP: net.ParseIP("fe80::"), Mask: net.IPMask(net.ParseIP("ffff::"))}, }, errMessage: "", }, { desc: "IPv4 only", trustedIPs: []string{ "127.0.0.1/8", }, expectedAuthorizedIPs: []*net.IPNet{ {IP: net.IPv4(127, 0, 0, 0).To4(), Mask: net.IPv4Mask(255, 0, 0, 0)}, }, errMessage: "", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() ipChecker, err := NewChecker(test.trustedIPs) if test.errMessage != "" { require.EqualError(t, err, test.errMessage) } else { require.NoError(t, err) for index, actual := range ipChecker.authorizedIPsNet { expected := test.expectedAuthorizedIPs[index] assert.Equal(t, expected.IP, actual.IP) assert.Equal(t, expected.Mask.String(), actual.Mask.String()) } } }) } } func TestContainsIsAllowed(t *testing.T) { testCases := []struct { desc string trustedIPs []string passIPs []string rejectIPs []string }{ { desc: "IPv4", trustedIPs: []string{"1.2.3.4/24"}, passIPs: []string{ "1.2.3.1", "1.2.3.32", "1.2.3.156", "1.2.3.255", }, rejectIPs: []string{ "1.2.16.1", "1.2.32.1", "127.0.0.1", "8.8.8.8", }, }, { desc: "IPv4 single IP", trustedIPs: []string{"8.8.8.8"}, passIPs: []string{"8.8.8.8"}, rejectIPs: []string{ "8.8.8.7", "8.8.8.9", "8.8.8.0", "8.8.8.255", "4.4.4.4", "127.0.0.1", }, }, { desc: "IPv4 Net single IP", trustedIPs: []string{"8.8.8.8/32"}, passIPs: []string{"8.8.8.8"}, rejectIPs: []string{ "8.8.8.7", "8.8.8.9", "8.8.8.0", "8.8.8.255", "4.4.4.4", "127.0.0.1", }, }, { desc: "multiple IPv4", trustedIPs: []string{"1.2.3.4/24", "8.8.8.8/8"}, passIPs: []string{ "1.2.3.1", "1.2.3.32", "1.2.3.156", "1.2.3.255", "8.8.4.4", "8.0.0.1", "8.32.42.128", "8.255.255.255", }, rejectIPs: []string{ "1.2.16.1", "1.2.32.1", "127.0.0.1", "4.4.4.4", "4.8.8.8", }, }, { desc: "IPv6", trustedIPs: []string{"2a03:4000:6:d080::/64"}, passIPs: []string{ "2a03:4000:6:d080::", "2a03:4000:6:d080::1", "2a03:4000:6:d080:dead:beef:ffff:ffff", "2a03:4000:6:d080::42", }, rejectIPs: []string{ "2a03:4000:7:d080::", "2a03:4000:7:d080::1", "fe80::", "4242::1", }, }, { desc: "IPv6 single IP", trustedIPs: []string{"2a03:4000:6:d080::42/128"}, passIPs: []string{"2a03:4000:6:d080::42"}, rejectIPs: []string{ "2a03:4000:6:d080::1", "2a03:4000:6:d080:dead:beef:ffff:ffff", "2a03:4000:6:d080::43", }, }, { desc: "multiple IPv6", trustedIPs: []string{"2a03:4000:6:d080::/64", "fe80::/16"}, passIPs: []string{ "2a03:4000:6:d080::", "2a03:4000:6:d080::1", "2a03:4000:6:d080:dead:beef:ffff:ffff", "2a03:4000:6:d080::42", "fe80::1", "fe80:aa00:00bb:4232:ff00:eeee:00ff:1111", "fe80::fe80", }, rejectIPs: []string{ "2a03:4000:7:d080::", "2a03:4000:7:d080::1", "4242::1", }, }, { desc: "multiple IPv6 & IPv4", trustedIPs: []string{"2a03:4000:6:d080::/64", "fe80::/16", "1.2.3.4/24", "8.8.8.8/8"}, passIPs: []string{ "2a03:4000:6:d080::", "2a03:4000:6:d080::1", "2a03:4000:6:d080:dead:beef:ffff:ffff", "2a03:4000:6:d080::42", "fe80::1", "fe80:aa00:00bb:4232:ff00:eeee:00ff:1111", "fe80:aa00:00bb:4232:ff00:eeee:00ff:1111%vEthernet", "fe80::fe80", "1.2.3.1", "1.2.3.32", "1.2.3.156", "1.2.3.255", "8.8.4.4", "8.0.0.1", "8.32.42.128", "8.255.255.255", }, rejectIPs: []string{ "2a03:4000:7:d080::", "2a03:4000:7:d080::1", "2a03:4000:7:d080::1%vmnet1", "4242::1", "1.2.16.1", "1.2.32.1", "127.0.0.1", "4.4.4.4", "4.8.8.8", }, }, { desc: "broken IP-addresses", trustedIPs: []string{"127.0.0.1/32"}, passIPs: nil, }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() ipChecker, err := NewChecker(test.trustedIPs) require.NoError(t, err) require.NotNil(t, ipChecker) for _, testIP := range test.passIPs { allowed, err := ipChecker.Contains(testIP) require.NoError(t, err) assert.Truef(t, allowed, "%s should have passed.", testIP) } for _, testIP := range test.rejectIPs { allowed, err := ipChecker.Contains(testIP) require.NoError(t, err) assert.Falsef(t, allowed, "%s should not have passed.", testIP) } }) } } func TestContainsBrokenIPs(t *testing.T) { brokenIPs := []string{ "foo", "10.0.0.350", "fe:::80", "", "\\&$§&/(", } ipChecker, err := NewChecker([]string{"1.2.3.4/24"}) require.NoError(t, err) for _, testIP := range brokenIPs { _, err := ipChecker.Contains(testIP) assert.Error(t, err) } }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/ip/strategy.go
pkg/ip/strategy.go
package ip import ( "net" "net/http" "net/netip" "strings" ) const ( xForwardedFor = "X-Forwarded-For" ) // Strategy a strategy for IP selection. type Strategy interface { GetIP(req *http.Request) string } // RemoteAddrStrategy a strategy that always return the remote address. type RemoteAddrStrategy struct { // IPv6Subnet instructs the strategy to return the first IP of the subnet where IP belongs. IPv6Subnet *int } // GetIP returns the selected IP. func (s *RemoteAddrStrategy) GetIP(req *http.Request) string { ip, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { return req.RemoteAddr } if s.IPv6Subnet != nil { return getIPv6SubnetIP(ip, *s.IPv6Subnet) } return ip } // DepthStrategy a strategy based on the depth inside the X-Forwarded-For from right to left. type DepthStrategy struct { Depth int // IPv6Subnet instructs the strategy to return the first IP of the subnet where IP belongs. IPv6Subnet *int } // GetIP returns the selected IP. func (s *DepthStrategy) GetIP(req *http.Request) string { xff := req.Header.Get(xForwardedFor) xffs := strings.Split(xff, ",") if len(xffs) < s.Depth { return "" } ip := strings.TrimSpace(xffs[len(xffs)-s.Depth]) if s.IPv6Subnet != nil { return getIPv6SubnetIP(ip, *s.IPv6Subnet) } return ip } // PoolStrategy is a strategy based on an IP Checker. // It allows to check whether addresses are in a given pool of IPs. type PoolStrategy struct { Checker *Checker } // GetIP checks the list of Forwarded IPs (most recent first) against the // Checker pool of IPs. It returns the first IP that is not in the pool, or the // empty string otherwise. func (s *PoolStrategy) GetIP(req *http.Request) string { if s.Checker == nil { return "" } xff := req.Header.Get(xForwardedFor) xffs := strings.Split(xff, ",") for i := len(xffs) - 1; i >= 0; i-- { xffTrimmed := strings.TrimSpace(xffs[i]) if len(xffTrimmed) == 0 { continue } if contain, _ := s.Checker.Contains(xffTrimmed); !contain { return xffTrimmed } } return "" } // getIPv6SubnetIP returns the IPv6 subnet IP. // It returns the original IP when it is not an IPv6, or if parsing the IP has failed with an error. func getIPv6SubnetIP(ip string, ipv6Subnet int) string { addr, err := netip.ParseAddr(ip) if err != nil { return ip } if !addr.Is6() { return ip } prefix, err := addr.Prefix(ipv6Subnet) if err != nil { return ip } return prefix.Addr().String() }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/ip/strategy_test.go
pkg/ip/strategy_test.go
package ip import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) const ( ipv6Basic = "::abcd:ffff:c0a8:1" ipv6BracketsPort = "[::abcd:ffff:c0a8:1]:80" ipv6BracketsZonePort = "[::abcd:ffff:c0a8:1%1]:80" ) func TestRemoteAddrStrategy_GetIP(t *testing.T) { testCases := []struct { desc string expected string remoteAddr string ipv6Subnet *int }{ // Valid IP format { desc: "Use RemoteAddr, ipv4", expected: "192.0.2.1", }, { desc: "Use RemoteAddr, ipv6 brackets with port, no IPv6 subnet", remoteAddr: ipv6BracketsPort, expected: "::abcd:ffff:c0a8:1", }, { desc: "Use RemoteAddr, ipv6 brackets with zone and port, no IPv6 subnet", remoteAddr: ipv6BracketsZonePort, expected: "::abcd:ffff:c0a8:1%1", }, // Invalid IPv6 format { desc: "Use RemoteAddr, ipv6 basic, missing brackets, no IPv6 subnet", remoteAddr: ipv6Basic, expected: ipv6Basic, }, // Valid IP format with subnet { desc: "Use RemoteAddr, ipv4, ignore subnet", expected: "192.0.2.1", ipv6Subnet: intPtr(24), }, { desc: "Use RemoteAddr, ipv6 brackets with port, subnet", remoteAddr: ipv6BracketsPort, expected: "::abcd:0:0:0", ipv6Subnet: intPtr(80), }, { desc: "Use RemoteAddr, ipv6 brackets with zone and port, subnet", remoteAddr: ipv6BracketsZonePort, expected: "::abcd:0:0:0", ipv6Subnet: intPtr(80), }, // Valid IP, invalid subnet { desc: "Use RemoteAddr, ipv6 brackets with port, invalid subnet", remoteAddr: ipv6BracketsPort, expected: "::abcd:ffff:c0a8:1", ipv6Subnet: intPtr(500), }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() strategy := RemoteAddrStrategy{ IPv6Subnet: test.ipv6Subnet, } req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1", nil) if test.remoteAddr != "" { req.RemoteAddr = test.remoteAddr } actual := strategy.GetIP(req) assert.Equal(t, test.expected, actual) }) } } func TestDepthStrategy_GetIP(t *testing.T) { testCases := []struct { desc string depth int xForwardedFor string expected string ipv6Subnet *int }{ { desc: "Use depth", depth: 3, xForwardedFor: "10.0.0.4,10.0.0.3,10.0.0.2,10.0.0.1", expected: "10.0.0.3", }, { desc: "Use nonexistent depth in XForwardedFor", depth: 2, xForwardedFor: "", expected: "", }, { desc: "Use depth that match the first IP in XForwardedFor", depth: 2, xForwardedFor: "10.0.0.2,10.0.0.1", expected: "10.0.0.2", }, { desc: "Use depth with IPv4 subnet", depth: 2, xForwardedFor: "10.0.0.3,10.0.0.2,10.0.0.1", expected: "10.0.0.2", ipv6Subnet: intPtr(80), }, { desc: "Use depth with IPv6 subnet", depth: 2, xForwardedFor: "10.0.0.3," + ipv6Basic + ",10.0.0.1", expected: "::abcd:0:0:0", ipv6Subnet: intPtr(80), }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() strategy := DepthStrategy{ Depth: test.depth, IPv6Subnet: test.ipv6Subnet, } req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1", nil) req.Header.Set(xForwardedFor, test.xForwardedFor) actual := strategy.GetIP(req) assert.Equal(t, test.expected, actual) }) } } func TestTrustedIPsStrategy_GetIP(t *testing.T) { testCases := []struct { desc string trustedIPs []string xForwardedFor string expected string useRemote bool }{ { desc: "Trust all IPs", trustedIPs: []string{"10.0.0.4", "10.0.0.3", "10.0.0.2", "10.0.0.1"}, xForwardedFor: "10.0.0.4,10.0.0.3,10.0.0.2,10.0.0.1", expected: "", }, { desc: "Do not trust all IPs", trustedIPs: []string{"10.0.0.2", "10.0.0.1"}, xForwardedFor: "10.0.0.4,10.0.0.3,10.0.0.2,10.0.0.1", expected: "10.0.0.3", }, { desc: "Do not trust all IPs with CIDR", trustedIPs: []string{"10.0.0.1/24"}, xForwardedFor: "127.0.0.1,10.0.0.4,10.0.0.3,10.0.0.2,10.0.0.1", expected: "127.0.0.1", }, { desc: "Trust all IPs with CIDR", trustedIPs: []string{"10.0.0.1/24"}, xForwardedFor: "10.0.0.4,10.0.0.3,10.0.0.2,10.0.0.1", expected: "", }, } for _, test := range testCases { t.Run(test.desc, func(t *testing.T) { t.Parallel() checker, err := NewChecker(test.trustedIPs) require.NoError(t, err) strategy := PoolStrategy{Checker: checker} req := httptest.NewRequest(http.MethodGet, "http://127.0.0.1", nil) req.Header.Set(xForwardedFor, test.xForwardedFor) actual := strategy.GetIP(req) assert.Equal(t, test.expected, actual) }) } } func intPtr(value int) *int { return &value }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false
traefik/traefik
https://github.com/traefik/traefik/blob/f7280439e6378221a541910f43a01323d52db048/pkg/testhelpers/metrics.go
pkg/testhelpers/metrics.go
package testhelpers import "github.com/go-kit/kit/metrics" // CollectingCounter is a metrics.Counter implementation that enables access to the CounterValue and LastLabelValues. type CollectingCounter struct { CounterValue float64 LastLabelValues []string } // With is there to satisfy the metrics.Counter interface. func (c *CollectingCounter) With(labelValues ...string) metrics.Counter { c.LastLabelValues = labelValues return c } // Add is there to satisfy the metrics.Counter interface. func (c *CollectingCounter) Add(delta float64) { c.CounterValue += delta } // CollectingGauge is a metrics.Gauge implementation that enables access to the GaugeValue and LastLabelValues. type CollectingGauge struct { GaugeValue float64 LastLabelValues []string } // With is there to satisfy the metrics.Gauge interface. func (g *CollectingGauge) With(labelValues ...string) metrics.Gauge { g.LastLabelValues = labelValues return g } // Set is there to satisfy the metrics.Gauge interface. func (g *CollectingGauge) Set(value float64) { g.GaugeValue = value } // Add is there to satisfy the metrics.Gauge interface. func (g *CollectingGauge) Add(delta float64) { g.GaugeValue = delta } // CollectingHealthCheckMetrics can be used for testing the Metrics instrumentation of the HealthCheck package. type CollectingHealthCheckMetrics struct { Gauge *CollectingGauge } // BackendServerUpGauge is there to satisfy the healthcheck.metricsRegistry interface. func (m *CollectingHealthCheckMetrics) BackendServerUpGauge() metrics.Gauge { return m.Gauge } // NewCollectingHealthCheckMetrics creates a new CollectingHealthCheckMetrics instance. func NewCollectingHealthCheckMetrics() *CollectingHealthCheckMetrics { return &CollectingHealthCheckMetrics{&CollectingGauge{}} }
go
MIT
f7280439e6378221a541910f43a01323d52db048
2026-01-07T08:35:43.502324Z
false