filecredsource.go 1.5 KB

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