| 16 | var errWrongFormat = errors.New("key in wrong format") |
| 17 | |
| 18 | func gpgKeyUpload(httpClient *http.Client, hostname string, keyFile io.Reader, title string) error { |
| 19 | keyBytes, err := io.ReadAll(keyFile) |
| 20 | if err != nil { |
| 21 | return err |
| 22 | } |
| 23 | |
| 24 | payload := map[string]string{ |
| 25 | "armored_public_key": string(keyBytes), |
| 26 | } |
| 27 | if title != "" { |
| 28 | payload["name"] = title |
| 29 | } |
| 30 | |
| 31 | payloadBytes, err := json.Marshal(payload) |
| 32 | if err != nil { |
| 33 | return err |
| 34 | } |
| 35 | |
| 36 | path, err := safeurl.JoinPath("user", "gpg_keys") |
| 37 | if err != nil { |
| 38 | return err |
| 39 | } |
| 40 | |
| 41 | // TODO(api-client-rollout) |
| 42 | // This line of code is part of a mechanical roll out of the api client. |
| 43 | // As a follow up, consider whether the api client can be injected to this call site, rather than constructed |
| 44 | apiClient := api.NewClientFromHTTP(httpClient) |
| 45 | err = apiClient.REST(hostname, "POST", path.String(), bytes.NewBuffer(payloadBytes), nil) |
| 46 | if err != nil { |
| 47 | if httpError, ok := errors.AsType[api.HTTPError](err); ok { |
| 48 | if httpError.StatusCode == 404 { |
| 49 | return errScopesMissing |
| 50 | } |
| 51 | for _, e := range httpError.Errors { |
| 52 | if httpError.StatusCode == 422 && e.Field == "key_id" && e.Message == "key_id already exists" { |
| 53 | return errDuplicateKey |
| 54 | } |
| 55 | } |
| 56 | if httpError.StatusCode == 422 && !isGpgKeyArmored(keyBytes) { |
| 57 | return errWrongFormat |
| 58 | } |
| 59 | } |
| 60 | return err |
| 61 | } |
| 62 | |
| 63 | return nil |
| 64 | } |
| 65 | |
| 66 | func isGpgKeyArmored(keyBytes []byte) bool { |
| 67 | return bytes.Contains(keyBytes, []byte("-----BEGIN ")) |