filecredsource.go raw

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