| @@ -4,6 +4,7 @@ import ( |
| 4 | "fmt" | 4 | "fmt" |
| 5 | "io" | 5 | "io" |
| 6 | "net/http" | 6 | "net/http" |
| | 7 | +added: "sort" |
| 7 | "strings" | 8 | "strings" |
| 8 | | 9 | |
| 9 | regexp "github.com/wasilibs/go-re2" | 10 | regexp "github.com/wasilibs/go-re2" |
| @@ -38,45 +39,93 @@ var ( |
| 38 | | 39 | |
| 39 | // FindTenantIdMatches returns a list of potential tenant IDs in the provided |data|. | 40 | // FindTenantIdMatches returns a list of potential tenant IDs in the provided |data|. |
| 40 | func FindTenantIdMatches(data string) map[string]struct{} { | 41 | func FindTenantIdMatches(data string) map[string]struct{} { |
| 41 | −removed: uniqueMatches := make(map[string]struct{}) | 42 | +added: return offsetsToSet(FindTenantIdOffsets(data)) |
| 42 | −removed: | 43 | +added: } |
| 43 | −removed: for _, match := range tenantIdPat.FindAllStringSubmatch(data, -1) { | 44 | +added: |
| 44 | −removed: var m string | 45 | +added: // FindTenantIdOffsets returns potential tenant IDs in |data|, mapped to the byte offsets where each was found. |
| 45 | −removed: if match[1] != "" { | 46 | +added: func FindTenantIdOffsets(data string) map[string][]int { |
| 46 | −removed: m = strings.ToLower(match[1]) | 47 | +added: matches := make(map[string][]int) |
| 47 | −removed: } else if match[2] != "" { | 48 | +added: |
| 48 | −removed: m = strings.ToLower(match[2]) | 49 | +added: for _, idx := range tenantIdPat.FindAllStringSubmatchIndex(data, -1) { |
| 49 | −removed: } else if match[3] != "" { | 50 | +added: // The pattern has four alternative capture groups; use the one that matched. |
| 50 | −removed: m = strings.ToLower(match[3]) | 51 | +added: for group := 1; group <= 4; group++ { |
| 51 | −removed: } else if match[4] != "" { | 52 | +added: start, end := idx[2*group], idx[2*group+1] |
| 52 | −removed: m = strings.ToLower(match[4]) | 53 | +added: if start < 0 { |
| 53 | −removed: } | 54 | +added: continue |
| 54 | −removed: if _, ok := detectors.UuidFalsePositives[detectors.FalsePositive(m)]; ok { | 55 | +added: } |
| 55 | −removed: continue | 56 | +added: m := strings.ToLower(data[start:end]) |
| 56 | −removed: } else if detectors.StringShannonEntropy(m) < 3 { | 57 | +added: if isLikelyId(m) { |
| 57 | −removed: continue | 58 | +added: matches[m] = append(matches[m], start) |
| | 59 | +added: } |
| | 60 | +added: break |
| 58 | } | 61 | } |
| 59 | −removed: uniqueMatches[m] = struct{}{} | | |
| 60 | } | 62 | } |
| 61 | −removed: for _, match := range tenantOnMicrosoftPat.FindAllStringSubmatch(data, -1) { | 63 | +added: for _, idx := range tenantOnMicrosoftPat.FindAllStringSubmatchIndex(data, -1) { |
| 62 | −removed: uniqueMatches[match[1]] = struct{}{} | 64 | +added: m := data[idx[2]:idx[3]] |
| | 65 | +added: matches[m] = append(matches[m], idx[2]) |
| 63 | } | 66 | } |
| 64 | −removed: return uniqueMatches | 67 | +added: return matches |
| 65 | } | 68 | } |
| 66 | | 69 | |
| 67 | // FindClientIdMatches returns a list of potential client UUIDs in the provided |data|. | 70 | // FindClientIdMatches returns a list of potential client UUIDs in the provided |data|. |
| 68 | func FindClientIdMatches(data string) map[string]struct{} { | 71 | func FindClientIdMatches(data string) map[string]struct{} { |
| 69 | −removed: uniqueMatches := make(map[string]struct{}) | 72 | +added: return offsetsToSet(FindClientIdOffsets(data)) |
| 70 | −removed: for _, match := range clientIdPat.FindAllStringSubmatch(data, -1) { | 73 | +added: } |
| 71 | −removed: m := strings.ToLower(match[1]) | 74 | +added: |
| 72 | −removed: if _, ok := detectors.UuidFalsePositives[detectors.FalsePositive(m)]; ok { | 75 | +added: // FindClientIdOffsets returns potential client UUIDs in |data|, mapped to the byte offsets where each was found. |
| 73 | −removed: continue | 76 | +added: func FindClientIdOffsets(data string) map[string][]int { |
| 74 | −removed: } else if detectors.StringShannonEntropy(m) < 3 { | 77 | +added: matches := make(map[string][]int) |
| 75 | −removed: continue | 78 | +added: for _, idx := range clientIdPat.FindAllStringSubmatchIndex(data, -1) { |
| | 79 | +added: m := strings.ToLower(data[idx[2]:idx[3]]) |
| | 80 | +added: if isLikelyId(m) { |
| | 81 | +added: matches[m] = append(matches[m], idx[2]) |
| 76 | } | 82 | } |
| 77 | −removed: uniqueMatches[m] = struct{}{} | | |
| 78 | } | 83 | } |
| 79 | −removed: return uniqueMatches | 84 | +added: return matches |
| | 85 | +added: } |
| | 86 | +added: |
| | 87 | +added: // NearestFirst returns the keys of |candidates| ordered by their distance to |pos|. |
| | 88 | +added: // A candidate's distance is that of its closest occurrence. Ties are broken by value so the order is stable. |
| | 89 | +added: func NearestFirst(candidates map[string][]int, pos int) []string { |
| | 90 | +added: distances := make(map[string]int, len(candidates)) |
| | 91 | +added: ordered := make([]string, 0, len(candidates)) |
| | 92 | +added: for value, offsets := range candidates { |
| | 93 | +added: closest := -1 |
| | 94 | +added: for _, offset := range offsets { |
| | 95 | +added: d := offset - pos |
| | 96 | +added: if d < 0 { |
| | 97 | +added: d = -d |
| | 98 | +added: } |
| | 99 | +added: if closest < 0 || d < closest { |
| | 100 | +added: closest = d |
| | 101 | +added: } |
| | 102 | +added: } |
| | 103 | +added: distances[value] = closest |
| | 104 | +added: ordered = append(ordered, value) |
| | 105 | +added: } |
| | 106 | +added: sort.Slice(ordered, func(i, j int) bool { |
| | 107 | +added: if distances[ordered[i]] != distances[ordered[j]] { |
| | 108 | +added: return distances[ordered[i]] < distances[ordered[j]] |
| | 109 | +added: } |
| | 110 | +added: return ordered[i] < ordered[j] |
| | 111 | +added: }) |
| | 112 | +added: return ordered |
| | 113 | +added: } |
| | 114 | +added: |
| | 115 | +added: // isLikelyId filters out well-known placeholder UUIDs and low-entropy values. |
| | 116 | +added: func isLikelyId(m string) bool { |
| | 117 | +added: if _, ok := detectors.UuidFalsePositives[detectors.FalsePositive(m)]; ok { |
| | 118 | +added: return false |
| | 119 | +added: } |
| | 120 | +added: return detectors.StringShannonEntropy(m) >= 3 |
| | 121 | +added: } |
| | 122 | +added: |
| | 123 | +added: func offsetsToSet(offsets map[string][]int) map[string]struct{} { |
| | 124 | +added: set := make(map[string]struct{}, len(offsets)) |
| | 125 | +added: for value := range offsets { |
| | 126 | +added: set[value] = struct{}{} |
| | 127 | +added: } |
| | 128 | +added: return set |
| 80 | } | 129 | } |
| 81 | | 130 | |
| 82 | var ( | 131 | var ( |
| @@ -85,35 +134,42 @@ var ( |
| 85 | ) | 134 | ) |
| 86 | | 135 | |
| 87 | // TenantExists returns whether the tenant exists according to Microsoft's well-known OpenID endpoint. | 136 | // TenantExists returns whether the tenant exists according to Microsoft's well-known OpenID endpoint. |
| 88 | −removed: func TenantExists(ctx context.Context, client *http.Client, tenant string) bool { | 137 | +added: // A non-nil error means the answer is unknown (e.g., a network failure); it is not cached. |
| | 138 | +added: func TenantExists(ctx context.Context, client *http.Client, tenant string) (bool, error) { |
| 89 | // Use cached value where possible. | 139 | // Use cached value where possible. |
| 90 | if tenantExists, isCached := tenantCache.Get(tenant); isCached { | 140 | if tenantExists, isCached := tenantCache.Get(tenant); isCached { |
| 91 | −removed: return tenantExists | 141 | +added: return tenantExists, nil |
| 92 | } | 142 | } |
| 93 | | 143 | |
| 94 | // https://www.codingexplorations.com/blog/understanding-singleflight-in-golang-a-solution-for-eliminating-redundant-work | 144 | // https://www.codingexplorations.com/blog/understanding-singleflight-in-golang-a-solution-for-eliminating-redundant-work |
| 95 | −removed: tenantExists, _, _ := tenantGroup.Do(tenant, func() (interface{}, error) { | 145 | +added: tenantExists, err, _ := tenantGroup.Do(tenant, func() (interface{}, error) { |
| 96 | −removed: result := queryTenant(ctx, client, tenant) | 146 | +added: result, err := queryTenant(ctx, client, tenant) |
| 97 | −removed: tenantCache.Set(tenant, result) | 147 | +added: // Only remember definite answers, so a transient failure doesn't stick. |
| 98 | −removed: return result, nil | 148 | +added: if err == nil { |
| | 149 | +added: tenantCache.Set(tenant, result) |
| | 150 | +added: } |
| | 151 | +added: return result, err |
| 99 | }) | 152 | }) |
| | 153 | +added: if err != nil { |
| | 154 | +added: return false, err |
| | 155 | +added: } |
| 100 | | 156 | |
| 101 | −removed: return tenantExists.(bool) | 157 | +added: return tenantExists.(bool), nil |
| 102 | } | 158 | } |
| 103 | | 159 | |
| 104 | −removed: func queryTenant(ctx context.Context, client *http.Client, tenant string) bool { | 160 | +added: func queryTenant(ctx context.Context, client *http.Client, tenant string) (bool, error) { |
| 105 | logger := ctx.Logger().WithName("azure").WithValues("tenant", tenant) | 161 | logger := ctx.Logger().WithName("azure").WithValues("tenant", tenant) |
| 106 | | 162 | |
| 107 | tenantUrl := fmt.Sprintf("https://login.microsoftonline.com/%s/.well-known/openid-configuration", tenant) | 163 | tenantUrl := fmt.Sprintf("https://login.microsoftonline.com/%s/.well-known/openid-configuration", tenant) |
| 108 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, tenantUrl, nil) | 164 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, tenantUrl, nil) |
| 109 | if err != nil { | 165 | if err != nil { |
| 110 | −removed: return false | 166 | +added: return false, err |
| 111 | } | 167 | } |
| 112 | | 168 | |
| 113 | res, err := client.Do(req) | 169 | res, err := client.Do(req) |
| 114 | if err != nil { | 170 | if err != nil { |
| 115 | logger.Error(err, "Failed to check if tenant exists") | 171 | logger.Error(err, "Failed to check if tenant exists") |
| 116 | −removed: return false | 172 | +added: return false, err |
| 117 | } | 173 | } |
| 118 | defer func() { | 174 | defer func() { |
| 119 | _, _ = io.Copy(io.Discard, res.Body) | 175 | _, _ = io.Copy(io.Discard, res.Body) |
| @@ -122,13 +178,13 @@ func queryTenant(ctx context.Context, client *http.Client, tenant string) bool { |
| 122 | | 178 | |
| 123 | switch res.StatusCode { | 179 | switch res.StatusCode { |
| 124 | case http.StatusOK: | 180 | case http.StatusOK: |
| 125 | −removed: return true | 181 | +added: return true, nil |
| 126 | case http.StatusBadRequest: | 182 | case http.StatusBadRequest: |
| 127 | logger.V(4).Info("Tenant does not exist.") | 183 | logger.V(4).Info("Tenant does not exist.") |
| 128 | −removed: return false | 184 | +added: return false, nil |
| 129 | default: | 185 | default: |
| 130 | bodyBytes, _ := io.ReadAll(res.Body) | 186 | bodyBytes, _ := io.ReadAll(res.Body) |
| 131 | logger.Error(nil, "WARNING: Unexpected response when checking if tenant exists", "status_code", res.StatusCode, "body", string(bodyBytes)) | 187 | logger.Error(nil, "WARNING: Unexpected response when checking if tenant exists", "status_code", res.StatusCode, "body", string(bodyBytes)) |
| 132 | −removed: return false | 188 | +added: return false, fmt.Errorf("unexpected status %d checking tenant", res.StatusCode) |
| 133 | } | 189 | } |
| 134 | } | 190 | } |