| 130 | } |
| 131 | |
| 132 | func (sr *SignRequest) Sign(ctx context.Context) (signedJSON string, err error) { |
| 133 | trimmedJSON := strings.TrimRightFunc(sr.UnsignedJSON, unicode.IsSpace) |
| 134 | |
| 135 | // TODO: make sure these return different things |
| 136 | inputfail := func(msg string) (string, error) { |
| 137 | return "", errors.New(msg) |
| 138 | } |
| 139 | execfail := func(msg string) (string, error) { |
| 140 | return "", errors.New(msg) |
| 141 | } |
| 142 | |
| 143 | jmap := make(map[string]interface{}) |
| 144 | if err := json.Unmarshal([]byte(trimmedJSON), &jmap); err != nil { |
| 145 | return inputfail("json parse error") |
| 146 | } |
| 147 | |
| 148 | camliSigner, hasSigner := jmap["camliSigner"] |
| 149 | if !hasSigner { |
| 150 | return inputfail("json lacks \"camliSigner\" key with public key blobref") |
| 151 | } |
| 152 | |
| 153 | camliSignerStr, _ := camliSigner.(string) |
| 154 | signerBlob, ok := blob.Parse(camliSignerStr) |
| 155 | if !ok { |
| 156 | return inputfail("json \"camliSigner\" key is malformed or unsupported") |
| 157 | } |
| 158 | |
| 159 | pubkeyReader, _, err := sr.Fetcher.Fetch(ctx, signerBlob) |
| 160 | if err != nil { |
| 161 | // TODO: not really either an inputfail or an execfail.. but going |
| 162 | // with exec for now. |
| 163 | return execfail(fmt.Sprintf("failed to find public key %s: %v", signerBlob.String(), err)) |
| 164 | } |
| 165 | |
| 166 | pubk, err := openArmoredPublicKeyFile(pubkeyReader) |
| 167 | pubkeyReader.Close() |
| 168 | if err != nil { |
| 169 | return execfail(fmt.Sprintf("failed to parse public key from blobref %s: %v", signerBlob.String(), err)) |
| 170 | } |
| 171 | |
| 172 | // This check should be redundant if the above JSON parse succeeded, but |
| 173 | // for explicitness... |
| 174 | if len(trimmedJSON) == 0 || trimmedJSON[len(trimmedJSON)-1] != '}' { |
| 175 | return inputfail("json parameter lacks trailing '}'") |
| 176 | } |
| 177 | trimmedJSON = trimmedJSON[0 : len(trimmedJSON)-1] |
| 178 | |
| 179 | // sign it |
| 180 | entityFetcher := sr.EntityFetcher |
| 181 | if entityFetcher == nil { |
| 182 | file := sr.secretRingPath() |
| 183 | if file == "" { |
| 184 | return "", errors.New("jsonsign: no EntityFetcher, and no secret ring file defined") |
| 185 | } |
| 186 | secring, err := wkfs.Open(sr.secretRingPath()) |
| 187 | if err != nil { |
| 188 | return "", fmt.Errorf("jsonsign: failed to open secret ring file %q: %v", sr.secretRingPath(), err) |
| 189 | } |