blob: 5b2b4fca6fb07ea30c3bb312b9fb4f55335ca549 [file] [log] [blame]
David K. Bainbridge215e0242017-09-05 23:18:24 -07001package libtrust
2
3import (
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.
10func 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}