...

Source file src/golang.org/x/oauth2/google/externalaccount/filecredsource.go

Documentation: golang.org/x/oauth2/google/externalaccount

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

View as plain text