azureblobuploader.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. package imguploader
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/hmac"
  6. "crypto/sha256"
  7. "encoding/base64"
  8. "encoding/xml"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "mime"
  13. "net/http"
  14. "net/url"
  15. "os"
  16. "path"
  17. "sort"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "github.com/grafana/grafana/pkg/infra/log"
  22. "github.com/grafana/grafana/pkg/util"
  23. )
  24. type AzureBlobUploader struct {
  25. account_name string
  26. account_key string
  27. container_name string
  28. log log.Logger
  29. }
  30. func NewAzureBlobUploader(account_name string, account_key string, container_name string) *AzureBlobUploader {
  31. return &AzureBlobUploader{
  32. account_name: account_name,
  33. account_key: account_key,
  34. container_name: container_name,
  35. log: log.New("azureBlobUploader"),
  36. }
  37. }
  38. // Receive path of image on disk and return azure blob url
  39. func (az *AzureBlobUploader) Upload(ctx context.Context, imageDiskPath string) (string, error) {
  40. // setup client
  41. blob := NewStorageClient(az.account_name, az.account_key)
  42. file, err := os.Open(imageDiskPath)
  43. if err != nil {
  44. return "", err
  45. }
  46. defer file.Close()
  47. randomFileName := util.GetRandomString(30) + ".png"
  48. // upload image
  49. az.log.Debug("Uploading image to azure_blob", "container_name", az.container_name, "blob_name", randomFileName)
  50. resp, err := blob.FileUpload(az.container_name, randomFileName, file)
  51. if err != nil {
  52. return "", err
  53. }
  54. if resp.StatusCode > 400 && resp.StatusCode < 600 {
  55. body, _ := ioutil.ReadAll(io.LimitReader(resp.Body, 1<<20))
  56. aerr := &Error{
  57. Code: resp.StatusCode,
  58. Status: resp.Status,
  59. Body: body,
  60. Header: resp.Header,
  61. }
  62. aerr.parseXML()
  63. resp.Body.Close()
  64. return "", aerr
  65. }
  66. url := fmt.Sprintf("https://%s.blob.core.windows.net/%s/%s", az.account_name, az.container_name, randomFileName)
  67. return url, nil
  68. }
  69. // --- AZURE LIBRARY
  70. type Blobs struct {
  71. XMLName xml.Name `xml:"EnumerationResults"`
  72. Items []Blob `xml:"Blobs>Blob"`
  73. }
  74. type Blob struct {
  75. Name string `xml:"Name"`
  76. Property Property `xml:"Properties"`
  77. }
  78. type Property struct {
  79. LastModified string `xml:"Last-Modified"`
  80. Etag string `xml:"Etag"`
  81. ContentLength int `xml:"Content-Length"`
  82. ContentType string `xml:"Content-Type"`
  83. BlobType string `xml:"BlobType"`
  84. LeaseStatus string `xml:"LeaseStatus"`
  85. }
  86. type Error struct {
  87. Code int
  88. Status string
  89. Body []byte
  90. Header http.Header
  91. AzureCode string
  92. }
  93. func (e *Error) Error() string {
  94. return fmt.Sprintf("status %d: %s", e.Code, e.Body)
  95. }
  96. func (e *Error) parseXML() {
  97. var xe xmlError
  98. _ = xml.NewDecoder(bytes.NewReader(e.Body)).Decode(&xe)
  99. e.AzureCode = xe.Code
  100. }
  101. type xmlError struct {
  102. XMLName xml.Name `xml:"Error"`
  103. Code string
  104. Message string
  105. }
  106. const ms_date_layout = "Mon, 02 Jan 2006 15:04:05 GMT"
  107. const version = "2017-04-17"
  108. type StorageClient struct {
  109. Auth *Auth
  110. Transport http.RoundTripper
  111. }
  112. func (c *StorageClient) transport() http.RoundTripper {
  113. if c.Transport != nil {
  114. return c.Transport
  115. }
  116. return http.DefaultTransport
  117. }
  118. func NewStorageClient(account, accessKey string) *StorageClient {
  119. return &StorageClient{
  120. Auth: &Auth{
  121. account,
  122. accessKey,
  123. },
  124. Transport: nil,
  125. }
  126. }
  127. func (c *StorageClient) absUrl(format string, a ...interface{}) string {
  128. part := fmt.Sprintf(format, a...)
  129. return fmt.Sprintf("https://%s.blob.core.windows.net/%s", c.Auth.Account, part)
  130. }
  131. func copyHeadersToRequest(req *http.Request, headers map[string]string) {
  132. for k, v := range headers {
  133. req.Header[k] = []string{v}
  134. }
  135. }
  136. func (c *StorageClient) FileUpload(container, blobName string, body io.Reader) (*http.Response, error) {
  137. blobName = escape(blobName)
  138. extension := strings.ToLower(path.Ext(blobName))
  139. contentType := mime.TypeByExtension(extension)
  140. buf := new(bytes.Buffer)
  141. buf.ReadFrom(body)
  142. req, err := http.NewRequest(
  143. "PUT",
  144. c.absUrl("%s/%s", container, blobName),
  145. buf,
  146. )
  147. if err != nil {
  148. return nil, err
  149. }
  150. copyHeadersToRequest(req, map[string]string{
  151. "x-ms-blob-type": "BlockBlob",
  152. "x-ms-date": time.Now().UTC().Format(ms_date_layout),
  153. "x-ms-version": version,
  154. "Accept-Charset": "UTF-8",
  155. "Content-Type": contentType,
  156. "Content-Length": strconv.Itoa(buf.Len()),
  157. })
  158. c.Auth.SignRequest(req)
  159. return c.transport().RoundTrip(req)
  160. }
  161. func escape(content string) string {
  162. content = url.QueryEscape(content)
  163. // the Azure's behavior uses %20 to represent whitespace instead of + (plus)
  164. content = strings.Replace(content, "+", "%20", -1)
  165. // the Azure's behavior uses slash instead of + %2F
  166. content = strings.Replace(content, "%2F", "/", -1)
  167. return content
  168. }
  169. type Auth struct {
  170. Account string
  171. Key string
  172. }
  173. func (a *Auth) SignRequest(req *http.Request) {
  174. strToSign := fmt.Sprintf("%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s",
  175. strings.ToUpper(req.Method),
  176. tryget(req.Header, "Content-Encoding"),
  177. tryget(req.Header, "Content-Language"),
  178. tryget(req.Header, "Content-Length"),
  179. tryget(req.Header, "Content-MD5"),
  180. tryget(req.Header, "Content-Type"),
  181. tryget(req.Header, "Date"),
  182. tryget(req.Header, "If-Modified-Since"),
  183. tryget(req.Header, "If-Match"),
  184. tryget(req.Header, "If-None-Match"),
  185. tryget(req.Header, "If-Unmodified-Since"),
  186. tryget(req.Header, "Range"),
  187. a.canonicalizedHeaders(req),
  188. a.canonicalizedResource(req),
  189. )
  190. decodedKey, _ := base64.StdEncoding.DecodeString(a.Key)
  191. sha256 := hmac.New(sha256.New, decodedKey)
  192. sha256.Write([]byte(strToSign))
  193. signature := base64.StdEncoding.EncodeToString(sha256.Sum(nil))
  194. copyHeadersToRequest(req, map[string]string{
  195. "Authorization": fmt.Sprintf("SharedKey %s:%s", a.Account, signature),
  196. })
  197. }
  198. func tryget(headers map[string][]string, key string) string {
  199. // We default to empty string for "0" values to match server side behavior when generating signatures.
  200. if len(headers[key]) > 0 { // && headers[key][0] != "0" { //&& key != "Content-Length" {
  201. return headers[key][0]
  202. }
  203. return ""
  204. }
  205. //
  206. // The following is copied ~95% verbatim from:
  207. // http://github.com/loldesign/azure/ -> core/core.go
  208. //
  209. /*
  210. Based on Azure docs:
  211. Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
  212. 1) Retrieve all headers for the resource that begin with x-ms-, including the x-ms-date header.
  213. 2) Convert each HTTP header name to lowercase.
  214. 3) Sort the headers lexicographically by header name, in ascending order. Note that each header may appear only once in the string.
  215. 4) Unfold the string by replacing any breaking white space with a single space.
  216. 5) Trim any white space around the colon in the header.
  217. 6) Finally, append a new line character to each canonicalized header in the resulting list. Construct the CanonicalizedHeaders string by concatenating all headers in this list into a single string.
  218. */
  219. func (a *Auth) canonicalizedHeaders(req *http.Request) string {
  220. var buffer bytes.Buffer
  221. for key, value := range req.Header {
  222. lowerKey := strings.ToLower(key)
  223. if strings.HasPrefix(lowerKey, "x-ms-") {
  224. if buffer.Len() == 0 {
  225. buffer.WriteString(fmt.Sprintf("%s:%s", lowerKey, value[0]))
  226. } else {
  227. buffer.WriteString(fmt.Sprintf("\n%s:%s", lowerKey, value[0]))
  228. }
  229. }
  230. }
  231. split := strings.Split(buffer.String(), "\n")
  232. sort.Strings(split)
  233. return strings.Join(split, "\n")
  234. }
  235. /*
  236. Based on Azure docs
  237. Link: http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx#Constructing_Element
  238. 1) Beginning with an empty string (""), append a forward slash (/), followed by the name of the account that owns the resource being accessed.
  239. 2) Append the resource's encoded URI path, without any query parameters.
  240. 3) Retrieve all query parameters on the resource URI, including the comp parameter if it exists.
  241. 4) Convert all parameter names to lowercase.
  242. 5) Sort the query parameters lexicographically by parameter name, in ascending order.
  243. 6) URL-decode each query parameter name and value.
  244. 7) Append each query parameter name and value to the string in the following format, making sure to include the colon (:) between the name and the value:
  245. parameter-name:parameter-value
  246. 8) If a query parameter has more than one value, sort all values lexicographically, then include them in a comma-separated list:
  247. parameter-name:parameter-value-1,parameter-value-2,parameter-value-n
  248. 9) Append a new line character (\n) after each name-value pair.
  249. Rules:
  250. 1) Avoid using the new line character (\n) in values for query parameters. If it must be used, ensure that it does not affect the format of the canonicalized resource string.
  251. 2) Avoid using commas in query parameter values.
  252. */
  253. func (a *Auth) canonicalizedResource(req *http.Request) string {
  254. var buffer bytes.Buffer
  255. buffer.WriteString(fmt.Sprintf("/%s%s", a.Account, req.URL.Path))
  256. queries := req.URL.Query()
  257. for key, values := range queries {
  258. sort.Strings(values)
  259. buffer.WriteString(fmt.Sprintf("\n%s:%s", key, strings.Join(values, ",")))
  260. }
  261. split := strings.Split(buffer.String(), "\n")
  262. sort.Strings(split)
  263. return strings.Join(split, "\n")
  264. }