From 8ef6d3e3ad00a595d0e169df3f588dabe028bf0b Mon Sep 17 00:00:00 2001 From: Soulou Date: Fri, 27 Mar 2020 21:18:09 +0100 Subject: [PATCH 1/2] Update deps --- Gopkg.lock | 20 +- Gopkg.toml | 2 +- addons/provision.go | 5 +- addons/upgrade.go | 5 +- cmd/autocomplete/notifications.go | 29 --- .../github.com/Scalingo/go-scalingo/addons.go | 48 +++-- .../Scalingo/go-scalingo/auth_mock.go | 15 +- .../github.com/Scalingo/go-scalingo/client.go | 5 +- .../go-scalingo/events_boilerplate.go | 9 - .../Scalingo/go-scalingo/events_structs.go | 189 +++++++++--------- .../go-scalingo/http/api_token_generator.go | 43 +++- .../go-scalingo/http/httpmock/client_mock.go | 30 +++ .../Scalingo/go-scalingo/notifications.go | 58 ------ .../Scalingo/go-scalingo/region_migrations.go | 1 + .../Scalingo/go-scalingo/scm_repo_link.go | 2 - .../Scalingo/go-scalingo/version.go | 2 +- vendor/github.com/dgrijalva/jwt-go/LICENSE | 8 + vendor/github.com/dgrijalva/jwt-go/claims.go | 134 +++++++++++++ vendor/github.com/dgrijalva/jwt-go/doc.go | 4 + vendor/github.com/dgrijalva/jwt-go/ecdsa.go | 148 ++++++++++++++ .../dgrijalva/jwt-go/ecdsa_utils.go | 67 +++++++ vendor/github.com/dgrijalva/jwt-go/errors.go | 59 ++++++ vendor/github.com/dgrijalva/jwt-go/hmac.go | 95 +++++++++ .../github.com/dgrijalva/jwt-go/map_claims.go | 94 +++++++++ vendor/github.com/dgrijalva/jwt-go/none.go | 52 +++++ vendor/github.com/dgrijalva/jwt-go/parser.go | 148 ++++++++++++++ vendor/github.com/dgrijalva/jwt-go/rsa.go | 101 ++++++++++ vendor/github.com/dgrijalva/jwt-go/rsa_pss.go | 126 ++++++++++++ .../github.com/dgrijalva/jwt-go/rsa_utils.go | 101 ++++++++++ .../dgrijalva/jwt-go/signing_method.go | 35 ++++ vendor/github.com/dgrijalva/jwt-go/token.go | 108 ++++++++++ vendor/github.com/golang/mock/gomock/call.go | 55 +++-- .../github.com/golang/mock/gomock/callset.go | 6 +- .../golang/mock/gomock/controller.go | 121 +++++++---- .../github.com/golang/mock/gomock/matchers.go | 166 ++++++++++++++- 35 files changed, 1792 insertions(+), 299 deletions(-) delete mode 100644 cmd/autocomplete/notifications.go delete mode 100644 vendor/github.com/Scalingo/go-scalingo/notifications.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/LICENSE create mode 100644 vendor/github.com/dgrijalva/jwt-go/claims.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/doc.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/ecdsa.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/errors.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/hmac.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/map_claims.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/none.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/parser.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_pss.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/rsa_utils.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/signing_method.go create mode 100644 vendor/github.com/dgrijalva/jwt-go/token.go diff --git a/Gopkg.lock b/Gopkg.lock index 4899b7e6a..c1a62a2ec 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -26,7 +26,7 @@ revision = "8eb48cc6f27eafda8e3a9627edba494a1d229a01" [[projects]] - digest = "1:841b02745d3c178285fe3fd510a7faaa87651c4c9939979805edb56040d28fbc" + digest = "1:c4592480d532e142014fcc5d96919df5a1e881f4236668a40ccf8a585008c666" name = "github.com/Scalingo/go-scalingo" packages = [ ".", @@ -37,8 +37,8 @@ "io", ] pruneopts = "NUT" - revision = "226f5e46f779d41b3a3174f78571f4d8687b63c2" - version = "v3.0.8" + revision = "fcb1b88a27d3a94c94ac28b1f01598072afc9e8b" + version = "v4.3.1" [[projects]] digest = "1:a1dcc4e2d5a5980c31901ea884435b64917fdd523eacb5d6171023b80eaa25a8" @@ -104,6 +104,14 @@ pruneopts = "NUT" revision = "83f37f9c154a678179d11e218bff73ebe5717f99" +[[projects]] + digest = "1:7a6852b35eb5bbc184561443762d225116ae630c26a7c4d90546619f1e7d2ad2" + name = "github.com/dgrijalva/jwt-go" + packages = ["."] + pruneopts = "NUT" + revision = "06ea1031745cb8b3dab3f6a236daf2b0aa468b7e" + version = "v3.2.0" + [[projects]] digest = "1:b7ffca49e9cfd3dfb04a8e0a59347708c6f78f68476a32c5e0a0edca5d1b258c" name = "github.com/dustin/go-humanize" @@ -136,12 +144,12 @@ version = "v1.6.0" [[projects]] - digest = "1:bc38c7c481812e178d85160472e231c5e1c9a7f5845d67e23ee4e706933c10d8" + digest = "1:7ae311278f7ccaa724de8f2cdec0a507ba3ee6dea8c77237e8157bcf64b0f28b" name = "github.com/golang/mock" packages = ["gomock"] pruneopts = "NUT" - revision = "c34cdb4725f4c3844d095133c6e40e448b86589b" - version = "v1.1.1" + revision = "3a35fb6e3e18b9dbfee291262260dee7372d2a92" + version = "v1.4.3" [[projects]] digest = "1:e45cda0965bf660df6421580001ef40e322a9b29b7b27e9f69568d9a999ec9b7" diff --git a/Gopkg.toml b/Gopkg.toml index a4986d98e..686f7e5e2 100644 --- a/Gopkg.toml +++ b/Gopkg.toml @@ -26,7 +26,7 @@ [[constraint]] name = "github.com/Scalingo/go-scalingo" - version = "^3" + version = "^4" [[constraint]] branch = "master" diff --git a/addons/provision.go b/addons/provision.go index 754093ff8..a16a111d4 100644 --- a/addons/provision.go +++ b/addons/provision.go @@ -29,7 +29,10 @@ func Provision(app, addon, plan string) error { return errgo.Mask(err, errgo.Any) } - params, err := c.AddonProvision(app, addon, planID) + params, err := c.AddonProvision(app, scalingo.AddonProvisionParams{ + AddonProviderID: addon, + PlanID: planID, + }) if err != nil { if !utils.IsPaymentRequiredAndFreeTrialExceededError(err) { return errgo.Notef(err, "Fail to provision addon %v", addon) diff --git a/addons/upgrade.go b/addons/upgrade.go index 17475d9d8..9b9ac413c 100644 --- a/addons/upgrade.go +++ b/addons/upgrade.go @@ -3,6 +3,7 @@ package addons import ( "github.com/Scalingo/cli/config" "github.com/Scalingo/cli/io" + "github.com/Scalingo/go-scalingo" "gopkg.in/errgo.v1" ) @@ -30,7 +31,9 @@ func Upgrade(app, addonID, plan string) error { return errgo.Mask(err, errgo.Any) } - params, err := c.AddonUpgrade(app, addon.ID, planID) + params, err := c.AddonUpgrade(app, addon.ID, scalingo.AddonUpgradeParams{ + PlanID: planID, + }) if err != nil { return errgo.Mask(err, errgo.Any) } diff --git a/cmd/autocomplete/notifications.go b/cmd/autocomplete/notifications.go deleted file mode 100644 index 3b95c462b..000000000 --- a/cmd/autocomplete/notifications.go +++ /dev/null @@ -1,29 +0,0 @@ -package autocomplete - -import ( - "fmt" - - "github.com/Scalingo/cli/config" - "github.com/urfave/cli" - "gopkg.in/errgo.v1" -) - -func NotificationsRemoveAutoComplete(c *cli.Context) error { - appName := CurrentAppCompletion(c) - if appName == "" { - return nil - } - - client, err := config.ScalingoClient() - if err != nil { - return errgo.Notef(err, "fail to get Scalingo client") - } - resources, err := client.NotificationsList(appName) - if err == nil { - for _, resource := range resources { - fmt.Println(resource.ID) - } - } - - return nil -} diff --git a/vendor/github.com/Scalingo/go-scalingo/addons.go b/vendor/github.com/Scalingo/go-scalingo/addons.go index 097f591ae..0c16d36e4 100644 --- a/vendor/github.com/Scalingo/go-scalingo/addons.go +++ b/vendor/github.com/Scalingo/go-scalingo/addons.go @@ -10,9 +10,9 @@ import ( type AddonsService interface { AddonsList(app string) ([]*Addon, error) - AddonProvision(app, addon, planID string) (AddonRes, error) + AddonProvision(app string, params AddonProvisionParams) (AddonRes, error) AddonDestroy(app, addonID string) error - AddonUpgrade(app, addonID, planID string) (AddonRes, error) + AddonUpgrade(app, addonID string, params AddonUpgradeParams) (AddonRes, error) AddonToken(app, addonID string) (string, error) AddonLogsURL(app, addonID string) (string, error) } @@ -28,14 +28,12 @@ const ( ) type Addon struct { - ID string `json:"id"` - AppID string `json:"app_id"` - ResourceID string `json:"resource_id"` - PlanID string `json:"plan_id"` - AddonProviderID string `json:"addon_provider_id"` - Status AddonStatus `json:"status"` - Plan *Plan `json:"plan"` - AddonProvider *AddonProvider `json:"addon_provider"` + ID string `json:"id"` + AppID string `json:"app_id"` + ResourceID string `json:"resource_id"` + Status AddonStatus `json:"status"` + Plan *Plan `json:"plan"` + AddonProvider *AddonProvider `json:"addon_provider"` } type AddonsRes struct { @@ -79,9 +77,20 @@ func (c *Client) AddonShow(app, addonID string) (Addon, error) { return addonRes.Addon, nil } -func (c *Client) AddonProvision(app, addon, planID string) (AddonRes, error) { +// AddonProvisionParams gathers all arguments which can be sent to provision an addon +type AddonProvisionParams struct { + AddonProviderID string `json:"addon_provider_id"` + PlanID string `json:"plan_id"` + Options map[string]string `json:"options"` +} + +type AddonProvisionParamsWrapper struct { + Addon AddonProvisionParams `json:"addon"` +} + +func (c *Client) AddonProvision(app string, params AddonProvisionParams) (AddonRes, error) { var addonRes AddonRes - err := c.ScalingoAPI().SubresourceAdd("apps", app, "addons", AddonRes{Addon: Addon{AddonProviderID: addon, PlanID: planID}}, &addonRes) + err := c.ScalingoAPI().SubresourceAdd("apps", app, "addons", AddonProvisionParamsWrapper{params}, &addonRes) if err != nil { return AddonRes{}, errgo.Mask(err, errgo.Any) } @@ -92,9 +101,20 @@ func (c *Client) AddonDestroy(app, addonID string) error { return c.ScalingoAPI().SubresourceDelete("apps", app, "addons", addonID) } -func (c *Client) AddonUpgrade(app, addonID, planID string) (AddonRes, error) { +type AddonUpgradeParams struct { + PlanID string `json:"plan_id"` +} + +type AddonUpgradeParamsWrapper struct { + Addon AddonUpgradeParams `json:"addon"` +} + +func (c *Client) AddonUpgrade(app, addonID string, params AddonUpgradeParams) (AddonRes, error) { var addonRes AddonRes - err := c.ScalingoAPI().SubresourceUpdate("apps", app, "addons", addonID, AddonRes{Addon: Addon{PlanID: planID}}, &addonRes) + err := c.ScalingoAPI().SubresourceUpdate( + "apps", app, "addons", addonID, + AddonUpgradeParamsWrapper{Addon: params}, &addonRes, + ) if err != nil { return AddonRes{}, errgo.Mask(err, errgo.Any) } diff --git a/vendor/github.com/Scalingo/go-scalingo/auth_mock.go b/vendor/github.com/Scalingo/go-scalingo/auth_mock.go index 61c5a0031..d0e630358 100644 --- a/vendor/github.com/Scalingo/go-scalingo/auth_mock.go +++ b/vendor/github.com/Scalingo/go-scalingo/auth_mock.go @@ -2,19 +2,32 @@ package scalingo import ( "bytes" + "fmt" "io/ioutil" "net/http" + "time" httpclient "github.com/Scalingo/go-scalingo/http" "github.com/Scalingo/go-scalingo/http/httpmock" + "github.com/dgrijalva/jwt-go" gomock "github.com/golang/mock/gomock" ) func MockAuth(ctrl *gomock.Controller) *httpmock.MockClient { mock := httpmock.NewMockClient(ctrl) + mock.EXPECT().Do(gomock.Any()).DoAndReturn(func(_ *httpclient.APIRequest) (*http.Response, error) { + claims := &jwt.StandardClaims{ + ExpiresAt: time.Now().Add(5 * time.Minute).Unix(), + } + jwtToken := jwt.NewWithClaims(jwt.SigningMethodNone, claims) + jwt, err := jwtToken.SignedString(jwt.UnsafeAllowNoneSignatureType) + if err != nil { + return nil, err + } + return &http.Response{ - Body: ioutil.NopCloser(bytes.NewBuffer([]byte(`{"token": "toto"}`))), + Body: ioutil.NopCloser(bytes.NewBuffer([]byte(fmt.Sprintf(`{"token": "%v"}`, jwt)))), }, nil }).AnyTimes() return mock diff --git a/vendor/github.com/Scalingo/go-scalingo/client.go b/vendor/github.com/Scalingo/go-scalingo/client.go index e3d8438cb..dec3e05ca 100644 --- a/vendor/github.com/Scalingo/go-scalingo/client.go +++ b/vendor/github.com/Scalingo/go-scalingo/client.go @@ -25,7 +25,6 @@ type API interface { LogsArchivesService LogsService NotificationPlatformsService - NotificationsService NotifiersService OperationsService RegionsService @@ -141,7 +140,11 @@ func (c *Client) AuthAPI() http.Client { if c.authClient != nil { return c.authClient } + var tokenGenerator http.TokenGenerator + if c.config.StaticTokenGenerator != nil { + tokenGenerator = c.config.StaticTokenGenerator + } if len(c.config.APIToken) != 0 { tokenGenerator = http.NewAPITokenGenerator(c, c.config.APIToken) } diff --git a/vendor/github.com/Scalingo/go-scalingo/events_boilerplate.go b/vendor/github.com/Scalingo/go-scalingo/events_boilerplate.go index 475b95a51..366002150 100644 --- a/vendor/github.com/Scalingo/go-scalingo/events_boilerplate.go +++ b/vendor/github.com/Scalingo/go-scalingo/events_boilerplate.go @@ -96,15 +96,6 @@ func (e *EventEditVariableType) TypeDataPtr() interface{} { func (e *EventEditVariablesType) TypeDataPtr() interface{} { return &e.TypeData } -func (e *EventNewNotificationType) TypeDataPtr() interface{} { - return &e.TypeData -} -func (e *EventEditNotificationType) TypeDataPtr() interface{} { - return &e.TypeData -} -func (e *EventDeleteNotificationType) TypeDataPtr() interface{} { - return &e.TypeData -} func (e *EventDeleteVariableType) TypeDataPtr() interface{} { return &e.TypeData } diff --git a/vendor/github.com/Scalingo/go-scalingo/events_structs.go b/vendor/github.com/Scalingo/go-scalingo/events_structs.go index d69366dae..be43306ab 100644 --- a/vendor/github.com/Scalingo/go-scalingo/events_structs.go +++ b/vendor/github.com/Scalingo/go-scalingo/events_structs.go @@ -64,54 +64,54 @@ type EventUser struct { type EventTypeName string const ( - EventNewUser EventTypeName = "new_user" - EventNewApp EventTypeName = "new_app" - EventEditApp EventTypeName = "edit_app" - EventDeleteApp EventTypeName = "delete_app" - EventRenameApp EventTypeName = "rename_app" - EventTransferApp EventTypeName = "transfer_app" - EventRestart EventTypeName = "restart" - EventScale EventTypeName = "scale" - EventStopApp EventTypeName = "stop_app" - EventCrash EventTypeName = "crash" - EventDeployment EventTypeName = "deployment" - EventLinkSCM EventTypeName = "link_scm" - EventUnlinkSCM EventTypeName = "unlink_scm" - EventNewIntegration EventTypeName = "new_integration" - EventDeleteIntegration EventTypeName = "delete_integration" - EventAuthorizeGithub EventTypeName = "authorize_github" - EventRevokeGithub EventTypeName = "revoke_github" - EventRun EventTypeName = "run" - EventNewDomain EventTypeName = "new_domain" - EventEditDomain EventTypeName = "edit_domain" - EventDeleteDomain EventTypeName = "delete_domain" - EventNewAddon EventTypeName = "new_addon" - EventUpgradeAddon EventTypeName = "upgrade_addon" - EventUpgradeDatabase EventTypeName = "upgrade_database" - EventDeleteAddon EventTypeName = "delete_addon" - EventResumeAddon EventTypeName = "resume_addon" - EventSuspendAddon EventTypeName = "suspend_addon" - EventNewCollaborator EventTypeName = "new_collaborator" - EventAcceptCollaborator EventTypeName = "accept_collaborator" - EventDeleteCollaborator EventTypeName = "delete_collaborator" - EventNewVariable EventTypeName = "new_variable" - EventEditVariable EventTypeName = "edit_variable" - EventEditVariables EventTypeName = "edit_variables" - EventDeleteVariable EventTypeName = "delete_variable" - EventNewNotification EventTypeName = "new_notification" - EventEditNotification EventTypeName = "edit_notification" - EventDeleteNotification EventTypeName = "delete_notification" - EventAddCredit EventTypeName = "add_credit" - EventAddPaymentMethod EventTypeName = "add_payment_method" - EventAddVoucher EventTypeName = "add_voucher" - EventNewKey EventTypeName = "new_key" - EventDeleteKey EventTypeName = "delete_key" - EventPaymentAttempt EventTypeName = "payment_attempt" - EventNewAlert EventTypeName = "new_alert" - EventAlert EventTypeName = "alert" - EventDeleteAlert EventTypeName = "delete_alert" - EventNewAutoscaler EventTypeName = "new_autoscaler" - EventDeleteAutoscaler EventTypeName = "delete_autoscaler" + EventNewUser EventTypeName = "new_user" + EventNewApp EventTypeName = "new_app" + EventEditApp EventTypeName = "edit_app" + EventDeleteApp EventTypeName = "delete_app" + EventRenameApp EventTypeName = "rename_app" + EventTransferApp EventTypeName = "transfer_app" + EventRestart EventTypeName = "restart" + EventScale EventTypeName = "scale" + EventStopApp EventTypeName = "stop_app" + EventCrash EventTypeName = "crash" + EventDeployment EventTypeName = "deployment" + EventLinkSCM EventTypeName = "link_scm" + EventUnlinkSCM EventTypeName = "unlink_scm" + EventNewIntegration EventTypeName = "new_integration" + EventDeleteIntegration EventTypeName = "delete_integration" + EventAuthorizeGithub EventTypeName = "authorize_github" + EventRevokeGithub EventTypeName = "revoke_github" + EventRun EventTypeName = "run" + EventNewDomain EventTypeName = "new_domain" + EventEditDomain EventTypeName = "edit_domain" + EventDeleteDomain EventTypeName = "delete_domain" + EventNewAddon EventTypeName = "new_addon" + EventUpgradeAddon EventTypeName = "upgrade_addon" + EventUpgradeDatabase EventTypeName = "upgrade_database" + EventDeleteAddon EventTypeName = "delete_addon" + EventResumeAddon EventTypeName = "resume_addon" + EventSuspendAddon EventTypeName = "suspend_addon" + EventNewCollaborator EventTypeName = "new_collaborator" + EventAcceptCollaborator EventTypeName = "accept_collaborator" + EventDeleteCollaborator EventTypeName = "delete_collaborator" + EventNewVariable EventTypeName = "new_variable" + EventEditVariable EventTypeName = "edit_variable" + EventEditVariables EventTypeName = "edit_variables" + EventDeleteVariable EventTypeName = "delete_variable" + EventAddCredit EventTypeName = "add_credit" + EventAddPaymentMethod EventTypeName = "add_payment_method" + EventAddVoucher EventTypeName = "add_voucher" + EventNewKey EventTypeName = "new_key" + EventDeleteKey EventTypeName = "delete_key" + EventPaymentAttempt EventTypeName = "payment_attempt" + EventNewAlert EventTypeName = "new_alert" + EventAlert EventTypeName = "alert" + EventDeleteAlert EventTypeName = "delete_alert" + EventNewAutoscaler EventTypeName = "new_autoscaler" + EventDeleteAutoscaler EventTypeName = "delete_autoscaler" + EventAddonUpdated EventTypeName = "addon_updated" + EventStartRegionMigration EventTypeName = "start_region_migration" + // EventLinkGithub and EventUnlinkGithub events are kept for // retro-compatibility. They are replaced by SCM events. EventLinkGithub EventTypeName = "link_github" @@ -685,47 +685,6 @@ type EventDeleteVariableTypeData struct { EventVariable } -type EventNotification struct { - NotificationType string `json:"notification_type"` - Active bool `json:"active"` - WebhookURL string `json:"webhook_url"` -} - -func (n *EventNotification) String() string { - state := "disabled" - if n.Active { - state = "enabled" - } - return fmt.Sprintf("%s: %s (%s)", n.NotificationType, n.WebhookURL, state) -} - -type EventNewNotificationType struct { - Event - TypeData EventNotification `json:"type_data"` -} - -func (ev *EventNewNotificationType) String() string { - return ev.TypeData.String() -} - -type EventEditNotificationType struct { - Event - TypeData EventNotification `json:"type_data"` -} - -func (ev *EventEditNotificationType) String() string { - return ev.TypeData.String() -} - -type EventDeleteNotificationType struct { - Event - TypeData EventNotification `json:"type_data"` -} - -func (ev *EventDeleteNotificationType) String() string { - return ev.TypeData.String() -} - type EventPaymentAttemptTypeData struct { Amount float32 `json:"amount"` PaymentMethod string `json:"payment_method"` @@ -860,6 +819,48 @@ func (ev *EventDeleteAutoscalerType) String() string { return fmt.Sprintf("Alert deleted about %s on container %s", d.Metric, d.ContainerType) } +type EventStartRegionMigrationTypeData struct { + MigrationID string `json:"migration_id"` + Destination string `json:"destination"` + Source string `json:"source"` + DstAppName string `json:"dst_app_name"` +} + +type EventStartRegionMigrationType struct { + Event + TypeData EventStartRegionMigrationTypeData `json:"type_data"` +} + +func (ev *EventStartRegionMigrationType) String() string { + return fmt.Sprintf("Application region migration started from %s to %s/%s", ev.TypeData.Source, ev.TypeData.Destination, ev.TypeData.DstAppName) +} + +type EventAddonUpdatedTypeData struct { + AddonID string `json:"addon_id"` + AddonPlanName string `json:"addon_plan_name"` + AddonResourceID string `json:"addon_resource_id"` + AddonProviderID string `json:"addon_provider_id"` + AddonProviderName string `json:"addon_provider_name"` + + // Status has only two items when is updated, the old value and the new value, in this order + Status []AddonStatus `json:"status"` + // AttributesChanged contain names of changed attributes + AttributesChanged []string `json:"attributes_changed"` +} + +type EventAddonUpdatedType struct { + Event + TypeData EventAddonUpdatedTypeData `json:"type_data"` +} + +func (ev *EventAddonUpdatedType) String() string { + d := ev.TypeData + return fmt.Sprintf( + "Addon %s %s updated, status %v -> %v", + d.AddonProviderName, d.AddonResourceID, d.Status[0], d.Status[1], + ) +} + func (pev *Event) Specialize() DetailedEvent { var e DetailedEvent ev := *pev @@ -932,12 +933,6 @@ func (pev *Event) Specialize() DetailedEvent { e = &EventEditVariablesType{Event: ev} case EventDeleteVariable: e = &EventDeleteVariableType{Event: ev} - case EventNewNotification: - e = &EventNewNotificationType{Event: ev} - case EventEditNotification: - e = &EventEditNotificationType{Event: ev} - case EventDeleteNotification: - e = &EventDeleteNotificationType{Event: ev} case EventAddCredit: e = &EventAddCreditType{Event: ev} case EventAddPaymentMethod: @@ -960,6 +955,10 @@ func (pev *Event) Specialize() DetailedEvent { e = &EventNewAutoscalerType{Event: ev} case EventDeleteAutoscaler: e = &EventDeleteAutoscalerType{Event: ev} + case EventStartRegionMigration: + e = &EventStartRegionMigrationType{Event: ev} + case EventAddonUpdated: + e = &EventAddonUpdatedType{Event: ev} // Deprecated events. Replaced by equivalent with SCM in the name instead of // Github case EventLinkGithub: diff --git a/vendor/github.com/Scalingo/go-scalingo/http/api_token_generator.go b/vendor/github.com/Scalingo/go-scalingo/http/api_token_generator.go index ddde5d3a9..98987c8c0 100644 --- a/vendor/github.com/Scalingo/go-scalingo/http/api_token_generator.go +++ b/vendor/github.com/Scalingo/go-scalingo/http/api_token_generator.go @@ -1,6 +1,10 @@ package http import ( + "time" + + "github.com/dgrijalva/jwt-go" + errgo "gopkg.in/errgo.v1" ) @@ -9,11 +13,19 @@ type TokensService interface { } type APITokenGenerator struct { - APIToken string `json:"token"` - TokensService TokensService `json:"-"` + APIToken string + TokensService TokensService + + // Internal cache of JWT info + currentJWT string + currentJWTexp time.Time } -func NewAPITokenGenerator(tokensService TokensService, apiToken string) TokenGenerator { +type apiJWTClaims struct { + jwt.StandardClaims +} + +func NewAPITokenGenerator(tokensService TokensService, apiToken string) *APITokenGenerator { return &APITokenGenerator{ APIToken: apiToken, TokensService: tokensService, @@ -21,9 +33,26 @@ func NewAPITokenGenerator(tokensService TokensService, apiToken string) TokenGen } func (t *APITokenGenerator) GetAccessToken() (string, error) { - accessToken, err := t.TokensService.TokenExchange(t.APIToken) - if err != nil { - return "", errgo.Notef(err, "fail to get access token") + // Ask for a new JWT if there wasn't any or if the current token will expire in less than 5 minutes + if t.currentJWTexp.IsZero() || t.currentJWTexp.Sub(time.Now()) < 5*time.Minute { + jwtToken, err := t.TokensService.TokenExchange(t.APIToken) + if err != nil { + return "", errgo.Notef(err, "fail to get access token") + } + token, err := jwt.ParseWithClaims(jwtToken, &apiJWTClaims{}, nil) + // If token is nil, nothing has been parsed, if it's not, err will be a + // ValidatingError we want to ignore + if token == nil { + return "", errgo.Notef(err, "fail to parse jwt token") + } + + if claims, ok := token.Claims.(*apiJWTClaims); ok { + t.currentJWTexp = time.Unix(claims.ExpiresAt, 0) + } else { + return "", errgo.Notef(err, "invalid exp date for jwt token: %v", token.Claims) + } + + t.currentJWT = jwtToken } - return accessToken, nil + return t.currentJWT, nil } diff --git a/vendor/github.com/Scalingo/go-scalingo/http/httpmock/client_mock.go b/vendor/github.com/Scalingo/go-scalingo/http/httpmock/client_mock.go index a5c7eddac..b96bab030 100644 --- a/vendor/github.com/Scalingo/go-scalingo/http/httpmock/client_mock.go +++ b/vendor/github.com/Scalingo/go-scalingo/http/httpmock/client_mock.go @@ -37,6 +37,7 @@ func (m *MockClient) EXPECT() *MockClientMockRecorder { // BaseURL mocks base method func (m *MockClient) BaseURL() string { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "BaseURL") ret0, _ := ret[0].(string) return ret0 @@ -44,11 +45,13 @@ func (m *MockClient) BaseURL() string { // BaseURL indicates an expected call of BaseURL func (mr *MockClientMockRecorder) BaseURL() *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "BaseURL", reflect.TypeOf((*MockClient)(nil).BaseURL)) } // Do mocks base method func (m *MockClient) Do(arg0 *http.APIRequest) (*http0.Response, error) { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "Do", arg0) ret0, _ := ret[0].(*http0.Response) ret1, _ := ret[1].(error) @@ -57,11 +60,13 @@ func (m *MockClient) Do(arg0 *http.APIRequest) (*http0.Response, error) { // Do indicates an expected call of Do func (mr *MockClientMockRecorder) Do(arg0 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Do", reflect.TypeOf((*MockClient)(nil).Do), arg0) } // DoRequest mocks base method func (m *MockClient) DoRequest(arg0 *http.APIRequest, arg1 interface{}) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "DoRequest", arg0, arg1) ret0, _ := ret[0].(error) return ret0 @@ -69,11 +74,13 @@ func (m *MockClient) DoRequest(arg0 *http.APIRequest, arg1 interface{}) error { // DoRequest indicates an expected call of DoRequest func (mr *MockClientMockRecorder) DoRequest(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DoRequest", reflect.TypeOf((*MockClient)(nil).DoRequest), arg0, arg1) } // HTTPClient mocks base method func (m *MockClient) HTTPClient() *http0.Client { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "HTTPClient") ret0, _ := ret[0].(*http0.Client) return ret0 @@ -81,11 +88,13 @@ func (m *MockClient) HTTPClient() *http0.Client { // HTTPClient indicates an expected call of HTTPClient func (mr *MockClientMockRecorder) HTTPClient() *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HTTPClient", reflect.TypeOf((*MockClient)(nil).HTTPClient)) } // ResourceAdd mocks base method func (m *MockClient) ResourceAdd(arg0 string, arg1, arg2 interface{}) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ResourceAdd", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 @@ -93,11 +102,13 @@ func (m *MockClient) ResourceAdd(arg0 string, arg1, arg2 interface{}) error { // ResourceAdd indicates an expected call of ResourceAdd func (mr *MockClientMockRecorder) ResourceAdd(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResourceAdd", reflect.TypeOf((*MockClient)(nil).ResourceAdd), arg0, arg1, arg2) } // ResourceDelete mocks base method func (m *MockClient) ResourceDelete(arg0, arg1 string) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ResourceDelete", arg0, arg1) ret0, _ := ret[0].(error) return ret0 @@ -105,11 +116,13 @@ func (m *MockClient) ResourceDelete(arg0, arg1 string) error { // ResourceDelete indicates an expected call of ResourceDelete func (mr *MockClientMockRecorder) ResourceDelete(arg0, arg1 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResourceDelete", reflect.TypeOf((*MockClient)(nil).ResourceDelete), arg0, arg1) } // ResourceGet mocks base method func (m *MockClient) ResourceGet(arg0, arg1 string, arg2, arg3 interface{}) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ResourceGet", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) return ret0 @@ -117,11 +130,13 @@ func (m *MockClient) ResourceGet(arg0, arg1 string, arg2, arg3 interface{}) erro // ResourceGet indicates an expected call of ResourceGet func (mr *MockClientMockRecorder) ResourceGet(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResourceGet", reflect.TypeOf((*MockClient)(nil).ResourceGet), arg0, arg1, arg2, arg3) } // ResourceList mocks base method func (m *MockClient) ResourceList(arg0 string, arg1, arg2 interface{}) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ResourceList", arg0, arg1, arg2) ret0, _ := ret[0].(error) return ret0 @@ -129,11 +144,13 @@ func (m *MockClient) ResourceList(arg0 string, arg1, arg2 interface{}) error { // ResourceList indicates an expected call of ResourceList func (mr *MockClientMockRecorder) ResourceList(arg0, arg1, arg2 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResourceList", reflect.TypeOf((*MockClient)(nil).ResourceList), arg0, arg1, arg2) } // ResourceUpdate mocks base method func (m *MockClient) ResourceUpdate(arg0, arg1 string, arg2, arg3 interface{}) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "ResourceUpdate", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) return ret0 @@ -141,11 +158,13 @@ func (m *MockClient) ResourceUpdate(arg0, arg1 string, arg2, arg3 interface{}) e // ResourceUpdate indicates an expected call of ResourceUpdate func (mr *MockClientMockRecorder) ResourceUpdate(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ResourceUpdate", reflect.TypeOf((*MockClient)(nil).ResourceUpdate), arg0, arg1, arg2, arg3) } // SubresourceAdd mocks base method func (m *MockClient) SubresourceAdd(arg0, arg1, arg2 string, arg3, arg4 interface{}) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SubresourceAdd", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(error) return ret0 @@ -153,11 +172,13 @@ func (m *MockClient) SubresourceAdd(arg0, arg1, arg2 string, arg3, arg4 interfac // SubresourceAdd indicates an expected call of SubresourceAdd func (mr *MockClientMockRecorder) SubresourceAdd(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubresourceAdd", reflect.TypeOf((*MockClient)(nil).SubresourceAdd), arg0, arg1, arg2, arg3, arg4) } // SubresourceDelete mocks base method func (m *MockClient) SubresourceDelete(arg0, arg1, arg2, arg3 string) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SubresourceDelete", arg0, arg1, arg2, arg3) ret0, _ := ret[0].(error) return ret0 @@ -165,11 +186,13 @@ func (m *MockClient) SubresourceDelete(arg0, arg1, arg2, arg3 string) error { // SubresourceDelete indicates an expected call of SubresourceDelete func (mr *MockClientMockRecorder) SubresourceDelete(arg0, arg1, arg2, arg3 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubresourceDelete", reflect.TypeOf((*MockClient)(nil).SubresourceDelete), arg0, arg1, arg2, arg3) } // SubresourceGet mocks base method func (m *MockClient) SubresourceGet(arg0, arg1, arg2, arg3 string, arg4, arg5 interface{}) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SubresourceGet", arg0, arg1, arg2, arg3, arg4, arg5) ret0, _ := ret[0].(error) return ret0 @@ -177,11 +200,13 @@ func (m *MockClient) SubresourceGet(arg0, arg1, arg2, arg3 string, arg4, arg5 in // SubresourceGet indicates an expected call of SubresourceGet func (mr *MockClientMockRecorder) SubresourceGet(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubresourceGet", reflect.TypeOf((*MockClient)(nil).SubresourceGet), arg0, arg1, arg2, arg3, arg4, arg5) } // SubresourceList mocks base method func (m *MockClient) SubresourceList(arg0, arg1, arg2 string, arg3, arg4 interface{}) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SubresourceList", arg0, arg1, arg2, arg3, arg4) ret0, _ := ret[0].(error) return ret0 @@ -189,11 +214,13 @@ func (m *MockClient) SubresourceList(arg0, arg1, arg2 string, arg3, arg4 interfa // SubresourceList indicates an expected call of SubresourceList func (mr *MockClientMockRecorder) SubresourceList(arg0, arg1, arg2, arg3, arg4 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubresourceList", reflect.TypeOf((*MockClient)(nil).SubresourceList), arg0, arg1, arg2, arg3, arg4) } // SubresourceUpdate mocks base method func (m *MockClient) SubresourceUpdate(arg0, arg1, arg2, arg3 string, arg4, arg5 interface{}) error { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "SubresourceUpdate", arg0, arg1, arg2, arg3, arg4, arg5) ret0, _ := ret[0].(error) return ret0 @@ -201,11 +228,13 @@ func (m *MockClient) SubresourceUpdate(arg0, arg1, arg2, arg3 string, arg4, arg5 // SubresourceUpdate indicates an expected call of SubresourceUpdate func (mr *MockClientMockRecorder) SubresourceUpdate(arg0, arg1, arg2, arg3, arg4, arg5 interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SubresourceUpdate", reflect.TypeOf((*MockClient)(nil).SubresourceUpdate), arg0, arg1, arg2, arg3, arg4, arg5) } // TokenGenerator mocks base method func (m *MockClient) TokenGenerator() http.TokenGenerator { + m.ctrl.T.Helper() ret := m.ctrl.Call(m, "TokenGenerator") ret0, _ := ret[0].(http.TokenGenerator) return ret0 @@ -213,5 +242,6 @@ func (m *MockClient) TokenGenerator() http.TokenGenerator { // TokenGenerator indicates an expected call of TokenGenerator func (mr *MockClientMockRecorder) TokenGenerator() *gomock.Call { + mr.mock.ctrl.T.Helper() return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "TokenGenerator", reflect.TypeOf((*MockClient)(nil).TokenGenerator)) } diff --git a/vendor/github.com/Scalingo/go-scalingo/notifications.go b/vendor/github.com/Scalingo/go-scalingo/notifications.go deleted file mode 100644 index a0d5d7405..000000000 --- a/vendor/github.com/Scalingo/go-scalingo/notifications.go +++ /dev/null @@ -1,58 +0,0 @@ -package scalingo - -import "gopkg.in/errgo.v1" - -type NotificationsService interface { - NotificationsList(app string) ([]*Notification, error) - NotificationProvision(app, webHookURL string) (NotificationRes, error) - NotificationUpdate(app, ID, webHookURL string) (NotificationRes, error) - NotificationDestroy(app, ID string) error -} - -var _ NotificationsService = (*Client)(nil) - -type Notification struct { - ID string `json:"id"` - Type string `json:"type"` - WebHookURL string `json:"webhook_url"` - Active bool `json:"active"` -} - -type NotificationRes struct { - Notification Notification `json:"notification"` -} - -type NotificationsRes struct { - Notifications []*Notification `json:"notifications"` -} - -func (c *Client) NotificationsList(app string) ([]*Notification, error) { - var notificationsRes NotificationsRes - err := c.ScalingoAPI().SubresourceList("apps", app, "notifications", nil, ¬ificationsRes) - if err != nil { - return nil, errgo.Mask(err, errgo.Any) - } - return notificationsRes.Notifications, nil -} - -func (c *Client) NotificationProvision(app, webHookURL string) (NotificationRes, error) { - var notificationRes NotificationRes - err := c.ScalingoAPI().SubresourceAdd("apps", app, "notifications", NotificationRes{Notification: Notification{WebHookURL: webHookURL}}, ¬ificationRes) - if err != nil { - return NotificationRes{}, errgo.Mask(err, errgo.Any) - } - return notificationRes, nil -} - -func (c *Client) NotificationUpdate(app, ID, webHookURL string) (NotificationRes, error) { - var notificationRes NotificationRes - err := c.ScalingoAPI().SubresourceUpdate("apps", app, "notifications", ID, NotificationRes{Notification: Notification{WebHookURL: webHookURL, Active: true}}, ¬ificationRes) - if err != nil { - return NotificationRes{}, errgo.Mask(err, errgo.Any) - } - return notificationRes, nil -} - -func (c *Client) NotificationDestroy(app, ID string) error { - return c.ScalingoAPI().SubresourceDelete("apps", app, "notifications", ID) -} diff --git a/vendor/github.com/Scalingo/go-scalingo/region_migrations.go b/vendor/github.com/Scalingo/go-scalingo/region_migrations.go index e67cdac19..0bb2f0f22 100644 --- a/vendor/github.com/Scalingo/go-scalingo/region_migrations.go +++ b/vendor/github.com/Scalingo/go-scalingo/region_migrations.go @@ -47,6 +47,7 @@ type RegionMigration struct { DstAppName string `json:"dst_app_name"` AppID string `json:"app_id"` NewAppID string `json:"new_app_id"` + Source string `json:"source"` Destination string `json:"destination"` Status RegionMigrationStatus `json:"status"` StartedAt time.Time `json:"started_at"` diff --git a/vendor/github.com/Scalingo/go-scalingo/scm_repo_link.go b/vendor/github.com/Scalingo/go-scalingo/scm_repo_link.go index fe27ab53b..9bf906bad 100644 --- a/vendor/github.com/Scalingo/go-scalingo/scm_repo_link.go +++ b/vendor/github.com/Scalingo/go-scalingo/scm_repo_link.go @@ -24,7 +24,6 @@ type SCMRepoLinkCreateParams struct { Source *string `json:"source,omitempty"` Branch *string `json:"branch,omitempty"` AuthIntegrationUUID *string `json:"auth_integration_uuid,omitempty"` - SCMIntegrationUUID *string `json:"scm_integration_uuid,omitempty"` AutoDeployEnabled *bool `json:"auto_deploy_enabled,omitempty"` DeployReviewAppsEnabled *bool `json:"deploy_review_apps_enabled,omitempty"` DestroyOnCloseEnabled *bool `json:"delete_on_close_enabled,omitempty"` @@ -54,7 +53,6 @@ type SCMRepoLink struct { CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` AutoDeployEnabled bool `json:"auto_deploy_enabled"` - SCMIntegrationUUID string `json:"scm_integration_uuid"` AuthIntegrationUUID string `json:"auth_integration_uuid"` DeployReviewAppsEnabled bool `json:"deploy_review_apps_enabled"` DeleteOnCloseEnabled bool `json:"delete_on_close_enabled"` diff --git a/vendor/github.com/Scalingo/go-scalingo/version.go b/vendor/github.com/Scalingo/go-scalingo/version.go index fb8cef506..1fa38aed6 100644 --- a/vendor/github.com/Scalingo/go-scalingo/version.go +++ b/vendor/github.com/Scalingo/go-scalingo/version.go @@ -1,3 +1,3 @@ package scalingo -var Version = "3.0.5" +var Version = "4.3.1" diff --git a/vendor/github.com/dgrijalva/jwt-go/LICENSE b/vendor/github.com/dgrijalva/jwt-go/LICENSE new file mode 100644 index 000000000..df83a9c2f --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/LICENSE @@ -0,0 +1,8 @@ +Copyright (c) 2012 Dave Grijalva + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/vendor/github.com/dgrijalva/jwt-go/claims.go b/vendor/github.com/dgrijalva/jwt-go/claims.go new file mode 100644 index 000000000..f0228f02e --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/claims.go @@ -0,0 +1,134 @@ +package jwt + +import ( + "crypto/subtle" + "fmt" + "time" +) + +// For a type to be a Claims object, it must just have a Valid method that determines +// if the token is invalid for any supported reason +type Claims interface { + Valid() error +} + +// Structured version of Claims Section, as referenced at +// https://tools.ietf.org/html/rfc7519#section-4.1 +// See examples for how to use this with your own claim types +type StandardClaims struct { + Audience string `json:"aud,omitempty"` + ExpiresAt int64 `json:"exp,omitempty"` + Id string `json:"jti,omitempty"` + IssuedAt int64 `json:"iat,omitempty"` + Issuer string `json:"iss,omitempty"` + NotBefore int64 `json:"nbf,omitempty"` + Subject string `json:"sub,omitempty"` +} + +// Validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (c StandardClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + // The claims below are optional, by default, so if they are set to the + // default value in Go, let's not fail the verification for them. + if c.VerifyExpiresAt(now, false) == false { + delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) + vErr.Inner = fmt.Errorf("token is expired by %v", delta) + vErr.Errors |= ValidationErrorExpired + } + + if c.VerifyIssuedAt(now, false) == false { + vErr.Inner = fmt.Errorf("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } + + if c.VerifyNotBefore(now, false) == false { + vErr.Inner = fmt.Errorf("token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} + +// Compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { + return verifyAud(c.Audience, cmp, req) +} + +// Compares the exp claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { + return verifyExp(c.ExpiresAt, cmp, req) +} + +// Compares the iat claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { + return verifyIat(c.IssuedAt, cmp, req) +} + +// Compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { + return verifyIss(c.Issuer, cmp, req) +} + +// Compares the nbf claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { + return verifyNbf(c.NotBefore, cmp, req) +} + +// ----- helpers + +func verifyAud(aud string, cmp string, required bool) bool { + if aud == "" { + return !required + } + if subtle.ConstantTimeCompare([]byte(aud), []byte(cmp)) != 0 { + return true + } else { + return false + } +} + +func verifyExp(exp int64, now int64, required bool) bool { + if exp == 0 { + return !required + } + return now <= exp +} + +func verifyIat(iat int64, now int64, required bool) bool { + if iat == 0 { + return !required + } + return now >= iat +} + +func verifyIss(iss string, cmp string, required bool) bool { + if iss == "" { + return !required + } + if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { + return true + } else { + return false + } +} + +func verifyNbf(nbf int64, now int64, required bool) bool { + if nbf == 0 { + return !required + } + return now >= nbf +} diff --git a/vendor/github.com/dgrijalva/jwt-go/doc.go b/vendor/github.com/dgrijalva/jwt-go/doc.go new file mode 100644 index 000000000..a86dc1a3b --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/doc.go @@ -0,0 +1,4 @@ +// Package jwt is a Go implementation of JSON Web Tokens: http://self-issued.info/docs/draft-jones-json-web-token.html +// +// See README.md for more info. +package jwt diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go new file mode 100644 index 000000000..f97738124 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa.go @@ -0,0 +1,148 @@ +package jwt + +import ( + "crypto" + "crypto/ecdsa" + "crypto/rand" + "errors" + "math/big" +) + +var ( + // Sadly this is missing from crypto/ecdsa compared to crypto/rsa + ErrECDSAVerification = errors.New("crypto/ecdsa: verification error") +) + +// Implements the ECDSA family of signing methods signing methods +// Expects *ecdsa.PrivateKey for signing and *ecdsa.PublicKey for verification +type SigningMethodECDSA struct { + Name string + Hash crypto.Hash + KeySize int + CurveBits int +} + +// Specific instances for EC256 and company +var ( + SigningMethodES256 *SigningMethodECDSA + SigningMethodES384 *SigningMethodECDSA + SigningMethodES512 *SigningMethodECDSA +) + +func init() { + // ES256 + SigningMethodES256 = &SigningMethodECDSA{"ES256", crypto.SHA256, 32, 256} + RegisterSigningMethod(SigningMethodES256.Alg(), func() SigningMethod { + return SigningMethodES256 + }) + + // ES384 + SigningMethodES384 = &SigningMethodECDSA{"ES384", crypto.SHA384, 48, 384} + RegisterSigningMethod(SigningMethodES384.Alg(), func() SigningMethod { + return SigningMethodES384 + }) + + // ES512 + SigningMethodES512 = &SigningMethodECDSA{"ES512", crypto.SHA512, 66, 521} + RegisterSigningMethod(SigningMethodES512.Alg(), func() SigningMethod { + return SigningMethodES512 + }) +} + +func (m *SigningMethodECDSA) Alg() string { + return m.Name +} + +// Implements the Verify method from SigningMethod +// For this verify method, key must be an ecdsa.PublicKey struct +func (m *SigningMethodECDSA) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + // Get the key + var ecdsaKey *ecdsa.PublicKey + switch k := key.(type) { + case *ecdsa.PublicKey: + ecdsaKey = k + default: + return ErrInvalidKeyType + } + + if len(sig) != 2*m.KeySize { + return ErrECDSAVerification + } + + r := big.NewInt(0).SetBytes(sig[:m.KeySize]) + s := big.NewInt(0).SetBytes(sig[m.KeySize:]) + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Verify the signature + if verifystatus := ecdsa.Verify(ecdsaKey, hasher.Sum(nil), r, s); verifystatus == true { + return nil + } else { + return ErrECDSAVerification + } +} + +// Implements the Sign method from SigningMethod +// For this signing method, key must be an ecdsa.PrivateKey struct +func (m *SigningMethodECDSA) Sign(signingString string, key interface{}) (string, error) { + // Get the key + var ecdsaKey *ecdsa.PrivateKey + switch k := key.(type) { + case *ecdsa.PrivateKey: + ecdsaKey = k + default: + return "", ErrInvalidKeyType + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return r, s + if r, s, err := ecdsa.Sign(rand.Reader, ecdsaKey, hasher.Sum(nil)); err == nil { + curveBits := ecdsaKey.Curve.Params().BitSize + + if m.CurveBits != curveBits { + return "", ErrInvalidKey + } + + keyBytes := curveBits / 8 + if curveBits%8 > 0 { + keyBytes += 1 + } + + // We serialize the outpus (r and s) into big-endian byte arrays and pad + // them with zeros on the left to make sure the sizes work out. Both arrays + // must be keyBytes long, and the output must be 2*keyBytes long. + rBytes := r.Bytes() + rBytesPadded := make([]byte, keyBytes) + copy(rBytesPadded[keyBytes-len(rBytes):], rBytes) + + sBytes := s.Bytes() + sBytesPadded := make([]byte, keyBytes) + copy(sBytesPadded[keyBytes-len(sBytes):], sBytes) + + out := append(rBytesPadded, sBytesPadded...) + + return EncodeSegment(out), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go new file mode 100644 index 000000000..d19624b72 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/ecdsa_utils.go @@ -0,0 +1,67 @@ +package jwt + +import ( + "crypto/ecdsa" + "crypto/x509" + "encoding/pem" + "errors" +) + +var ( + ErrNotECPublicKey = errors.New("Key is not a valid ECDSA public key") + ErrNotECPrivateKey = errors.New("Key is not a valid ECDSA private key") +) + +// Parse PEM encoded Elliptic Curve Private Key Structure +func ParseECPrivateKeyFromPEM(key []byte) (*ecdsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParseECPrivateKey(block.Bytes); err != nil { + return nil, err + } + + var pkey *ecdsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PrivateKey); !ok { + return nil, ErrNotECPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 public key +func ParseECPublicKeyFromPEM(key []byte) (*ecdsa.PublicKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } + + var pkey *ecdsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*ecdsa.PublicKey); !ok { + return nil, ErrNotECPublicKey + } + + return pkey, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/errors.go b/vendor/github.com/dgrijalva/jwt-go/errors.go new file mode 100644 index 000000000..1c93024aa --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/errors.go @@ -0,0 +1,59 @@ +package jwt + +import ( + "errors" +) + +// Error constants +var ( + ErrInvalidKey = errors.New("key is invalid") + ErrInvalidKeyType = errors.New("key is of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") +) + +// The errors that might occur when parsing and validating a token +const ( + ValidationErrorMalformed uint32 = 1 << iota // Token is malformed + ValidationErrorUnverifiable // Token could not be verified because of signing problems + ValidationErrorSignatureInvalid // Signature validation failed + + // Standard Claim validation errors + ValidationErrorAudience // AUD validation failed + ValidationErrorExpired // EXP validation failed + ValidationErrorIssuedAt // IAT validation failed + ValidationErrorIssuer // ISS validation failed + ValidationErrorNotValidYet // NBF validation failed + ValidationErrorId // JTI validation failed + ValidationErrorClaimsInvalid // Generic claims validation error +) + +// Helper for constructing a ValidationError with a string error message +func NewValidationError(errorText string, errorFlags uint32) *ValidationError { + return &ValidationError{ + text: errorText, + Errors: errorFlags, + } +} + +// The error from Parse if token is not valid +type ValidationError struct { + Inner error // stores the error returned by external dependencies, i.e.: KeyFunc + Errors uint32 // bitfield. see ValidationError... constants + text string // errors that do not have a valid error just have text +} + +// Validation error is an error type +func (e ValidationError) Error() string { + if e.Inner != nil { + return e.Inner.Error() + } else if e.text != "" { + return e.text + } else { + return "token is invalid" + } +} + +// No errors +func (e *ValidationError) valid() bool { + return e.Errors == 0 +} diff --git a/vendor/github.com/dgrijalva/jwt-go/hmac.go b/vendor/github.com/dgrijalva/jwt-go/hmac.go new file mode 100644 index 000000000..addbe5d40 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/hmac.go @@ -0,0 +1,95 @@ +package jwt + +import ( + "crypto" + "crypto/hmac" + "errors" +) + +// Implements the HMAC-SHA family of signing methods signing methods +// Expects key type of []byte for both signing and validation +type SigningMethodHMAC struct { + Name string + Hash crypto.Hash +} + +// Specific instances for HS256 and company +var ( + SigningMethodHS256 *SigningMethodHMAC + SigningMethodHS384 *SigningMethodHMAC + SigningMethodHS512 *SigningMethodHMAC + ErrSignatureInvalid = errors.New("signature is invalid") +) + +func init() { + // HS256 + SigningMethodHS256 = &SigningMethodHMAC{"HS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodHS256.Alg(), func() SigningMethod { + return SigningMethodHS256 + }) + + // HS384 + SigningMethodHS384 = &SigningMethodHMAC{"HS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodHS384.Alg(), func() SigningMethod { + return SigningMethodHS384 + }) + + // HS512 + SigningMethodHS512 = &SigningMethodHMAC{"HS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodHS512.Alg(), func() SigningMethod { + return SigningMethodHS512 + }) +} + +func (m *SigningMethodHMAC) Alg() string { + return m.Name +} + +// Verify the signature of HSXXX tokens. Returns nil if the signature is valid. +func (m *SigningMethodHMAC) Verify(signingString, signature string, key interface{}) error { + // Verify the key is the right type + keyBytes, ok := key.([]byte) + if !ok { + return ErrInvalidKeyType + } + + // Decode signature, for comparison + sig, err := DecodeSegment(signature) + if err != nil { + return err + } + + // Can we use the specified hashing method? + if !m.Hash.Available() { + return ErrHashUnavailable + } + + // This signing method is symmetric, so we validate the signature + // by reproducing the signature from the signing string and key, then + // comparing that against the provided signature. + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + if !hmac.Equal(sig, hasher.Sum(nil)) { + return ErrSignatureInvalid + } + + // No validation errors. Signature is good. + return nil +} + +// Implements the Sign method from SigningMethod for this signing method. +// Key must be []byte +func (m *SigningMethodHMAC) Sign(signingString string, key interface{}) (string, error) { + if keyBytes, ok := key.([]byte); ok { + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := hmac.New(m.Hash.New, keyBytes) + hasher.Write([]byte(signingString)) + + return EncodeSegment(hasher.Sum(nil)), nil + } + + return "", ErrInvalidKeyType +} diff --git a/vendor/github.com/dgrijalva/jwt-go/map_claims.go b/vendor/github.com/dgrijalva/jwt-go/map_claims.go new file mode 100644 index 000000000..291213c46 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/map_claims.go @@ -0,0 +1,94 @@ +package jwt + +import ( + "encoding/json" + "errors" + // "fmt" +) + +// Claims type that uses the map[string]interface{} for JSON decoding +// This is the default claims type if you don't supply one +type MapClaims map[string]interface{} + +// Compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyAudience(cmp string, req bool) bool { + aud, _ := m["aud"].(string) + return verifyAud(aud, cmp, req) +} + +// Compares the exp claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { + switch exp := m["exp"].(type) { + case float64: + return verifyExp(int64(exp), cmp, req) + case json.Number: + v, _ := exp.Int64() + return verifyExp(v, cmp, req) + } + return req == false +} + +// Compares the iat claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { + switch iat := m["iat"].(type) { + case float64: + return verifyIat(int64(iat), cmp, req) + case json.Number: + v, _ := iat.Int64() + return verifyIat(v, cmp, req) + } + return req == false +} + +// Compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { + iss, _ := m["iss"].(string) + return verifyIss(iss, cmp, req) +} + +// Compares the nbf claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { + switch nbf := m["nbf"].(type) { + case float64: + return verifyNbf(int64(nbf), cmp, req) + case json.Number: + v, _ := nbf.Int64() + return verifyNbf(v, cmp, req) + } + return req == false +} + +// Validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (m MapClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + if m.VerifyExpiresAt(now, false) == false { + vErr.Inner = errors.New("Token is expired") + vErr.Errors |= ValidationErrorExpired + } + + if m.VerifyIssuedAt(now, false) == false { + vErr.Inner = errors.New("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } + + if m.VerifyNotBefore(now, false) == false { + vErr.Inner = errors.New("Token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} diff --git a/vendor/github.com/dgrijalva/jwt-go/none.go b/vendor/github.com/dgrijalva/jwt-go/none.go new file mode 100644 index 000000000..f04d189d0 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/none.go @@ -0,0 +1,52 @@ +package jwt + +// Implements the none signing method. This is required by the spec +// but you probably should never use it. +var SigningMethodNone *signingMethodNone + +const UnsafeAllowNoneSignatureType unsafeNoneMagicConstant = "none signing method allowed" + +var NoneSignatureTypeDisallowedError error + +type signingMethodNone struct{} +type unsafeNoneMagicConstant string + +func init() { + SigningMethodNone = &signingMethodNone{} + NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) + + RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { + return SigningMethodNone + }) +} + +func (m *signingMethodNone) Alg() string { + return "none" +} + +// Only allow 'none' alg type if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Verify(signingString, signature string, key interface{}) (err error) { + // Key must be UnsafeAllowNoneSignatureType to prevent accidentally + // accepting 'none' signing method + if _, ok := key.(unsafeNoneMagicConstant); !ok { + return NoneSignatureTypeDisallowedError + } + // If signing method is none, signature must be an empty string + if signature != "" { + return NewValidationError( + "'none' signing method with non-empty signature", + ValidationErrorSignatureInvalid, + ) + } + + // Accept 'none' signing method. + return nil +} + +// Only allow 'none' signing if UnsafeAllowNoneSignatureType is specified as the key +func (m *signingMethodNone) Sign(signingString string, key interface{}) (string, error) { + if _, ok := key.(unsafeNoneMagicConstant); ok { + return "", nil + } + return "", NoneSignatureTypeDisallowedError +} diff --git a/vendor/github.com/dgrijalva/jwt-go/parser.go b/vendor/github.com/dgrijalva/jwt-go/parser.go new file mode 100644 index 000000000..d6901d9ad --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/parser.go @@ -0,0 +1,148 @@ +package jwt + +import ( + "bytes" + "encoding/json" + "fmt" + "strings" +) + +type Parser struct { + ValidMethods []string // If populated, only these methods will be considered valid + UseJSONNumber bool // Use JSON Number format in JSON decoder + SkipClaimsValidation bool // Skip claims validation during token parsing +} + +// Parse, validate, and return a token. +// keyFunc will receive the parsed token and should return the key for validating. +// If everything is kosher, err will be nil +func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) +} + +func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + token, parts, err := p.ParseUnverified(tokenString, claims) + if err != nil { + return token, err + } + + // Verify signing method is in the required set + if p.ValidMethods != nil { + var signingMethodValid = false + var alg = token.Method.Alg() + for _, m := range p.ValidMethods { + if m == alg { + signingMethodValid = true + break + } + } + if !signingMethodValid { + // signing method is not in the listed set + return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) + } + } + + // Lookup key + var key interface{} + if keyFunc == nil { + // keyFunc was not provided. short circuiting validation + return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) + } + if key, err = keyFunc(token); err != nil { + // keyFunc returned an error + if ve, ok := err.(*ValidationError); ok { + return token, ve + } + return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} + } + + vErr := &ValidationError{} + + // Validate Claims + if !p.SkipClaimsValidation { + if err := token.Claims.Valid(); err != nil { + + // If the Claims Valid returned an error, check if it is a validation error, + // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set + if e, ok := err.(*ValidationError); !ok { + vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} + } else { + vErr = e + } + } + } + + // Perform validation + token.Signature = parts[2] + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + vErr.Inner = err + vErr.Errors |= ValidationErrorSignatureInvalid + } + + if vErr.valid() { + token.Valid = true + return token, nil + } + + return token, vErr +} + +// WARNING: Don't use this method unless you know what you're doing +// +// This method parses the token but doesn't validate the signature. It's only +// ever useful in cases where you know the signature is valid (because it has +// been checked previously in the stack) and you want to extract values from +// it. +func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { + parts = strings.Split(tokenString, ".") + if len(parts) != 3 { + return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) + } + + token = &Token{Raw: tokenString} + + // parse Header + var headerBytes []byte + if headerBytes, err = DecodeSegment(parts[0]); err != nil { + if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { + return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) + } + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + if err = json.Unmarshal(headerBytes, &token.Header); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // parse Claims + var claimBytes []byte + token.Claims = claims + + if claimBytes, err = DecodeSegment(parts[1]); err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) + if p.UseJSONNumber { + dec.UseNumber() + } + // JSON Decode. Special case for map type to avoid weird pointer behavior + if c, ok := token.Claims.(MapClaims); ok { + err = dec.Decode(&c) + } else { + err = dec.Decode(&claims) + } + // Handle decode error + if err != nil { + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + } + + // Lookup signature method + if method, ok := token.Header["alg"].(string); ok { + if token.Method = GetSigningMethod(method); token.Method == nil { + return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) + } + } else { + return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + } + + return token, parts, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa.go b/vendor/github.com/dgrijalva/jwt-go/rsa.go new file mode 100644 index 000000000..e4caf1ca4 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa.go @@ -0,0 +1,101 @@ +package jwt + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" +) + +// Implements the RSA family of signing methods signing methods +// Expects *rsa.PrivateKey for signing and *rsa.PublicKey for validation +type SigningMethodRSA struct { + Name string + Hash crypto.Hash +} + +// Specific instances for RS256 and company +var ( + SigningMethodRS256 *SigningMethodRSA + SigningMethodRS384 *SigningMethodRSA + SigningMethodRS512 *SigningMethodRSA +) + +func init() { + // RS256 + SigningMethodRS256 = &SigningMethodRSA{"RS256", crypto.SHA256} + RegisterSigningMethod(SigningMethodRS256.Alg(), func() SigningMethod { + return SigningMethodRS256 + }) + + // RS384 + SigningMethodRS384 = &SigningMethodRSA{"RS384", crypto.SHA384} + RegisterSigningMethod(SigningMethodRS384.Alg(), func() SigningMethod { + return SigningMethodRS384 + }) + + // RS512 + SigningMethodRS512 = &SigningMethodRSA{"RS512", crypto.SHA512} + RegisterSigningMethod(SigningMethodRS512.Alg(), func() SigningMethod { + return SigningMethodRS512 + }) +} + +func (m *SigningMethodRSA) Alg() string { + return m.Name +} + +// Implements the Verify method from SigningMethod +// For this signing method, must be an *rsa.PublicKey structure. +func (m *SigningMethodRSA) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + var rsaKey *rsa.PublicKey + var ok bool + + if rsaKey, ok = key.(*rsa.PublicKey); !ok { + return ErrInvalidKeyType + } + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Verify the signature + return rsa.VerifyPKCS1v15(rsaKey, m.Hash, hasher.Sum(nil), sig) +} + +// Implements the Sign method from SigningMethod +// For this signing method, must be an *rsa.PrivateKey structure. +func (m *SigningMethodRSA) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey + var ok bool + + // Validate type of key + if rsaKey, ok = key.(*rsa.PrivateKey); !ok { + return "", ErrInvalidKey + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPKCS1v15(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil)); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go new file mode 100644 index 000000000..10ee9db8a --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa_pss.go @@ -0,0 +1,126 @@ +// +build go1.4 + +package jwt + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" +) + +// Implements the RSAPSS family of signing methods signing methods +type SigningMethodRSAPSS struct { + *SigningMethodRSA + Options *rsa.PSSOptions +} + +// Specific instances for RS/PS and company +var ( + SigningMethodPS256 *SigningMethodRSAPSS + SigningMethodPS384 *SigningMethodRSAPSS + SigningMethodPS512 *SigningMethodRSAPSS +) + +func init() { + // PS256 + SigningMethodPS256 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS256", + Hash: crypto.SHA256, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA256, + }, + } + RegisterSigningMethod(SigningMethodPS256.Alg(), func() SigningMethod { + return SigningMethodPS256 + }) + + // PS384 + SigningMethodPS384 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS384", + Hash: crypto.SHA384, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA384, + }, + } + RegisterSigningMethod(SigningMethodPS384.Alg(), func() SigningMethod { + return SigningMethodPS384 + }) + + // PS512 + SigningMethodPS512 = &SigningMethodRSAPSS{ + &SigningMethodRSA{ + Name: "PS512", + Hash: crypto.SHA512, + }, + &rsa.PSSOptions{ + SaltLength: rsa.PSSSaltLengthAuto, + Hash: crypto.SHA512, + }, + } + RegisterSigningMethod(SigningMethodPS512.Alg(), func() SigningMethod { + return SigningMethodPS512 + }) +} + +// Implements the Verify method from SigningMethod +// For this verify method, key must be an rsa.PublicKey struct +func (m *SigningMethodRSAPSS) Verify(signingString, signature string, key interface{}) error { + var err error + + // Decode the signature + var sig []byte + if sig, err = DecodeSegment(signature); err != nil { + return err + } + + var rsaKey *rsa.PublicKey + switch k := key.(type) { + case *rsa.PublicKey: + rsaKey = k + default: + return ErrInvalidKey + } + + // Create hasher + if !m.Hash.Available() { + return ErrHashUnavailable + } + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + return rsa.VerifyPSS(rsaKey, m.Hash, hasher.Sum(nil), sig, m.Options) +} + +// Implements the Sign method from SigningMethod +// For this signing method, key must be an rsa.PrivateKey struct +func (m *SigningMethodRSAPSS) Sign(signingString string, key interface{}) (string, error) { + var rsaKey *rsa.PrivateKey + + switch k := key.(type) { + case *rsa.PrivateKey: + rsaKey = k + default: + return "", ErrInvalidKeyType + } + + // Create the hasher + if !m.Hash.Available() { + return "", ErrHashUnavailable + } + + hasher := m.Hash.New() + hasher.Write([]byte(signingString)) + + // Sign the string and return the encoded bytes + if sigBytes, err := rsa.SignPSS(rand.Reader, rsaKey, m.Hash, hasher.Sum(nil), m.Options); err == nil { + return EncodeSegment(sigBytes), nil + } else { + return "", err + } +} diff --git a/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go new file mode 100644 index 000000000..a5ababf95 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/rsa_utils.go @@ -0,0 +1,101 @@ +package jwt + +import ( + "crypto/rsa" + "crypto/x509" + "encoding/pem" + "errors" +) + +var ( + ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key") + ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key") + ErrNotRSAPublicKey = errors.New("Key is not a valid RSA public key") +) + +// Parse PEM encoded PKCS1 or PKCS8 private key +func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + var parsedKey interface{} + if parsedKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(block.Bytes); err != nil { + return nil, err + } + } + + var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 private key protected with password +func ParseRSAPrivateKeyFromPEMWithPassword(key []byte, password string) (*rsa.PrivateKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + var parsedKey interface{} + + var blockDecrypted []byte + if blockDecrypted, err = x509.DecryptPEMBlock(block, []byte(password)); err != nil { + return nil, err + } + + if parsedKey, err = x509.ParsePKCS1PrivateKey(blockDecrypted); err != nil { + if parsedKey, err = x509.ParsePKCS8PrivateKey(blockDecrypted); err != nil { + return nil, err + } + } + + var pkey *rsa.PrivateKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok { + return nil, ErrNotRSAPrivateKey + } + + return pkey, nil +} + +// Parse PEM encoded PKCS1 or PKCS8 public key +func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) { + var err error + + // Parse PEM block + var block *pem.Block + if block, _ = pem.Decode(key); block == nil { + return nil, ErrKeyMustBePEMEncoded + } + + // Parse the key + var parsedKey interface{} + if parsedKey, err = x509.ParsePKIXPublicKey(block.Bytes); err != nil { + if cert, err := x509.ParseCertificate(block.Bytes); err == nil { + parsedKey = cert.PublicKey + } else { + return nil, err + } + } + + var pkey *rsa.PublicKey + var ok bool + if pkey, ok = parsedKey.(*rsa.PublicKey); !ok { + return nil, ErrNotRSAPublicKey + } + + return pkey, nil +} diff --git a/vendor/github.com/dgrijalva/jwt-go/signing_method.go b/vendor/github.com/dgrijalva/jwt-go/signing_method.go new file mode 100644 index 000000000..ed1f212b2 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/signing_method.go @@ -0,0 +1,35 @@ +package jwt + +import ( + "sync" +) + +var signingMethods = map[string]func() SigningMethod{} +var signingMethodLock = new(sync.RWMutex) + +// Implement SigningMethod to add new methods for signing or verifying tokens. +type SigningMethod interface { + Verify(signingString, signature string, key interface{}) error // Returns nil if signature is valid + Sign(signingString string, key interface{}) (string, error) // Returns encoded signature or error + Alg() string // returns the alg identifier for this method (example: 'HS256') +} + +// Register the "alg" name and a factory function for signing method. +// This is typically done during init() in the method's implementation +func RegisterSigningMethod(alg string, f func() SigningMethod) { + signingMethodLock.Lock() + defer signingMethodLock.Unlock() + + signingMethods[alg] = f +} + +// Get a signing method from an "alg" string +func GetSigningMethod(alg string) (method SigningMethod) { + signingMethodLock.RLock() + defer signingMethodLock.RUnlock() + + if methodF, ok := signingMethods[alg]; ok { + method = methodF() + } + return +} diff --git a/vendor/github.com/dgrijalva/jwt-go/token.go b/vendor/github.com/dgrijalva/jwt-go/token.go new file mode 100644 index 000000000..d637e0867 --- /dev/null +++ b/vendor/github.com/dgrijalva/jwt-go/token.go @@ -0,0 +1,108 @@ +package jwt + +import ( + "encoding/base64" + "encoding/json" + "strings" + "time" +) + +// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). +// You can override it to use another time value. This is useful for testing or if your +// server uses a different time zone than your tokens. +var TimeFunc = time.Now + +// Parse methods use this callback function to supply +// the key for verification. The function receives the parsed, +// but unverified Token. This allows you to use properties in the +// Header of the token (such as `kid`) to identify which key to use. +type Keyfunc func(*Token) (interface{}, error) + +// A JWT Token. Different fields will be used depending on whether you're +// creating or parsing/verifying a token. +type Token struct { + Raw string // The raw token. Populated when you Parse a token + Method SigningMethod // The signing method used or to be used + Header map[string]interface{} // The first segment of the token + Claims Claims // The second segment of the token + Signature string // The third segment of the token. Populated when you Parse a token + Valid bool // Is the token valid? Populated when you Parse/Verify a token +} + +// Create a new Token. Takes a signing method +func New(method SigningMethod) *Token { + return NewWithClaims(method, MapClaims{}) +} + +func NewWithClaims(method SigningMethod, claims Claims) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), + }, + Claims: claims, + Method: method, + } +} + +// Get the complete, signed token +func (t *Token) SignedString(key interface{}) (string, error) { + var sig, sstr string + var err error + if sstr, err = t.SigningString(); err != nil { + return "", err + } + if sig, err = t.Method.Sign(sstr, key); err != nil { + return "", err + } + return strings.Join([]string{sstr, sig}, "."), nil +} + +// Generate the signing string. This is the +// most expensive part of the whole deal. Unless you +// need this for something special, just go straight for +// the SignedString. +func (t *Token) SigningString() (string, error) { + var err error + parts := make([]string, 2) + for i, _ := range parts { + var jsonValue []byte + if i == 0 { + if jsonValue, err = json.Marshal(t.Header); err != nil { + return "", err + } + } else { + if jsonValue, err = json.Marshal(t.Claims); err != nil { + return "", err + } + } + + parts[i] = EncodeSegment(jsonValue) + } + return strings.Join(parts, "."), nil +} + +// Parse, validate, and return a token. +// keyFunc will receive the parsed token and should return the key for validating. +// If everything is kosher, err will be nil +func Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { + return new(Parser).Parse(tokenString, keyFunc) +} + +func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { + return new(Parser).ParseWithClaims(tokenString, claims, keyFunc) +} + +// Encode JWT specific base64url encoding with padding stripped +func EncodeSegment(seg []byte) string { + return strings.TrimRight(base64.URLEncoding.EncodeToString(seg), "=") +} + +// Decode JWT specific base64url encoding with padding stripped +func DecodeSegment(seg string) ([]byte, error) { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + + return base64.URLEncoding.DecodeString(seg) +} diff --git a/vendor/github.com/golang/mock/gomock/call.go b/vendor/github.com/golang/mock/gomock/call.go index a3fa1ae41..7345f6540 100644 --- a/vendor/github.com/golang/mock/gomock/call.go +++ b/vendor/github.com/golang/mock/gomock/call.go @@ -23,7 +23,7 @@ import ( // Call represents an expected call to a mock. type Call struct { - t TestReporter // for triggering test failures on invalid call setup + t TestHelper // for triggering test failures on invalid call setup receiver interface{} // the receiver of the method call method string // the name of the method @@ -46,10 +46,8 @@ type Call struct { // newCall creates a *Call. It requires the method type in order to support // unexported methods. -func newCall(t TestReporter, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { - if h, ok := t.(testHelper); ok { - h.Helper() - } +func newCall(t TestHelper, receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { + t.Helper() // TODO: check arity, types. margs := make([]Matcher, len(args)) @@ -84,8 +82,8 @@ func (c *Call) AnyTimes() *Call { return c } -// MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called, MinTimes also -// sets the maximum number of calls to infinity. +// MinTimes requires the call to occur at least n times. If AnyTimes or MaxTimes have not been called or if MaxTimes +// was previously called with 1, MinTimes also sets the maximum number of calls to infinity. func (c *Call) MinTimes(n int) *Call { c.minCalls = n if c.maxCalls == 1 { @@ -94,8 +92,8 @@ func (c *Call) MinTimes(n int) *Call { return c } -// MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called, MaxTimes also -// sets the minimum number of calls to 0. +// MaxTimes limits the number of calls to n times. If AnyTimes or MinTimes have not been called or if MinTimes was +// previously called with 1, MaxTimes also sets the minimum number of calls to 0. func (c *Call) MaxTimes(n int) *Call { c.maxCalls = n if c.minCalls == 1 { @@ -159,9 +157,7 @@ func (c *Call) Do(f interface{}) *Call { // Return declares the values to be returned by the mocked function call. func (c *Call) Return(rets ...interface{}) *Call { - if h, ok := c.t.(testHelper); ok { - h.Helper() - } + c.t.Helper() mt := c.methodType if len(rets) != mt.NumOut() { @@ -209,9 +205,7 @@ func (c *Call) Times(n int) *Call { // indirected through a pointer. Or, in the case of a slice, SetArg // will copy value's elements into the nth argument. func (c *Call) SetArg(n int, value interface{}) *Call { - if h, ok := c.t.(testHelper); ok { - h.Helper() - } + c.t.Helper() mt := c.methodType // TODO: This will break on variadic methods. @@ -264,9 +258,7 @@ func (c *Call) isPreReq(other *Call) bool { // After declares that the call may only match after preReq has been exhausted. func (c *Call) After(preReq *Call) *Call { - if h, ok := c.t.(testHelper); ok { - h.Helper() - } + c.t.Helper() if c == preReq { c.t.Fatalf("A call isn't allowed to be its own prerequisite") @@ -284,7 +276,7 @@ func (c *Call) satisfied() bool { return c.numCalls >= c.minCalls } -// Returns true iff the maximum number of calls have been made. +// Returns true if the maximum number of calls have been made. func (c *Call) exhausted() bool { return c.numCalls >= c.maxCalls } @@ -303,27 +295,34 @@ func (c *Call) String() string { func (c *Call) matches(args []interface{}) error { if !c.methodType.IsVariadic() { if len(args) != len(c.args) { - return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d", + return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d", c.origin, len(args), len(c.args)) } for i, m := range c.args { if !m.Matches(args[i]) { - return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", - c.origin, strconv.Itoa(i), args[i], m) + got := fmt.Sprintf("%v", args[i]) + if gs, ok := m.(GotFormatter); ok { + got = gs.Got(args[i]) + } + + return fmt.Errorf( + "expected call at %s doesn't match the argument at index %d.\nGot: %v\nWant: %v", + c.origin, i, got, m, + ) } } } else { if len(c.args) < c.methodType.NumIn()-1 { - return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d", + return fmt.Errorf("expected call at %s has the wrong number of matchers. Got: %d, want: %d", c.origin, len(c.args), c.methodType.NumIn()-1) } if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) { - return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d", + return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: %d", c.origin, len(args), len(c.args)) } if len(args) < len(c.args)-1 { - return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d", + return fmt.Errorf("expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d", c.origin, len(args), len(c.args)-1) } @@ -331,7 +330,7 @@ func (c *Call) matches(args []interface{}) error { if i < c.methodType.NumIn()-1 { // Non-variadic args if !m.Matches(args[i]) { - return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", + return fmt.Errorf("expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v", c.origin, strconv.Itoa(i), args[i], m) } continue @@ -390,7 +389,7 @@ func (c *Call) matches(args []interface{}) error { // Check that the call is not exhausted. if c.exhausted() { - return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin) + return fmt.Errorf("expected call at %s has already been called the max number of times", c.origin) } return nil @@ -404,7 +403,7 @@ func (c *Call) dropPrereqs() (preReqs []*Call) { return } -func (c *Call) call(args []interface{}) []func([]interface{}) []interface{} { +func (c *Call) call() []func([]interface{}) []interface{} { c.numCalls++ return c.actions } diff --git a/vendor/github.com/golang/mock/gomock/callset.go b/vendor/github.com/golang/mock/gomock/callset.go index c44a8a585..b046b525e 100644 --- a/vendor/github.com/golang/mock/gomock/callset.go +++ b/vendor/github.com/golang/mock/gomock/callset.go @@ -72,7 +72,7 @@ func (cs callSet) FindMatch(receiver interface{}, method string, args []interfac for _, call := range expected { err := call.matches(args) if err != nil { - fmt.Fprintf(&callsErrors, "\n%v", err) + _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) } else { return call, nil } @@ -83,12 +83,12 @@ func (cs callSet) FindMatch(receiver interface{}, method string, args []interfac exhausted := cs.exhausted[key] for _, call := range exhausted { if err := call.matches(args); err != nil { - fmt.Fprintf(&callsErrors, "\n%v", err) + _, _ = fmt.Fprintf(&callsErrors, "\n%v", err) } } if len(expected)+len(exhausted) == 0 { - fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method) + _, _ = fmt.Fprintf(&callsErrors, "there are no expected calls of the method %q for that receiver", method) } return nil, fmt.Errorf(callsErrors.String()) diff --git a/vendor/github.com/golang/mock/gomock/controller.go b/vendor/github.com/golang/mock/gomock/controller.go index a7b79188b..d7c3c656a 100644 --- a/vendor/github.com/golang/mock/gomock/controller.go +++ b/vendor/github.com/golang/mock/gomock/controller.go @@ -12,7 +12,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -// GoMock - a mock framework for Go. +// Package gomock is a mock framework for Go. // // Standard usage: // (1) Define an interface that you wish to mock. @@ -56,59 +56,111 @@ package gomock import ( + "context" "fmt" - "golang.org/x/net/context" "reflect" "runtime" "sync" ) -// A TestReporter is something that can be used to report test failures. -// It is satisfied by the standard library's *testing.T. +// A TestReporter is something that can be used to report test failures. It +// is satisfied by the standard library's *testing.T. type TestReporter interface { Errorf(format string, args ...interface{}) Fatalf(format string, args ...interface{}) } -// A Controller represents the top-level control of a mock ecosystem. -// It defines the scope and lifetime of mock objects, as well as their expectations. -// It is safe to call Controller's methods from multiple goroutines. +// TestHelper is a TestReporter that has the Helper method. It is satisfied +// by the standard library's *testing.T. +type TestHelper interface { + TestReporter + Helper() +} + +// A Controller represents the top-level control of a mock ecosystem. It +// defines the scope and lifetime of mock objects, as well as their +// expectations. It is safe to call Controller's methods from multiple +// goroutines. Each test should create a new Controller and invoke Finish via +// defer. +// +// func TestFoo(t *testing.T) { +// ctrl := gomock.NewController(t) +// defer ctrl.Finish() +// // .. +// } +// +// func TestBar(t *testing.T) { +// t.Run("Sub-Test-1", st) { +// ctrl := gomock.NewController(st) +// defer ctrl.Finish() +// // .. +// }) +// t.Run("Sub-Test-2", st) { +// ctrl := gomock.NewController(st) +// defer ctrl.Finish() +// // .. +// }) +// }) type Controller struct { + // T should only be called within a generated mock. It is not intended to + // be used in user code and may be changed in future versions. T is the + // TestReporter passed in when creating the Controller via NewController. + // If the TestReporter does not implement a TestHelper it will be wrapped + // with a nopTestHelper. + T TestHelper mu sync.Mutex - t TestReporter expectedCalls *callSet finished bool } +// NewController returns a new Controller. It is the preferred way to create a +// Controller. func NewController(t TestReporter) *Controller { + h, ok := t.(TestHelper) + if !ok { + h = nopTestHelper{t} + } + return &Controller{ - t: t, + T: h, expectedCalls: newCallSet(), } } type cancelReporter struct { - t TestReporter + TestHelper cancel func() } -func (r *cancelReporter) Errorf(format string, args ...interface{}) { r.t.Errorf(format, args...) } +func (r *cancelReporter) Errorf(format string, args ...interface{}) { + r.TestHelper.Errorf(format, args...) +} func (r *cancelReporter) Fatalf(format string, args ...interface{}) { defer r.cancel() - r.t.Fatalf(format, args...) + r.TestHelper.Fatalf(format, args...) } // WithContext returns a new Controller and a Context, which is cancelled on any // fatal failure. func WithContext(ctx context.Context, t TestReporter) (*Controller, context.Context) { + h, ok := t.(TestHelper) + if !ok { + h = nopTestHelper{t} + } + ctx, cancel := context.WithCancel(ctx) - return NewController(&cancelReporter{t, cancel}), ctx + return NewController(&cancelReporter{h, cancel}), ctx } +type nopTestHelper struct { + TestReporter +} + +func (h nopTestHelper) Helper() {} + +// RecordCall is called by a mock. It should not be called by user code. func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ...interface{}) *Call { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } + ctrl.T.Helper() recv := reflect.ValueOf(receiver) for i := 0; i < recv.Type().NumMethod(); i++ { @@ -116,16 +168,15 @@ func (ctrl *Controller) RecordCall(receiver interface{}, method string, args ... return ctrl.RecordCallWithMethodType(receiver, method, recv.Method(i).Type(), args...) } } - ctrl.t.Fatalf("gomock: failed finding method %s on %T", method, receiver) + ctrl.T.Fatalf("gomock: failed finding method %s on %T", method, receiver) panic("unreachable") } +// RecordCallWithMethodType is called by a mock. It should not be called by user code. func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method string, methodType reflect.Type, args ...interface{}) *Call { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } + ctrl.T.Helper() - call := newCall(ctrl.t, receiver, method, methodType, args...) + call := newCall(ctrl.T, receiver, method, methodType, args...) ctrl.mu.Lock() defer ctrl.mu.Unlock() @@ -134,20 +185,20 @@ func (ctrl *Controller) RecordCallWithMethodType(receiver interface{}, method st return call } +// Call is called by a mock. It should not be called by user code. func (ctrl *Controller) Call(receiver interface{}, method string, args ...interface{}) []interface{} { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } + ctrl.T.Helper() // Nest this code so we can use defer to make sure the lock is released. actions := func() []func([]interface{}) []interface{} { + ctrl.T.Helper() ctrl.mu.Lock() defer ctrl.mu.Unlock() expected, err := ctrl.expectedCalls.FindMatch(receiver, method, args) if err != nil { origin := callerInfo(2) - ctrl.t.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err) + ctrl.T.Fatalf("Unexpected call to %T.%v(%v) at %s because: %s", receiver, method, args, origin, err) } // Two things happen here: @@ -158,7 +209,7 @@ func (ctrl *Controller) Call(receiver interface{}, method string, args ...interf ctrl.expectedCalls.Remove(preReqCall) } - actions := expected.call(args) + actions := expected.call() if expected.exhausted() { ctrl.expectedCalls.Remove(expected) } @@ -175,16 +226,17 @@ func (ctrl *Controller) Call(receiver interface{}, method string, args ...interf return rets } +// Finish checks to see if all the methods that were expected to be called +// were called. It should be invoked for each Controller. It is not idempotent +// and therefore can only be invoked once. func (ctrl *Controller) Finish() { - if h, ok := ctrl.t.(testHelper); ok { - h.Helper() - } + ctrl.T.Helper() ctrl.mu.Lock() defer ctrl.mu.Unlock() if ctrl.finished { - ctrl.t.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.") + ctrl.T.Fatalf("Controller.Finish was called more than once. It has to be called exactly once.") } ctrl.finished = true @@ -197,10 +249,10 @@ func (ctrl *Controller) Finish() { // Check that all remaining expected calls are satisfied. failures := ctrl.expectedCalls.Failures() for _, call := range failures { - ctrl.t.Errorf("missing call(s) to %v", call) + ctrl.T.Errorf("missing call(s) to %v", call) } if len(failures) != 0 { - ctrl.t.Fatalf("aborting test due to missing call(s)") + ctrl.T.Fatalf("aborting test due to missing call(s)") } } @@ -210,8 +262,3 @@ func callerInfo(skip int) string { } return "unknown file" } - -type testHelper interface { - TestReporter - Helper() -} diff --git a/vendor/github.com/golang/mock/gomock/matchers.go b/vendor/github.com/golang/mock/gomock/matchers.go index e8b1ddccf..7bfc07be4 100644 --- a/vendor/github.com/golang/mock/gomock/matchers.go +++ b/vendor/github.com/golang/mock/gomock/matchers.go @@ -1,5 +1,3 @@ -//go:generate mockgen -destination mock_matcher/mock_matcher.go github.com/golang/mock/gomock Matcher - // Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); @@ -19,6 +17,7 @@ package gomock import ( "fmt" "reflect" + "strings" ) // A Matcher is a representation of a class of values. @@ -31,9 +30,66 @@ type Matcher interface { String() string } +// WantFormatter modifies the given Matcher's String() method to the given +// Stringer. This allows for control on how the "Want" is formatted when +// printing . +func WantFormatter(s fmt.Stringer, m Matcher) Matcher { + type matcher interface { + Matches(x interface{}) bool + } + + return struct { + matcher + fmt.Stringer + }{ + matcher: m, + Stringer: s, + } +} + +// StringerFunc type is an adapter to allow the use of ordinary functions as +// a Stringer. If f is a function with the appropriate signature, +// StringerFunc(f) is a Stringer that calls f. +type StringerFunc func() string + +// String implements fmt.Stringer. +func (f StringerFunc) String() string { + return f() +} + +// GotFormatter is used to better print failure messages. If a matcher +// implements GotFormatter, it will use the result from Got when printing +// the failure message. +type GotFormatter interface { + // Got is invoked with the received value. The result is used when + // printing the failure message. + Got(got interface{}) string +} + +// GotFormatterFunc type is an adapter to allow the use of ordinary +// functions as a GotFormatter. If f is a function with the appropriate +// signature, GotFormatterFunc(f) is a GotFormatter that calls f. +type GotFormatterFunc func(got interface{}) string + +// Got implements GotFormatter. +func (f GotFormatterFunc) Got(got interface{}) string { + return f(got) +} + +// GotFormatterAdapter attaches a GotFormatter to a Matcher. +func GotFormatterAdapter(s GotFormatter, m Matcher) Matcher { + return struct { + GotFormatter + Matcher + }{ + GotFormatter: s, + Matcher: m, + } +} + type anyMatcher struct{} -func (anyMatcher) Matches(x interface{}) bool { +func (anyMatcher) Matches(interface{}) bool { return true } @@ -87,13 +143,113 @@ func (n notMatcher) String() string { return "not(" + n.m.String() + ")" } +type assignableToTypeOfMatcher struct { + targetType reflect.Type +} + +func (m assignableToTypeOfMatcher) Matches(x interface{}) bool { + return reflect.TypeOf(x).AssignableTo(m.targetType) +} + +func (m assignableToTypeOfMatcher) String() string { + return "is assignable to " + m.targetType.Name() +} + +type allMatcher struct { + matchers []Matcher +} + +func (am allMatcher) Matches(x interface{}) bool { + for _, m := range am.matchers { + if !m.Matches(x) { + return false + } + } + return true +} + +func (am allMatcher) String() string { + ss := make([]string, 0, len(am.matchers)) + for _, matcher := range am.matchers { + ss = append(ss, matcher.String()) + } + return strings.Join(ss, "; ") +} + +type lenMatcher struct { + i int +} + +func (m lenMatcher) Matches(x interface{}) bool { + v := reflect.ValueOf(x) + switch v.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice, reflect.String: + return v.Len() == m.i + default: + return false + } +} + +func (m lenMatcher) String() string { + return fmt.Sprintf("has length %d", m.i) +} + // Constructors -func Any() Matcher { return anyMatcher{} } + +// All returns a composite Matcher that returns true if and only all of the +// matchers return true. +func All(ms ...Matcher) Matcher { return allMatcher{ms} } + +// Any returns a matcher that always matches. +func Any() Matcher { return anyMatcher{} } + +// Eq returns a matcher that matches on equality. +// +// Example usage: +// Eq(5).Matches(5) // returns true +// Eq(5).Matches(4) // returns false func Eq(x interface{}) Matcher { return eqMatcher{x} } -func Nil() Matcher { return nilMatcher{} } + +// Len returns a matcher that matches on length. This matcher returns false if +// is compared to a type that is not an array, chan, map, slice, or string. +func Len(i int) Matcher { + return lenMatcher{i} +} + +// Nil returns a matcher that matches if the received value is nil. +// +// Example usage: +// var x *bytes.Buffer +// Nil().Matches(x) // returns true +// x = &bytes.Buffer{} +// Nil().Matches(x) // returns false +func Nil() Matcher { return nilMatcher{} } + +// Not reverses the results of its given child matcher. +// +// Example usage: +// Not(Eq(5)).Matches(4) // returns true +// Not(Eq(5)).Matches(5) // returns false func Not(x interface{}) Matcher { if m, ok := x.(Matcher); ok { return notMatcher{m} } return notMatcher{Eq(x)} } + +// AssignableToTypeOf is a Matcher that matches if the parameter to the mock +// function is assignable to the type of the parameter to this function. +// +// Example usage: +// var s fmt.Stringer = &bytes.Buffer{} +// AssignableToTypeOf(s).Matches(time.Second) // returns true +// AssignableToTypeOf(s).Matches(99) // returns false +// +// var ctx = reflect.TypeOf((*context.Context)).Elem() +// AssignableToTypeOf(ctx).Matches(context.Background()) // returns true +func AssignableToTypeOf(x interface{}) Matcher { + if xt, ok := x.(reflect.Type); ok { + return assignableToTypeOfMatcher{xt} + } + return assignableToTypeOfMatcher{reflect.TypeOf(x)} +} From 6ac6ed29c95ba7590146ad6f1cc115ec5944632c Mon Sep 17 00:00:00 2001 From: Soulou Date: Fri, 27 Mar 2020 21:18:33 +0100 Subject: [PATCH 2/2] Display region name in migration example commands Fixes #539 --- region_migrations/run.go | 2 +- region_migrations/status.go | 12 ++++++------ 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/region_migrations/run.go b/region_migrations/run.go index 3398ac487..0b1ee1d6b 100644 --- a/region_migrations/run.go +++ b/region_migrations/run.go @@ -55,7 +55,7 @@ func Run(app, migrationID string, step scalingo.RegionMigrationStep) error { if !shouldContinue { fmt.Println("The current step has been canceled. You can restart it later.") fmt.Println("If you want to abort the migration, run:") - fmt.Printf("scalingo --app %s migration-abort %s\n", app, migrationID) + fmt.Printf("scalingo --region %s --app %s migration-abort %s\n", migration.Source, app, migrationID) return nil } expectedStatuses := []scalingo.RegionMigrationStatus{} diff --git a/region_migrations/status.go b/region_migrations/status.go index 73dd847fc..c4ae0d019 100644 --- a/region_migrations/status.go +++ b/region_migrations/status.go @@ -94,7 +94,7 @@ func showMigrationStatusFailed(appId string, migration scalingo.RegionMigration, if opts.CurrentStep != scalingo.RegionMigrationStepAbort { fmt.Println("To rollback your application to a working state, run:") - fmt.Printf("scalingo --app %s migration-abort %s\n\n", appId, migration.ID) + fmt.Printf("scalingo --region %s --app %s migration-abort %s\n\n", migration.Source, appId, migration.ID) } fmt.Println("You can contact support@scalingo.com to troubleshoot this issue.") @@ -103,27 +103,27 @@ func showMigrationStatusFailed(appId string, migration scalingo.RegionMigration, func showMigrationStatusPreflightSuccess(appId string, migration scalingo.RegionMigration) { fmt.Printf("Your app can be migrated to the %s zone.\n", migration.Destination) fmt.Printf("To start the migration launch:\n\n") - fmt.Printf("scalingo --app %s migration-run --prepare %s\n", appId, migration.ID) + fmt.Printf("scalingo --region %s --app %s migration-run --prepare %s\n", migration.Source, appId, migration.ID) } func showMigrationStatusPrepared(appId string, migration scalingo.RegionMigration) { fmt.Printf("Application on region '%s' has been prepared, you can now:\n", migration.Destination) fmt.Printf("- Let us migrate your data to '%s' newly created databases with:\n", migration.Destination) - fmt.Printf("scalingo --app %s migration-run --data %s\n", appId, migration.ID) + fmt.Printf("scalingo --region %s --app %s migration-run --data %s\n", migration.Source, appId, migration.ID) fmt.Printf("- Handle data migration manually, then finalizing the migration with:\n") - fmt.Printf("scalingo --app %s migration-run --finalize %s\n", appId, migration.ID) + fmt.Printf("scalingo --region %s --app %s migration-run --finalize %s\n", migration.Source, appId, migration.ID) } func showMigrationStatusDataMigrated(appId string, migration scalingo.RegionMigration) { fmt.Printf("Data has been migrated to the '%s' region\n", migration.Destination) fmt.Printf("You can finalize the migration with:\n") - fmt.Printf("scalingo --app %s migration-run --finalize %s\n", appId, migration.ID) + fmt.Printf("scalingo --region %s --app %s migration-run --finalize %s\n", migration.Source, appId, migration.ID) } func showMigrationStatusAborted(appId string, migration scalingo.RegionMigration) { fmt.Printf("The migration '%s' has been aborted\n", migration.ID) fmt.Printf("You can retry it with:\n") - fmt.Printf("scalingo --app %s migration-create --to %s", appId, migration.Destination) + fmt.Printf("scalingo --region %s --app %s migration-create --to %s", migration.Source, appId, migration.Destination) if migration.DstAppName != migration.SrcAppName { fmt.Printf(" --new-name %s \n", migration.DstAppName) } else {