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

Support for PagerDuty Apps Oauth scoped token #708

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
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
15 changes: 0 additions & 15 deletions GNUmakefile
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
TEST?=$$(go list ./... |grep -v 'vendor')
GOFMT_FILES?=$$(find . -name '*.go' |grep -v vendor)
WEBSITE_REPO=github.com/hashicorp/terraform-website
PKG_NAME=pagerduty

default: build
Expand Down Expand Up @@ -46,19 +45,5 @@ test-compile:
update-go-pagerduty:
go get github.com/heimweh/go-pagerduty/pagerduty && go mod tidy && go mod vendor

website:
ifeq (,$(wildcard $(GOPATH)/src/$(WEBSITE_REPO)))
echo "$(WEBSITE_REPO) not found in your GOPATH (necessary for layouts and assets), get-ting..."
git clone https://$(WEBSITE_REPO) $(GOPATH)/src/$(WEBSITE_REPO)
endif
@$(MAKE) -C $(GOPATH)/src/$(WEBSITE_REPO) website-provider PROVIDER_PATH=$(shell pwd) PROVIDER_NAME=$(PKG_NAME)

website-test:
ifeq (,$(wildcard $(GOPATH)/src/$(WEBSITE_REPO)))
echo "$(WEBSITE_REPO) not found in your GOPATH (necessary for layouts and assets), get-ting..."
git clone https://$(WEBSITE_REPO) $(GOPATH)/src/$(WEBSITE_REPO)
endif
@$(MAKE) -C $(GOPATH)/src/$(WEBSITE_REPO) website-provider-test PROVIDER_PATH=$(shell pwd) PROVIDER_NAME=$(PKG_NAME)

.PHONY: build test testacc vet fmt fmtcheck errcheck test-compile website website-test

19 changes: 9 additions & 10 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ require (
github.com/hashicorp/terraform-exec v0.16.0
github.com/hashicorp/terraform-json v0.13.0
github.com/hashicorp/terraform-plugin-sdk/v2 v2.11.0
github.com/heimweh/go-pagerduty v0.0.0-20230821205435-23a4af661dd7
github.com/heimweh/go-pagerduty v0.0.0-20230908205257-a96e6c05f7ea
)

require (
Expand All @@ -20,7 +20,6 @@ require (
github.com/cloudflare/circl v1.3.3 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/fatih/color v1.7.0 // indirect
github.com/golang/mock v1.6.0 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/golang/snappy v0.0.4 // indirect
github.com/google/go-cmp v0.5.9 // indirect
Expand All @@ -43,14 +42,14 @@ require (
github.com/mattn/go-colorable v0.1.4 // indirect
github.com/mattn/go-isatty v0.0.10 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/mitchellh/go-wordwrap v1.0.0 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/montanaflynn/stats v0.6.6 // indirect
github.com/oklog/run v1.0.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/spf13/afero v1.9.5 // indirect
github.com/vmihailenco/msgpack v4.0.4+incompatible // indirect
github.com/vmihailenco/msgpack/v4 v4.3.12 // indirect
github.com/vmihailenco/tagparser v0.1.1 // indirect
Expand All @@ -62,13 +61,13 @@ require (
go.mongodb.org/mongo-driver v1.10.2 // indirect
golang.org/x/crypto v0.11.0 // indirect
golang.org/x/mod v0.10.0 // indirect
golang.org/x/net v0.12.0 // indirect
golang.org/x/sync v0.0.0-20220601150217-0de741cfad7f // indirect
golang.org/x/net v0.10.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sys v0.10.0 // indirect
golang.org/x/text v0.11.0 // indirect
golang.org/x/text v0.13.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20230110181048-76db0878b65f // indirect
google.golang.org/grpc v1.53.0 // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/yaml.v2 v2.3.0 // indirect
google.golang.org/genproto v0.0.0-20210226172003-ab064af71705 // indirect
google.golang.org/grpc v1.45.0 // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
)
712 changes: 14 additions & 698 deletions go.sum

Large diffs are not rendered by default.

21 changes: 15 additions & 6 deletions pagerduty/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/logging"
"github.com/heimweh/go-pagerduty/pagerduty"
"github.com/heimweh/go-pagerduty/persistentconfig"
)

// Config defines the configuration options for the PagerDuty client
Expand Down Expand Up @@ -35,6 +36,12 @@ type Config struct {
// UserAgent for API Client
UserAgent string

APITokenType *pagerduty.AuthTokenType

AppOauthScopedTokenParams *persistentconfig.AppOauthScopedTokenParams

ServiceRegion string

client *pagerduty.Client
slackClient *pagerduty.Client
}
Expand All @@ -57,7 +64,7 @@ func (c *Config) Client() (*pagerduty.Client, error) {
}

// Validate that the PagerDuty token is set
if c.Token == "" {
if c.Token == "" && c.APITokenType != nil && *c.APITokenType == pagerduty.AuthTokenTypeAPIToken {
return nil, fmt.Errorf(invalidCreds)
}

Expand All @@ -71,11 +78,13 @@ func (c *Config) Client() (*pagerduty.Client, error) {
}

config := &pagerduty.Config{
BaseURL: apiUrl,
Debug: logging.IsDebugOrHigher(),
HTTPClient: httpClient,
Token: c.Token,
UserAgent: c.UserAgent,
BaseURL: apiUrl,
Debug: logging.IsDebugOrHigher(),
HTTPClient: httpClient,
Token: c.Token,
UserAgent: c.UserAgent,
AppOauthScopedTokenParams: c.AppOauthScopedTokenParams,
APIAuthTokenType: c.APITokenType,
}

client, err := pagerduty.NewClient(config)
Expand Down
99 changes: 88 additions & 11 deletions pagerduty/provider.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
package pagerduty

import (
"context"
"fmt"
"log"
"regexp"
"runtime"
"strings"

"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/heimweh/go-pagerduty/pagerduty"
"github.com/heimweh/go-pagerduty/persistentconfig"
)

// Provider represents a resource provider in Terraform
Expand All @@ -23,7 +26,7 @@ func Provider() *schema.Provider {

"token": {
Type: schema.TypeString,
Required: true,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc("PAGERDUTY_TOKEN", nil),
},

Expand All @@ -39,6 +42,31 @@ func Provider() *schema.Provider {
Default: "",
},

"use_app_oauth_scoped_token": {
Type: schema.TypeList,
Optional: true,
MaxItems: 1,
Elem: &schema.Resource{
Schema: map[string]*schema.Schema{
"pd_client_id": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("PAGERDUTY_CLIENT_ID", nil),
},
"pd_client_secret": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("PAGERDUTY_CLIENT_SECRET", nil),
},
"pd_subdomain": {
Type: schema.TypeString,
Required: true,
DefaultFunc: schema.EnvDefaultFunc("PAGERDUTY_SUBDOMAIN", nil),
},
},
},
},

"api_url_override": {
Type: schema.TypeString,
Optional: true,
Expand Down Expand Up @@ -123,14 +151,14 @@ func Provider() *schema.Provider {
},
}

p.ConfigureFunc = func(d *schema.ResourceData) (interface{}, error) {
p.ConfigureContextFunc = func(ctx context.Context, d *schema.ResourceData) (interface{}, diag.Diagnostics) {
terraformVersion := p.TerraformVersion
if terraformVersion == "" {
// Terraform 0.12 introduced this field to the protocol
// We can therefore assume that if it's missing it's 0.10 or 0.11
terraformVersion = "0.11+compatible"
}
return providerConfigure(d, terraformVersion)
return providerConfigureContextFunc(ctx, d, terraformVersion)
}

return p
Expand Down Expand Up @@ -164,25 +192,74 @@ func handleNotFoundError(err error, d *schema.ResourceData) error {
return genError(err, d)
}

func providerConfigure(data *schema.ResourceData, terraformVersion string) (interface{}, error) {
var ServiceRegion = strings.ToLower(data.Get("service_region").(string))
func providerConfigureContextFunc(ctx context.Context, data *schema.ResourceData, terraformVersion string) (interface{}, diag.Diagnostics) {
var diags diag.Diagnostics
var serviceRegion = strings.ToLower(data.Get("service_region").(string))

if ServiceRegion == "us" || ServiceRegion == "" {
ServiceRegion = ""
var regionApiUrl string
if serviceRegion == "us" || serviceRegion == "" {
regionApiUrl = ""
} else {
ServiceRegion = ServiceRegion + "."
regionApiUrl = serviceRegion + "."
}

config := Config{
ApiUrl: "https://api." + ServiceRegion + "pagerduty.com",
AppUrl: "https://app." + ServiceRegion + "pagerduty.com",
ApiUrl: "https://api." + regionApiUrl + "pagerduty.com",
AppUrl: "https://app." + regionApiUrl + "pagerduty.com",
SkipCredsValidation: data.Get("skip_credentials_validation").(bool),
Token: data.Get("token").(string),
UserToken: data.Get("user_token").(string),
UserAgent: fmt.Sprintf("(%s %s) Terraform/%s", runtime.GOOS, runtime.GOARCH, terraformVersion),
ApiUrlOverride: data.Get("api_url_override").(string),
ServiceRegion: serviceRegion,
}

useAuthTokenType := pagerduty.AuthTokenTypeAPIToken
if attr, ok := data.GetOk("use_app_oauth_scoped_token"); ok {
config.AppOauthScopedTokenParams = expandAppOauthTokenParams(attr)
config.AppOauthScopedTokenParams.Region = serviceRegion
useAuthTokenType = pagerduty.AuthTokenTypeUseAppCredentials
if err := validateAuthMethodConfig(data); err != nil {
diag := diag.Diagnostic{
Severity: diag.Warning,
Summary: fmt.Sprint("`token` and `use_app_oauth_scoped_token` are both configured at the same time"),
Detail: err.Error(),
}
diags = append(diags, diag)
}
}

config.APITokenType = &useAuthTokenType

log.Println("[INFO] Initializing PagerDuty client")
return &config, nil
return &config, diags
}

func expandAppOauthTokenParams(v interface{}) *persistentconfig.AppOauthScopedTokenParams {
aotp := &persistentconfig.AppOauthScopedTokenParams{}

i := v.([]interface{})[0]
if isNilFunc(i) {
return nil
}
mi := i.(map[string]interface{})

aotp.ClientID = mi["pd_client_id"].(string)
aotp.ClientSecret = mi["pd_client_secret"].(string)
aotp.PDSubDomain = mi["pd_subdomain"].(string)

return aotp
}

var validationAuthMethodConfigWarning = "PagerDuty Provider has been set to authenticate API calls utilizing API token and App Oauth token at same time, in this scenario the use of App Oauth token is prioritised over API token authentication configuration. It is recommended to explicitely set just one authentication method.\nWe also suggest you to check your environment variables in case `token` being automatically read by Provider configuration through `PAGERDUTY_TOKEN` environment variable."

func validateAuthMethodConfig(data *schema.ResourceData) error {
_, isSetAPIToken := data.GetOk("token")
_, isSetUseAppOauthScopedToken := data.GetOk("use_app_oauth_scoped_token")

if isSetUseAppOauthScopedToken && isSetAPIToken {
return fmt.Errorf(validationAuthMethodConfigWarning)
}

return nil
}
Loading
Loading