github.com/xmidt-org/webpa-common@v1.11.9/secure/tools/cmd/keyserver/configuration.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "errors" 6 "fmt" 7 "github.com/xmidt-org/webpa-common/resource" 8 "io/ioutil" 9 "strings" 10 ) 11 12 const ( 13 DefaultIssuer = "test" 14 DefaultBits = 4096 15 DefaultBindAddress = ":8080" 16 ) 17 18 var ( 19 ErrorNoKeys = errors.New("No keys found in configuration") 20 ErrorBlankKeyId = errors.New("Blank key identifiers are not allowed") 21 ErrorInvalidKeyId = errors.New("Key identifiers cannot have leading or trailing whitespace") 22 ErrorNoConfiguration = errors.New("A configuration file is required") 23 ) 24 25 // Configuration provides the basic, JSON-marshallable configuration for 26 // the keyserver. 27 type Configuration struct { 28 // Issuer is the string used for the iss field for any JWTs issued 29 // by this server. If not supplied, DefaultIssuer is used. 30 Issuer string `json:"issuer"` 31 32 // BindAddress is the local address on which the server listens 33 BindAddress string `json:"bindAddress"` 34 35 // Keys stores information about all the keys known to this server. 36 Keys map[string]*resource.Factory `json:"keys"` 37 38 // Bits is the bit length of any keys generated by the server. 39 // If this value is non-positive, DefaultBits is used 40 Bits int `json:"bits"` 41 42 // Generate is a list of key identifiers which will be generated 43 // each time this server starts. 44 Generate []string `json:"generate"` 45 } 46 47 func (c *Configuration) Validate() error { 48 if len(c.Keys) == 0 && len(c.Generate) == 0 { 49 return ErrorNoKeys 50 } 51 52 for keyID := range c.Keys { 53 trimmedKeyId := strings.TrimSpace(keyID) 54 if len(trimmedKeyId) == 0 { 55 return ErrorBlankKeyId 56 } else if trimmedKeyId != keyID { 57 return ErrorInvalidKeyId 58 } 59 } 60 61 for _, keyID := range c.Generate { 62 trimmedKeyId := strings.TrimSpace(keyID) 63 if len(trimmedKeyId) == 0 { 64 return ErrorBlankKeyId 65 } else if trimmedKeyId != keyID { 66 return ErrorInvalidKeyId 67 } 68 69 if _, ok := c.Keys[keyID]; ok { 70 return fmt.Errorf("Key %s is ambiguous: it occurs in keys and generate", keyID) 71 } 72 } 73 74 return nil 75 } 76 77 func ParseConfiguration(configurationFileName string) (*Configuration, error) { 78 if len(configurationFileName) == 0 { 79 return nil, ErrorNoConfiguration 80 } 81 82 contents, err := ioutil.ReadFile(configurationFileName) 83 if err != nil { 84 return nil, err 85 } 86 87 var configuration Configuration 88 err = json.Unmarshal(contents, &configuration) 89 if err != nil { 90 return nil, err 91 } 92 93 return &configuration, nil 94 }