mirror of
https://github.com/golang/oauth2.git
synced 2025-07-21 00:00:09 +08:00
With https://go.dev/issue/61417 implemented, we can use the token type directly to unmarshal the JSON fields for the wire format. While here, remove all uses of the deprecated ioutil package as suggested by gopls while making these changes. Change-Id: I79d82374643007a21b5b3d9a8117bed81273eca5 Reviewed-on: https://go-review.googlesource.com/c/oauth2/+/614415 Reviewed-by: Sean Liao <sean@liao.dev> LUCI-TryBot-Result: Go LUCI <golang-scoped@luci-project-accounts.iam.gserviceaccount.com> Reviewed-by: Dmitri Shuralyov <dmitshur@google.com> Reviewed-by: Michael Pratt <mpratt@google.com>
61 lines
1.6 KiB
Go
61 lines
1.6 KiB
Go
// 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"
|
|
"os"
|
|
)
|
|
|
|
type fileCredentialSource struct {
|
|
File string
|
|
Format Format
|
|
}
|
|
|
|
func (cs fileCredentialSource) credentialSourceType() string {
|
|
return "file"
|
|
}
|
|
|
|
func (cs fileCredentialSource) subjectToken() (string, error) {
|
|
tokenFile, err := os.Open(cs.File)
|
|
if err != nil {
|
|
return "", fmt.Errorf("oauth2/google/externalaccount: failed to open credential file %q", cs.File)
|
|
}
|
|
defer tokenFile.Close()
|
|
tokenBytes, err := io.ReadAll(io.LimitReader(tokenFile, 1<<20))
|
|
if err != nil {
|
|
return "", fmt.Errorf("oauth2/google/externalaccount: failed to read credential file: %v", err)
|
|
}
|
|
tokenBytes = bytes.TrimSpace(tokenBytes)
|
|
switch cs.Format.Type {
|
|
case "json":
|
|
jsonData := make(map[string]interface{})
|
|
err = json.Unmarshal(tokenBytes, &jsonData)
|
|
if err != nil {
|
|
return "", fmt.Errorf("oauth2/google/externalaccount: failed to unmarshal subject token file: %v", err)
|
|
}
|
|
val, ok := jsonData[cs.Format.SubjectTokenFieldName]
|
|
if !ok {
|
|
return "", errors.New("oauth2/google/externalaccount: provided subject_token_field_name not found in credentials")
|
|
}
|
|
token, ok := val.(string)
|
|
if !ok {
|
|
return "", errors.New("oauth2/google/externalaccount: improperly formatted subject token")
|
|
}
|
|
return token, nil
|
|
case "text":
|
|
return string(tokenBytes), nil
|
|
case "":
|
|
return string(tokenBytes), nil
|
|
default:
|
|
return "", errors.New("oauth2/google/externalaccount: invalid credential_source file format type")
|
|
}
|
|
|
|
}
|