Skip to content

Commit a2e1965

Browse files
authored
Fix some issues for oauth2 client (#166)
* Fix some issues for oauth2 client Signed-off-by: Jose Fuentes <[email protected]> * Better validation of credentials Signed-off-by: Jose Fuentes <[email protected]>
1 parent 73b93c1 commit a2e1965

File tree

5 files changed

+51
-27
lines changed

5 files changed

+51
-27
lines changed

Makefile

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ define LDFLAGS
1616
-X "github.com/jetstack/preflight/pkg/version.Commit=$(COMMIT)" \
1717
-X "github.com/jetstack/preflight/pkg/version.BuildDate=$(DATE)" \
1818
-X "github.com/jetstack/preflight/pkg/version.GoVersion=$(GOVERSION)" \
19-
-X "github.com/jetstack/preflight/pkg/client.clientID=$(OAUTH_CLIENT_ID)" \
20-
-X "github.com/jetstack/preflight/pkg/client.clientSecret=$(OAUTH_CLIENT_SECRET)" \
21-
-X "github.com/jetstack/preflight/pkg/client.authServer=$(OAUTH_AUTH_SERVER)"
19+
-X "github.com/jetstack/preflight/pkg/client.ClientID=$(OAUTH_CLIENT_ID)" \
20+
-X "github.com/jetstack/preflight/pkg/client.ClientSecret=$(OAUTH_CLIENT_SECRET)" \
21+
-X "github.com/jetstack/preflight/pkg/client.AuthServerDomain=$(OAUTH_AUTH_SERVER_DOMAIN)"
2222
endef
2323

2424
GO_BUILD:=go build -ldflags '$(LDFLAGS)'

pkg/agent/run.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ func gatherAndPostData(ctx context.Context) {
8383

8484
log.Printf("Loaded config: \n%s", dump)
8585

86-
var credentials *Credentials
86+
var credentials *client.Credentials
8787
if CredentialsPath != "" {
8888
file, err = os.Open(CredentialsPath)
8989
if err != nil {
@@ -93,7 +93,7 @@ func gatherAndPostData(ctx context.Context) {
9393

9494
b, err = ioutil.ReadAll(file)
9595

96-
credentials, err = ParseCredentials(b)
96+
credentials, err = client.ParseCredentials(b)
9797
if err != nil {
9898
log.Fatalf("Failed to parse credentials file: %s", err)
9999
}
@@ -105,7 +105,7 @@ func gatherAndPostData(ctx context.Context) {
105105
var preflightClient *client.PreflightClient
106106
if credentials != nil {
107107
log.Printf("A credentials file was specified. Using OAuth2 authentication...")
108-
preflightClient, err = client.New(agentMetadata, credentials.UserID, credentials.UserSecret, baseURL)
108+
preflightClient, err = client.New(agentMetadata, credentials, baseURL)
109109
if err != nil {
110110
log.Fatalf("Error creating preflight client: %+v", err)
111111
}

pkg/client/accessToken.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,9 @@ func (c *PreflightClient) getValidAccessToken() (*accessToken, error) {
3535
}
3636

3737
func (c *PreflightClient) renewAccessToken() error {
38-
url := fmt.Sprintf("https://%s/oauth/token", authServer)
39-
// TODO: audience will be dynamic in the future, but at the moment this client only sends readings.
40-
audience := "https://preflight.jetstack.io/api/v1/datareading"
41-
payload := fmt.Sprintf("grant_type=password&client_id=%s&client_secret=%s&audience=%s&username=%s&password=%s", clientID, clientSecret, audience, c.userID, c.userSecret)
38+
url := fmt.Sprintf("https://%s/oauth/token", c.credentials.AuthServerDomain)
39+
audience := "https://preflight.jetstack.io/api/v1"
40+
payload := fmt.Sprintf("grant_type=password&client_id=%s&client_secret=%s&audience=%s&username=%s&password=%s", c.credentials.ClientID, c.credentials.ClientSecret, audience, c.credentials.UserID, c.credentials.UserSecret)
4241
req, err := http.NewRequest("POST", url, strings.NewReader(payload))
4342
if err != nil {
4443
return errors.Trace(err)
@@ -57,6 +56,10 @@ func (c *PreflightClient) renewAccessToken() error {
5756

5857
defer res.Body.Close()
5958

59+
if status := res.StatusCode; status < 200 || status >= 300 {
60+
return errors.Errorf("auth server did not provide an access token: (status %d) %s.", status, string(body))
61+
}
62+
6063
response := struct {
6164
Bearer string `json:"access_token"`
6265
ExpiresIn uint `json:"expires_in"`
@@ -68,7 +71,7 @@ func (c *PreflightClient) renewAccessToken() error {
6871
}
6972

7073
if response.ExpiresIn == 0 {
71-
return fmt.Errorf("got wrong expiration for access token")
74+
return errors.Errorf("got wrong expiration for access token")
7275
}
7376

7477
c.accessToken.bearer = response.Bearer

pkg/client/client.go

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -11,16 +11,14 @@ import (
1111
)
1212

1313
// These variables are injected at build time.
14-
15-
var clientID string
16-
var clientSecret string
17-
var authServer string
14+
var ClientID string
15+
var ClientSecret string
16+
var AuthServerDomain string
1817

1918
// PreflightClient can be used to talk to the Preflight backend.
2019
type PreflightClient struct {
2120
// OAuth2
22-
userID string
23-
userSecret string
21+
credentials *Credentials
2422
// accessToken is the current OAuth access token.
2523
accessToken *accessToken
2624

@@ -47,29 +45,34 @@ func NewWithBasicAuth(agentMetadata *api.AgentMetadata, authToken, baseURL strin
4745
}
4846

4947
// New creates a new client that uses OAuth2.
50-
func New(agentMetadata *api.AgentMetadata, userID, userSecret, baseURL string) (*PreflightClient, error) {
51-
if userID == "" || userSecret == "" {
52-
return nil, fmt.Errorf("cannot create PreflightClient: neither userID or userSecret can be empty")
48+
func New(agentMetadata *api.AgentMetadata, credentials *Credentials, baseURL string) (*PreflightClient, error) {
49+
if err := credentials.validate(); err != nil {
50+
return nil, fmt.Errorf("cannot create PreflightClient: %v", err)
5351
}
5452
if baseURL == "" {
5553
return nil, fmt.Errorf("cannot create PreflightClient: baseURL cannot be empty")
5654
}
5755

58-
if clientID == "" || clientSecret == "" || authServer == "" {
59-
return nil, fmt.Errorf("cannot create PreflightClient: this build does not have a valid OAuth client configuration")
56+
if !credentials.IsClientSet() {
57+
credentials.ClientID = ClientID
58+
credentials.ClientSecret = ClientSecret
59+
credentials.AuthServerDomain = AuthServerDomain
60+
}
61+
62+
if !credentials.IsClientSet() {
63+
return nil, fmt.Errorf("cannot create PreflightClient: invalid OAuth2 client configuration")
6064
}
6165

6266
return &PreflightClient{
6367
agentMetadata: agentMetadata,
64-
userID: userID,
65-
userSecret: userSecret,
68+
credentials: credentials,
6669
baseURL: baseURL,
6770
accessToken: &accessToken{},
6871
}, nil
6972
}
7073

7174
func (c *PreflightClient) usingOAuth2() bool {
72-
return c.userID != ""
75+
return c.credentials.UserID != ""
7376
}
7477

7578
// PostDataReadings sends a slice of readings to Preflight.
@@ -96,7 +99,7 @@ func (c *PreflightClient) PostDataReadings(orgID string, readings []*api.DataRea
9699
}
97100
defer res.Body.Close()
98101

99-
return fmt.Errorf("Received response with status code %d. Body: %s", code, errorContent)
102+
return fmt.Errorf("received response with status code %d. Body: %s", code, errorContent)
100103
}
101104

102105
return nil

pkg/agent/credentials.go renamed to pkg/client/credentials.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
package agent
1+
package client
22

33
import (
44
"encoding/json"
@@ -13,11 +13,29 @@ type Credentials struct {
1313
UserID string `json:"user_id"`
1414
// UserSecret is the secret for the user or service account.
1515
UserSecret string `json:"user_secret"`
16+
// The following fields are optional as the default behaviour
17+
// is to use the equivalent variables defined at package level
18+
// and injected at build time.
19+
// ClientID is the oauth2 client ID.
20+
ClientID string `json:"client_id,omitempty"`
21+
// ClientSecret is the oauth2 client secret.
22+
ClientSecret string `json:"client_secret,omitempty"`
23+
// AuthServerDomain is the domain for the auth server.
24+
AuthServerDomain string `json:"auth_server_domain,omitempty"`
25+
}
26+
27+
// IsClientSet returns whether the client credentials are set or not.
28+
func (c *Credentials) IsClientSet() bool {
29+
return c.ClientID != "" && c.ClientSecret != "" && c.AuthServerDomain != ""
1630
}
1731

1832
func (c *Credentials) validate() error {
1933
var result *multierror.Error
2034

35+
if c == nil {
36+
return fmt.Errorf("credentials are nil")
37+
}
38+
2139
if c.UserID == "" {
2240
result = multierror.Append(result, fmt.Errorf("user_id cannot be empty"))
2341
}

0 commit comments

Comments
 (0)