David K. Bainbridge | 215e024 | 2017-09-05 23:18:24 -0700 | [diff] [blame] | 1 | package libtrust |
| 2 | |
| 3 | import ( |
| 4 | "path/filepath" |
| 5 | ) |
| 6 | |
| 7 | // FilterByHosts filters the list of PublicKeys to only those which contain a |
| 8 | // 'hosts' pattern which matches the given host. If *includeEmpty* is true, |
| 9 | // then keys which do not specify any hosts are also returned. |
| 10 | func FilterByHosts(keys []PublicKey, host string, includeEmpty bool) ([]PublicKey, error) { |
| 11 | filtered := make([]PublicKey, 0, len(keys)) |
| 12 | |
| 13 | for _, pubKey := range keys { |
| 14 | var hosts []string |
| 15 | switch v := pubKey.GetExtendedField("hosts").(type) { |
| 16 | case []string: |
| 17 | hosts = v |
| 18 | case []interface{}: |
| 19 | for _, value := range v { |
| 20 | h, ok := value.(string) |
| 21 | if !ok { |
| 22 | continue |
| 23 | } |
| 24 | hosts = append(hosts, h) |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | if len(hosts) == 0 { |
| 29 | if includeEmpty { |
| 30 | filtered = append(filtered, pubKey) |
| 31 | } |
| 32 | continue |
| 33 | } |
| 34 | |
| 35 | // Check if any hosts match pattern |
| 36 | for _, hostPattern := range hosts { |
| 37 | match, err := filepath.Match(hostPattern, host) |
| 38 | if err != nil { |
| 39 | return nil, err |
| 40 | } |
| 41 | |
| 42 | if match { |
| 43 | filtered = append(filtered, pubKey) |
| 44 | continue |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | return filtered, nil |
| 50 | } |