11package identities
22
33import (
4+ "context"
45 "encoding/json"
56 "errors"
67 "fmt"
@@ -10,14 +11,16 @@ import (
1011 "github.com/go-playground/validator/v10"
1112 "github.com/mcuadros/go-defaults"
1213 "github.com/raystack/guardian/domain"
14+ "golang.org/x/oauth2"
15+ "google.golang.org/api/idtoken"
1316)
1417
1518var ErrFailedRequest = errors .New ("request failed" )
1619
1720const UserIDWildcard = "{user_id}"
1821
1922type HTTPAuthConfig struct {
20- Type string `mapstructure:"type" json:"type" yaml:"type" validate:"required,oneof=basic api_key bearer"`
23+ Type string `mapstructure:"type" json:"type" yaml:"type" validate:"required,oneof=basic api_key bearer google_idtoken "`
2124
2225 // basic auth
2326 Username string `mapstructure:"username,omitempty" json:"username,omitempty" yaml:"username,omitempty" validate:"required_if=Type basic"`
@@ -30,6 +33,11 @@ type HTTPAuthConfig struct {
3033
3134 // bearer
3235 Token string `mapstructure:"token,omitempty" json:"token,omitempty" yaml:"token,omitempty" validate:"required_if=Type bearer"`
36+
37+ // google_idtoken
38+ Audience string `mapstructure:"audience,omitempty" json:"audience,omitempty" yaml:"audience,omitempty" validate:"required_if=Type google_idtoken"`
39+ // TODO: allow base64 encoded credentials
40+ CredentialsJSON string `mapstructure:"credentials_json,omitempty" json:"credentials_json,omitempty" yaml:"credentials_json,omitempty" validate:"required_if=Type google_idtoken"`
3341}
3442
3543// HTTPClientConfig is the configuration required by iam.Client
@@ -72,6 +80,14 @@ func (c *HTTPClientConfig) Encrypt() error {
7280 }
7381 c .Auth .Token = encryptedValue
7482 }
83+
84+ if c .Auth .CredentialsJSON != "" {
85+ encryptedValue , err := c .crypto .Encrypt (c .Auth .CredentialsJSON )
86+ if err != nil {
87+ return err
88+ }
89+ c .Auth .CredentialsJSON = encryptedValue
90+ }
7591 }
7692
7793 return nil
@@ -102,6 +118,14 @@ func (c *HTTPClientConfig) Decrypt() error {
102118 }
103119 c .Auth .Token = decryptedValue
104120 }
121+
122+ if c .Auth .CredentialsJSON != "" {
123+ decryptedValue , err := c .crypto .Decrypt (c .Auth .CredentialsJSON )
124+ if err != nil {
125+ return err
126+ }
127+ c .Auth .CredentialsJSON = decryptedValue
128+ }
105129 }
106130
107131 return nil
@@ -126,6 +150,15 @@ func NewHTTPClient(config *HTTPClientConfig) (*HTTPClient, error) {
126150 httpClient = http .DefaultClient
127151 }
128152
153+ if config .Auth .Type == "google_idtoken" {
154+ ctx := context .Background ()
155+ ts , err := idtoken .NewTokenSource (ctx , config .Auth .Audience , idtoken .WithCredentialsJSON ([]byte (config .Auth .CredentialsJSON )))
156+ if err != nil {
157+ return nil , err
158+ }
159+ httpClient = oauth2 .NewClient (ctx , ts )
160+ }
161+
129162 return & HTTPClient {
130163 httpClient : httpClient ,
131164 config : config ,
0 commit comments