RevokeToken deletes one access token belonging to the GitHub CLI OAuth app. The client must not attach user authentication or log credential-bearing bodies.
(ctx context.Context, client *http.Client, hostname, token string)
| 22 | // RevokeToken deletes one access token belonging to the GitHub CLI OAuth app. |
| 23 | // The client must not attach user authentication or log credential-bearing bodies. |
| 24 | func RevokeToken(ctx context.Context, client *http.Client, hostname, token string) error { |
| 25 | if token == "" { |
| 26 | return errors.New("authentication token is empty") |
| 27 | } |
| 28 | body, err := json.Marshal(struct { |
| 29 | AccessToken string `json:"access_token"` |
| 30 | }{AccessToken: token}) |
| 31 | if err != nil { |
| 32 | return err |
| 33 | } |
| 34 | |
| 35 | ctx, cancel := context.WithTimeout(ctx, 15*time.Second) |
| 36 | defer cancel() |
| 37 | basicAuth := base64.StdEncoding.EncodeToString([]byte(oauthClientID + ":" + oauthClientSecret)) |
| 38 | path, err := safeurl.JoinPath("applications", oauthClientID, "token") |
| 39 | if err != nil { |
| 40 | return err |
| 41 | } |
| 42 | resp, err := api.NewClientFromHTTP(client).RequestWithContext( |
| 43 | ctx, hostname, http.MethodDelete, path.String(), bytes.NewReader(body), |
| 44 | api.WithHeader("Authorization", "Basic "+basicAuth), |
| 45 | api.WithHeader("Accept", "application/vnd.github+json"), |
| 46 | api.WithHeader("Content-Type", "application/json"), |
| 47 | api.WithoutFollowingRedirects(), |
| 48 | ) |
| 49 | if err != nil { |
| 50 | if httpErr, ok := errors.AsType[api.HTTPError](err); ok { |
| 51 | // A server error message may echo the access token supplied in the body. |
| 52 | if httpErr.StatusCode == http.StatusNotFound { |
| 53 | return ErrTokenNotFound |
| 54 | } |
| 55 | return fmt.Errorf("HTTP %d (%s)", httpErr.StatusCode, http.StatusText(httpErr.StatusCode)) |
| 56 | } |
| 57 | var netErr net.Error |
| 58 | if errors.Is(err, context.DeadlineExceeded) || errors.As(err, &netErr) && netErr.Timeout() { |
| 59 | return errors.New("request timed out") |
| 60 | } |
| 61 | if errors.Is(err, context.Canceled) { |
| 62 | return context.Canceled |
| 63 | } |
| 64 | return errors.New(strings.NewReplacer( |
| 65 | token, "[REDACTED]", |
| 66 | oauthClientSecret, "[REDACTED]", |
| 67 | basicAuth, "[REDACTED]", |
| 68 | ).Replace(err.Error())) |
| 69 | } |
| 70 | defer resp.Body.Close() |
| 71 | if resp.StatusCode != http.StatusNoContent { |
| 72 | return api.UnexpectedStatusError(resp) |
| 73 | } |
| 74 | return nil |
| 75 | } |