| 1 | package config |
| 2 | |
| 3 | import ( |
| 4 | "encoding/base64" |
| 5 | "strings" |
| 6 | ) |
| 7 | |
| 8 | const ( |
| 9 | APITag = "API" |
| 10 | AuthorizationTag = "Authorizations" |
| 11 | ) |
| 12 | |
| 13 | type RPCAuthScope struct { |
| 14 | // AuthSecret is the secret that will be compared to the HTTP "Authorization". |
| 15 | // header. A secret is in the format "type:value". Check the documentation for |
| 16 | // supported types. |
| 17 | AuthSecret string |
| 18 | |
| 19 | // AllowedPaths is an explicit list of RPC path prefixes to allow. |
| 20 | // By default, none are allowed. ["/api/v0"] exposes all RPCs. |
| 21 | AllowedPaths []string |
| 22 | } |
| 23 | |
| 24 | type API struct { |
| 25 | // HTTPHeaders are the HTTP headers to return with the API. |
| 26 | HTTPHeaders map[string][]string |
| 27 | |
| 28 | // Authorization is a map of authorizations used to authenticate in the API. |
| 29 | // If the map is empty, then the RPC API is exposed to everyone. Check the |
| 30 | // documentation for more details. |
| 31 | Authorizations map[string]*RPCAuthScope `json:",omitempty"` |
| 32 | } |
| 33 | |
| 34 | // ConvertAuthSecret converts the given secret in the format "type:value" into an |
| 35 | // HTTP Authorization header value. It can handle 'bearer' and 'basic' as type. |
| 36 | // If type exists and is not known, an empty string is returned. If type does not |
| 37 | // exist, 'bearer' type is assumed. |
| 38 | func ConvertAuthSecret(secret string) string { |
| 39 | if secret == "" { |
| 40 | return secret |
| 41 | } |
| 42 | |
| 43 | split := strings.SplitN(secret, ":", 2) |
| 44 | if len(split) < 2 { |
| 45 | // No prefix: assume bearer token. |
| 46 | return "Bearer " + secret |
| 47 | } |
| 48 | |
| 49 | if strings.HasPrefix(secret, "basic:") { |
| 50 | if strings.Contains(split[1], ":") { |
| 51 | // Assume basic:user:password |
| 52 | return "Basic " + base64.StdEncoding.EncodeToString([]byte(split[1])) |
| 53 | } else { |
| 54 | // Assume already base64 encoded. |
| 55 | return "Basic " + split[1] |
| 56 | } |
| 57 | } else if strings.HasPrefix(secret, "bearer:") { |
| 58 | return "Bearer " + split[1] |
| 59 | } |
| 60 | |
| 61 | // Unknown. Type is present, but we can't handle it. |
| 62 | return "" |
| 63 | } |