Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for the new API Tokens (beta) auth scheme #326

Merged
merged 3 commits into from
Jul 15, 2019
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions cloudflare.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@ import (
)

const apiURL = "https://api.cloudflare.com/client/v4"

const (
// AuthKeyEmail specifies that we should authenticate with API key and email address
AuthKeyEmail = 1 << iota
// AuthUserService specifies that we should authenticate with a User-Service key
AuthUserService
// AuthToken specifies that we should authenticate with an API Token
AuthToken
)

// API holds the configuration for the current API client. A client should not
Expand All @@ -33,6 +36,7 @@ type API struct {
APIKey string
APIEmail string
APIUserServiceKey string
APIToken string
BaseURL string
OrganizationID string
UserAgent string
Expand Down Expand Up @@ -92,6 +96,23 @@ func New(key, email string, opts ...Option) (*API, error) {
return api, nil
}

// NewWithAPIToken creates a new Cloudflare v4 API client using API Tokens
func NewWithAPIToken(token string, opts ...Option) (*API, error) {
if token == "" {
return nil, errors.New(errEmptyAPIToken)
}

api, err := newClient(opts...)
if err != nil {
return nil, err
}

api.APIToken = token
api.authType = AuthToken

return api, nil
}

// NewWithUserServiceKey creates a new Cloudflare v4 API client using service key authentication.
func NewWithUserServiceKey(key string, opts ...Option) (*API, error) {
if key == "" {
Expand All @@ -109,7 +130,7 @@ func NewWithUserServiceKey(key string, opts ...Option) (*API, error) {
return api, nil
}

// SetAuthType sets the authentication method (AuthyKeyEmail or AuthUserService).
// SetAuthType sets the authentication method (AuthKeyEmail, AuthToken, or AuthUserService).
func (api *API) SetAuthType(authType int) {
api.authType = authType
}
Expand Down Expand Up @@ -141,7 +162,7 @@ func (api *API) ZoneIDByName(zoneName string) (string, error) {
}

// makeRequest makes a HTTP request and returns the body as a byte slice,
// closing it before returnng. params will be serialized to JSON.
// closing it before returning. params will be serialized to JSON.
func (api *API) makeRequest(method, uri string, params interface{}) ([]byte, error) {
return api.makeRequestWithAuthType(context.TODO(), method, uri, params, api.authType)
}
Expand Down Expand Up @@ -185,8 +206,8 @@ func (api *API) makeRequestWithAuthTypeAndHeaders(ctx context.Context, method, u
reqBody = bytes.NewReader(jsonBody)
}
if i > 0 {
// expect the backoff introduced here on errored requests to dominate the effect of rate limiting
// dont need a random component here as the rate limiter should do something similar
// expect the backoff introduced here on errorred requests to dominate the effect of rate limiting
// don't need a random component here as the rate limiter should do something similar
// nb time duration could truncate an arbitrary float. Since our inputs are all ints, we should be ok
sleepDuration := time.Duration(math.Pow(2, float64(i-1)) * float64(api.retryPolicy.MinRetryDelay))

Expand Down Expand Up @@ -277,13 +298,18 @@ func (api *API) request(ctx context.Context, method, uri string, reqBody io.Read
copyHeader(combinedHeaders, api.headers)
copyHeader(combinedHeaders, headers)
req.Header = combinedHeaders

if authType&AuthKeyEmail != 0 {
req.Header.Set("X-Auth-Key", api.APIKey)
req.Header.Set("X-Auth-Email", api.APIEmail)
}
if authType&AuthUserService != 0 {
req.Header.Set("X-Auth-User-Service-Key", api.APIUserServiceKey)
}
if authType&AuthToken != 0 {
req.Header.Set("Authorization", "Bearer "+api.APIToken)
}

if api.UserAgent != "" {
req.Header.Set("User-Agent", api.UserAgent)
}
Expand Down
18 changes: 18 additions & 0 deletions cloudflare_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ func TestClient_Headers(t *testing.T) {
assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method)
assert.Empty(t, r.Header.Get("X-Auth-Email"))
assert.Empty(t, r.Header.Get("X-Auth-Key"))
assert.Empty(t, r.Header.Get("Authorization"))
assert.Equal(t, "userservicekey", r.Header.Get("X-Auth-User-Service-Key"))
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
})
Expand All @@ -87,11 +88,28 @@ func TestClient_Headers(t *testing.T) {
assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method)
assert.Empty(t, r.Header.Get("X-Auth-Email"))
assert.Empty(t, r.Header.Get("X-Auth-Key"))
assert.Empty(t, r.Header.Get("Authorization"))
assert.Equal(t, "userservicekey", r.Header.Get("X-Auth-User-Service-Key"))
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
})
client.UserDetails()
teardown()

// it should set Authorization and omit others credential headers when using NewWithAPIToken
setup()
client, err = NewWithAPIToken("my-api-token")
assert.NoError(t, err)
client.BaseURL = server.URL
mux.HandleFunc("/zones/123456", func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "GET", r.Method, "Expected method 'GET', got %s", r.Method)
assert.Empty(t, r.Header.Get("X-Auth-Email"))
assert.Empty(t, r.Header.Get("X-Auth-Key"))
assert.Empty(t, r.Header.Get("X-Auth-User-Service-Key"))
assert.Equal(t, "Bearer my-api-token", r.Header.Get("Authorization"))
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
})
client.UserDetails()
teardown()
}

func TestClient_RetryCanSucceedAfterErrors(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package cloudflare
// Error messages
const (
errEmptyCredentials = "invalid credentials: key & email must not be empty"
errEmptyAPIToken = "invalid credential: API Token must not be empty"
errMakeRequestError = "error from makeRequest"
errUnmarshalError = "error unmarshalling the JSON response"
errRequestNotSuccessful = "error reported by API"
Expand Down