normalizeOrigin checks if the provided origin is in a correct format and normalizes it by removing any path or trailing slash. It returns a boolean indicating whether the origin is valid and the normalized origin.
(origin string)
| 12 | // It returns a boolean indicating whether the origin is valid |
| 13 | // and the normalized origin. |
| 14 | func normalizeOrigin(origin string) (valid bool, normalized string) { //nolint:nonamedreturns // gocritic unnamedResult prefers naming validity and normalized origin results |
| 15 | parsedOrigin, err := url.Parse(origin) |
| 16 | if err != nil { |
| 17 | return false, "" |
| 18 | } |
| 19 | |
| 20 | // Don't allow a wildcard with a protocol |
| 21 | // wildcards cannot be used within any other value. For example, the following header is not valid: |
| 22 | // Access-Control-Allow-Origin: https://* |
| 23 | if strings.IndexByte(parsedOrigin.Host, '*') >= 0 { |
| 24 | return false, "" |
| 25 | } |
| 26 | |
| 27 | // Validate there is a host present. The presence of a path, query, or fragment components |
| 28 | // is checked, but a trailing "/" (indicative of the root) is allowed for the path and will be normalized |
| 29 | if parsedOrigin.User != nil || |
| 30 | parsedOrigin.Host == "" || |
| 31 | (parsedOrigin.Path != "" && parsedOrigin.Path != "/") || |
| 32 | parsedOrigin.RawQuery != "" || |
| 33 | parsedOrigin.Fragment != "" { |
| 34 | return false, "" |
| 35 | } |
| 36 | |
| 37 | // Normalize the origin by constructing it from the scheme and host. |
| 38 | // The path or trailing slash is not included in the normalized origin. |
| 39 | return true, utilsstrings.ToLower(parsedOrigin.Scheme) + "://" + utilsstrings.ToLower(parsedOrigin.Host) |
| 40 | } |
| 41 | |
| 42 | type subdomain struct { |
| 43 | // The wildcard pattern |