You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

168 line
4.8 KiB

  1. // Copyright 2018 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package jira provides claims and JWT signing for OAuth2 to access JIRA/Confluence.
  5. package jira
  6. import (
  7. "context"
  8. "crypto/hmac"
  9. "crypto/sha256"
  10. "encoding/base64"
  11. "encoding/json"
  12. "fmt"
  13. "io"
  14. "io/ioutil"
  15. "net/http"
  16. "net/url"
  17. "strings"
  18. "time"
  19. "golang.org/x/oauth2"
  20. )
  21. // ClaimSet contains information about the JWT signature according
  22. // to Atlassian's documentation
  23. // https://developer.atlassian.com/cloud/jira/software/oauth-2-jwt-bearer-token-authorization-grant-type/
  24. type ClaimSet struct {
  25. Issuer string `json:"iss"`
  26. Subject string `json:"sub"`
  27. InstalledURL string `json:"tnt"` // URL of installed app
  28. AuthURL string `json:"aud"` // URL of auth server
  29. ExpiresIn int64 `json:"exp"` // Must be no later that 60 seconds in the future
  30. IssuedAt int64 `json:"iat"`
  31. }
  32. var (
  33. defaultGrantType = "urn:ietf:params:oauth:grant-type:jwt-bearer"
  34. defaultHeader = map[string]string{
  35. "typ": "JWT",
  36. "alg": "HS256",
  37. }
  38. )
  39. // Config is the configuration for using JWT to fetch tokens,
  40. // commonly known as "two-legged OAuth 2.0".
  41. type Config struct {
  42. // BaseURL for your app
  43. BaseURL string
  44. // Subject is the userkey as defined by Atlassian
  45. // Different than username (ex: /rest/api/2/user?username=alex)
  46. Subject string
  47. oauth2.Config
  48. }
  49. // TokenSource returns a JWT TokenSource using the configuration
  50. // in c and the HTTP client from the provided context.
  51. func (c *Config) TokenSource(ctx context.Context) oauth2.TokenSource {
  52. return oauth2.ReuseTokenSource(nil, jwtSource{ctx, c})
  53. }
  54. // Client returns an HTTP client wrapping the context's
  55. // HTTP transport and adding Authorization headers with tokens
  56. // obtained from c.
  57. //
  58. // The returned client and its Transport should not be modified.
  59. func (c *Config) Client(ctx context.Context) *http.Client {
  60. return oauth2.NewClient(ctx, c.TokenSource(ctx))
  61. }
  62. // jwtSource is a source that always does a signed JWT request for a token.
  63. // It should typically be wrapped with a reuseTokenSource.
  64. type jwtSource struct {
  65. ctx context.Context
  66. conf *Config
  67. }
  68. func (js jwtSource) Token() (*oauth2.Token, error) {
  69. exp := time.Duration(59) * time.Second
  70. claimSet := &ClaimSet{
  71. Issuer: fmt.Sprintf("urn:atlassian:connect:clientid:%s", js.conf.ClientID),
  72. Subject: fmt.Sprintf("urn:atlassian:connect:userkey:%s", js.conf.Subject),
  73. InstalledURL: js.conf.BaseURL,
  74. AuthURL: js.conf.Endpoint.AuthURL,
  75. IssuedAt: time.Now().Unix(),
  76. ExpiresIn: time.Now().Add(exp).Unix(),
  77. }
  78. v := url.Values{}
  79. v.Set("grant_type", defaultGrantType)
  80. // Add scopes if they exist; If not, it defaults to app scopes
  81. if scopes := js.conf.Scopes; scopes != nil {
  82. upperScopes := make([]string, len(scopes))
  83. for i, k := range scopes {
  84. upperScopes[i] = strings.ToUpper(k)
  85. }
  86. v.Set("scope", strings.Join(upperScopes, "+"))
  87. }
  88. // Sign claims for assertion
  89. assertion, err := sign(js.conf.ClientSecret, claimSet)
  90. if err != nil {
  91. return nil, err
  92. }
  93. v.Set("assertion", string(assertion))
  94. // Fetch access token from auth server
  95. hc := oauth2.NewClient(js.ctx, nil)
  96. resp, err := hc.PostForm(js.conf.Endpoint.TokenURL, v)
  97. if err != nil {
  98. return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
  99. }
  100. defer resp.Body.Close()
  101. body, err := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20))
  102. if err != nil {
  103. return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
  104. }
  105. if c := resp.StatusCode; c < 200 || c > 299 {
  106. return nil, fmt.Errorf("oauth2: cannot fetch token: %v\nResponse: %s", resp.Status, body)
  107. }
  108. // tokenRes is the JSON response body.
  109. var tokenRes struct {
  110. AccessToken string `json:"access_token"`
  111. TokenType string `json:"token_type"`
  112. ExpiresIn int64 `json:"expires_in"` // relative seconds from now
  113. }
  114. if err := json.Unmarshal(body, &tokenRes); err != nil {
  115. return nil, fmt.Errorf("oauth2: cannot fetch token: %v", err)
  116. }
  117. token := &oauth2.Token{
  118. AccessToken: tokenRes.AccessToken,
  119. TokenType: tokenRes.TokenType,
  120. }
  121. if secs := tokenRes.ExpiresIn; secs > 0 {
  122. token.Expiry = time.Now().Add(time.Duration(secs) * time.Second)
  123. }
  124. return token, nil
  125. }
  126. // Sign the claim set with the shared secret
  127. // Result to be sent as assertion
  128. func sign(key string, claims *ClaimSet) (string, error) {
  129. b, err := json.Marshal(defaultHeader)
  130. if err != nil {
  131. return "", err
  132. }
  133. header := base64.RawURLEncoding.EncodeToString(b)
  134. jsonClaims, err := json.Marshal(claims)
  135. if err != nil {
  136. return "", err
  137. }
  138. encodedClaims := strings.TrimRight(base64.URLEncoding.EncodeToString(jsonClaims), "=")
  139. ss := fmt.Sprintf("%s.%s", header, encodedClaims)
  140. mac := hmac.New(sha256.New, []byte(key))
  141. mac.Write([]byte(ss))
  142. signature := mac.Sum(nil)
  143. return fmt.Sprintf("%s.%s", ss, base64.RawURLEncoding.EncodeToString(signature)), nil
  144. }