filecredsource.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright 2020 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 externalaccount
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "os"
  13. )
  14. type fileCredentialSource struct {
  15. File string
  16. Format format
  17. }
  18. func (cs fileCredentialSource) credentialSourceType() string {
  19. return "file"
  20. }
  21. func (cs fileCredentialSource) subjectToken() (string, error) {
  22. tokenFile, err := os.Open(cs.File)
  23. if err != nil {
  24. return "", fmt.Errorf("oauth2/google: failed to open credential file %q", cs.File)
  25. }
  26. defer tokenFile.Close()
  27. tokenBytes, err := ioutil.ReadAll(io.LimitReader(tokenFile, 1<<20))
  28. if err != nil {
  29. return "", fmt.Errorf("oauth2/google: failed to read credential file: %v", err)
  30. }
  31. tokenBytes = bytes.TrimSpace(tokenBytes)
  32. switch cs.Format.Type {
  33. case "json":
  34. jsonData := make(map[string]interface{})
  35. err = json.Unmarshal(tokenBytes, &jsonData)
  36. if err != nil {
  37. return "", fmt.Errorf("oauth2/google: failed to unmarshal subject token file: %v", err)
  38. }
  39. val, ok := jsonData[cs.Format.SubjectTokenFieldName]
  40. if !ok {
  41. return "", errors.New("oauth2/google: provided subject_token_field_name not found in credentials")
  42. }
  43. token, ok := val.(string)
  44. if !ok {
  45. return "", errors.New("oauth2/google: improperly formatted subject token")
  46. }
  47. return token, nil
  48. case "text":
  49. return string(tokenBytes), nil
  50. case "":
  51. return string(tokenBytes), nil
  52. default:
  53. return "", errors.New("oauth2/google: invalid credential_source file format type")
  54. }
  55. }