2022-07-07 20:11:50 +00:00
|
|
|
// Copyright 2020 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package externalaccount
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
"encoding/json"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
|
|
|
)
|
|
|
|
|
|
|
|
type fileCredentialSource struct {
|
|
|
|
File string
|
2024-10-16 10:54:40 +00:00
|
|
|
Format Format
|
2022-07-07 20:11:50 +00:00
|
|
|
}
|
|
|
|
|
2024-02-24 00:34:55 +00:00
|
|
|
func (cs fileCredentialSource) credentialSourceType() string {
|
|
|
|
return "file"
|
|
|
|
}
|
|
|
|
|
2022-07-07 20:11:50 +00:00
|
|
|
func (cs fileCredentialSource) subjectToken() (string, error) {
|
|
|
|
tokenFile, err := os.Open(cs.File)
|
|
|
|
if err != nil {
|
2024-10-16 10:54:40 +00:00
|
|
|
return "", fmt.Errorf("oauth2/google/externalaccount: failed to open credential file %q", cs.File)
|
2022-07-07 20:11:50 +00:00
|
|
|
}
|
|
|
|
defer tokenFile.Close()
|
|
|
|
tokenBytes, err := ioutil.ReadAll(io.LimitReader(tokenFile, 1<<20))
|
|
|
|
if err != nil {
|
2024-10-16 10:54:40 +00:00
|
|
|
return "", fmt.Errorf("oauth2/google/externalaccount: failed to read credential file: %v", err)
|
2022-07-07 20:11:50 +00:00
|
|
|
}
|
|
|
|
tokenBytes = bytes.TrimSpace(tokenBytes)
|
|
|
|
switch cs.Format.Type {
|
|
|
|
case "json":
|
|
|
|
jsonData := make(map[string]interface{})
|
|
|
|
err = json.Unmarshal(tokenBytes, &jsonData)
|
|
|
|
if err != nil {
|
2024-10-16 10:54:40 +00:00
|
|
|
return "", fmt.Errorf("oauth2/google/externalaccount: failed to unmarshal subject token file: %v", err)
|
2022-07-07 20:11:50 +00:00
|
|
|
}
|
|
|
|
val, ok := jsonData[cs.Format.SubjectTokenFieldName]
|
|
|
|
if !ok {
|
2024-10-16 10:54:40 +00:00
|
|
|
return "", errors.New("oauth2/google/externalaccount: provided subject_token_field_name not found in credentials")
|
2022-07-07 20:11:50 +00:00
|
|
|
}
|
|
|
|
token, ok := val.(string)
|
|
|
|
if !ok {
|
2024-10-16 10:54:40 +00:00
|
|
|
return "", errors.New("oauth2/google/externalaccount: improperly formatted subject token")
|
2022-07-07 20:11:50 +00:00
|
|
|
}
|
|
|
|
return token, nil
|
|
|
|
case "text":
|
|
|
|
return string(tokenBytes), nil
|
|
|
|
case "":
|
|
|
|
return string(tokenBytes), nil
|
|
|
|
default:
|
2024-10-16 10:54:40 +00:00
|
|
|
return "", errors.New("oauth2/google/externalaccount: invalid credential_source file format type")
|
2022-07-07 20:11:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
}
|