From eee4b55e0f254e1fea19e34d18c0bd48a574bc8f Mon Sep 17 00:00:00 2001 From: Kamal Nasser Date: Wed, 15 Jan 2020 13:09:34 +0200 Subject: [PATCH] DigitalOcean Auth Provider (#351) * DigitalOcean provider * documentation: digitalocean provider * changelog: digitalocean provider * codeowners: digitalocean provider --- .github/CODEOWNERS | 4 + CHANGELOG.md | 1 + contrib/oauth2_proxy_autocomplete.sh | 2 +- docs/2_auth.md | 18 ++++ providers/digitalocean.go | 81 ++++++++++++++++ providers/digitalocean_test.go | 134 +++++++++++++++++++++++++++ providers/providers.go | 2 + 7 files changed, 241 insertions(+), 1 deletion(-) create mode 100644 providers/digitalocean.go create mode 100644 providers/digitalocean_test.go diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 71a79063..fa1f8104 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -18,3 +18,7 @@ providers/bitbucket_test.go @aledeganopix4d # Nextcloud provider providers/nextcloud.go @Ramblurr providers/nextcloud_test.go @Ramblurr + +# DigitalOcean provider +providers/digitalocean.go @kamaln7 +providers/digitalocean_test.go @kamaln7 diff --git a/CHANGELOG.md b/CHANGELOG.md index 783335dd..14d60f09 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ - [#347](https://github.com/pusher/oauth2_proxy/pull/347) Update keycloak provider configuration documentation - [#325](https://github.com/pusher/oauth2_proxy/pull/325) dist.sh: use sha256sum (@syscll) - [#179](https://github.com/pusher/oauth2_proxy/pull/179) Add Nextcloud provider (@Ramblurr) +- [#351](https://github.com/pusher/oauth2_proxy/pull/351) Add DigitalOcean Auth provider (@kamaln7) # v4.1.0 diff --git a/contrib/oauth2_proxy_autocomplete.sh b/contrib/oauth2_proxy_autocomplete.sh index fd9d87a4..219a0ec5 100644 --- a/contrib/oauth2_proxy_autocomplete.sh +++ b/contrib/oauth2_proxy_autocomplete.sh @@ -17,7 +17,7 @@ _oauth2_proxy() { return 0 ;; -provider) - COMPREPLY=( $(compgen -W "google azure facebook github keycloak gitlab linkedin login.gov" -- ${cur}) ) + COMPREPLY=( $(compgen -W "google azure facebook github keycloak gitlab linkedin login.gov digitalocean" -- ${cur}) ) return 0 ;; -@(http-address|https-address|redirect-url|upstream|basic-auth-password|skip-auth-regex|flush-interval|extra-jwt-issuers|email-domain|whitelist-domain|keycloak-group|azure-tenant|bitbucket-team|bitbucket-repository|github-org|github-team|gitlab-group|google-group|google-admin-email|google-service-account-json|client-id|client_secret|banner|footer|proxy-prefix|ping-path|cookie-name|cookie-secret|cookie-domain|cookie-path|cookie-expire|cookie-refresh|redist-sentinel-master-name|redist-sentinel-connection-urls|logging-max-size|logging-max-age|logging-max-backups|standard-logging-format|request-logging-format|exclude-logging-paths|auth-logging-format|oidc-issuer-url|oidc-jwks-url|login-url|redeem-url|profile-url|resource|validate-url|scope|approval-prompt|signature-key|acr-values|jwt-key|pubjwk-url)) diff --git a/docs/2_auth.md b/docs/2_auth.md index e1440075..d715c6cc 100644 --- a/docs/2_auth.md +++ b/docs/2_auth.md @@ -20,6 +20,7 @@ Valid providers are : - [LinkedIn](#linkedin-auth-provider) - [login.gov](#logingov-provider) - [Nextcloud](#nextcloud-provider) +- [DigitalOcean](#digitalocean-auth-provider) The provider can be selected using the `provider` configuration value. @@ -320,6 +321,23 @@ to setup the client id and client secret. Your "Redirection URI" will be Note: in *all* cases the validate-url will *not* have the `index.php`. +### DigitalOcean Auth Provider + +1. [Create a new OAuth application](https://cloud.digitalocean.com/account/api/applications) + * You can fill in the name, homepage, and description however you wish. + * In the "Application callback URL" field, enter: `https://oauth-proxy/oauth2/callback`, substituting `oauth2-proxy` with the actual hostname that oauth2_proxy is running on. The URL must match oauth2_proxy's configured redirect URL. +2. Note the Client ID and Client Secret. + +To use the provider, pass the following options: + +``` + --provider=digitalocean + --client-id= + --client-secret= +``` + + Alternatively, set the equivalent options in the config file. The redirect URL defaults to `https:///oauth2/callback`. If you need to change it, you can use the `--redirect-url` command-line option. + ## Email Authentication To authorize by email domain use `--email-domain=yourcompany.com`. To authorize individual email addresses use `--authenticated-emails-file=/path/to/file` with one email per line. To authorize all email addresses use `--email-domain=*`. diff --git a/providers/digitalocean.go b/providers/digitalocean.go new file mode 100644 index 00000000..f4d9ce57 --- /dev/null +++ b/providers/digitalocean.go @@ -0,0 +1,81 @@ +package providers + +import ( + "errors" + "fmt" + "net/http" + "net/url" + + "github.com/pusher/oauth2_proxy/pkg/apis/sessions" + "github.com/pusher/oauth2_proxy/pkg/requests" +) + +// DigitalOceanProvider represents a DigitalOcean based Identity Provider +type DigitalOceanProvider struct { + *ProviderData +} + +// NewDigitalOceanProvider initiates a new DigitalOceanProvider +func NewDigitalOceanProvider(p *ProviderData) *DigitalOceanProvider { + p.ProviderName = "DigitalOcean" + if p.LoginURL.String() == "" { + p.LoginURL = &url.URL{Scheme: "https", + Host: "cloud.digitalocean.com", + Path: "/v1/oauth/authorize", + } + } + if p.RedeemURL.String() == "" { + p.RedeemURL = &url.URL{Scheme: "https", + Host: "cloud.digitalocean.com", + Path: "/v1/oauth/token", + } + } + if p.ProfileURL.String() == "" { + p.ProfileURL = &url.URL{Scheme: "https", + Host: "api.digitalocean.com", + Path: "/v2/account", + } + } + if p.ValidateURL.String() == "" { + p.ValidateURL = p.ProfileURL + } + if p.Scope == "" { + p.Scope = "read" + } + return &DigitalOceanProvider{ProviderData: p} +} + +func getDigitalOceanHeader(accessToken string) http.Header { + header := make(http.Header) + header.Set("Content-Type", "application/json") + header.Set("Authorization", fmt.Sprintf("Bearer %s", accessToken)) + return header +} + +// GetEmailAddress returns the Account email address +func (p *DigitalOceanProvider) GetEmailAddress(s *sessions.SessionState) (string, error) { + if s.AccessToken == "" { + return "", errors.New("missing access token") + } + req, err := http.NewRequest("GET", p.ProfileURL.String(), nil) + if err != nil { + return "", err + } + req.Header = getDigitalOceanHeader(s.AccessToken) + + json, err := requests.Request(req) + if err != nil { + return "", err + } + + email, err := json.GetPath("account", "email").String() + if err != nil { + return "", err + } + return email, nil +} + +// ValidateSessionState validates the AccessToken +func (p *DigitalOceanProvider) ValidateSessionState(s *sessions.SessionState) bool { + return validateToken(p, s.AccessToken, getDigitalOceanHeader(s.AccessToken)) +} diff --git a/providers/digitalocean_test.go b/providers/digitalocean_test.go new file mode 100644 index 00000000..08b52957 --- /dev/null +++ b/providers/digitalocean_test.go @@ -0,0 +1,134 @@ +package providers + +import ( + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "github.com/pusher/oauth2_proxy/pkg/apis/sessions" + "github.com/stretchr/testify/assert" +) + +func testDigitalOceanProvider(hostname string) *DigitalOceanProvider { + p := NewDigitalOceanProvider( + &ProviderData{ + ProviderName: "", + LoginURL: &url.URL{}, + RedeemURL: &url.URL{}, + ProfileURL: &url.URL{}, + ValidateURL: &url.URL{}, + Scope: ""}) + if hostname != "" { + updateURL(p.Data().LoginURL, hostname) + updateURL(p.Data().RedeemURL, hostname) + updateURL(p.Data().ProfileURL, hostname) + } + return p +} + +func testDigitalOceanBackend(payload string) *httptest.Server { + path := "/v2/account" + + return httptest.NewServer(http.HandlerFunc( + func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != path { + w.WriteHeader(404) + } else if r.Header.Get("Authorization") != "Bearer imaginary_access_token" { + w.WriteHeader(403) + } else { + w.WriteHeader(200) + w.Write([]byte(payload)) + } + })) +} + +func TestDigitalOceanProviderDefaults(t *testing.T) { + p := testDigitalOceanProvider("") + assert.NotEqual(t, nil, p) + assert.Equal(t, "DigitalOcean", p.Data().ProviderName) + assert.Equal(t, "https://cloud.digitalocean.com/v1/oauth/authorize", + p.Data().LoginURL.String()) + assert.Equal(t, "https://cloud.digitalocean.com/v1/oauth/token", + p.Data().RedeemURL.String()) + assert.Equal(t, "https://api.digitalocean.com/v2/account", + p.Data().ProfileURL.String()) + assert.Equal(t, "https://api.digitalocean.com/v2/account", + p.Data().ValidateURL.String()) + assert.Equal(t, "read", p.Data().Scope) +} + +func TestDigitalOceanProviderOverrides(t *testing.T) { + p := NewDigitalOceanProvider( + &ProviderData{ + LoginURL: &url.URL{ + Scheme: "https", + Host: "example.com", + Path: "/oauth/auth"}, + RedeemURL: &url.URL{ + Scheme: "https", + Host: "example.com", + Path: "/oauth/token"}, + ProfileURL: &url.URL{ + Scheme: "https", + Host: "example.com", + Path: "/oauth/profile"}, + ValidateURL: &url.URL{ + Scheme: "https", + Host: "example.com", + Path: "/oauth/tokeninfo"}, + Scope: "profile"}) + assert.NotEqual(t, nil, p) + assert.Equal(t, "DigitalOcean", p.Data().ProviderName) + assert.Equal(t, "https://example.com/oauth/auth", + p.Data().LoginURL.String()) + assert.Equal(t, "https://example.com/oauth/token", + p.Data().RedeemURL.String()) + assert.Equal(t, "https://example.com/oauth/profile", + p.Data().ProfileURL.String()) + assert.Equal(t, "https://example.com/oauth/tokeninfo", + p.Data().ValidateURL.String()) + assert.Equal(t, "profile", p.Data().Scope) +} + +func TestDigitalOceanProviderGetEmailAddress(t *testing.T) { + b := testDigitalOceanBackend(`{"account": {"email": "user@example.com"}}`) + defer b.Close() + + bURL, _ := url.Parse(b.URL) + p := testDigitalOceanProvider(bURL.Host) + + session := &sessions.SessionState{AccessToken: "imaginary_access_token"} + email, err := p.GetEmailAddress(session) + assert.Equal(t, nil, err) + assert.Equal(t, "user@example.com", email) +} + +func TestDigitalOceanProviderGetEmailAddressFailedRequest(t *testing.T) { + b := testDigitalOceanBackend("unused payload") + defer b.Close() + + bURL, _ := url.Parse(b.URL) + p := testDigitalOceanProvider(bURL.Host) + + // We'll trigger a request failure by using an unexpected access + // token. Alternatively, we could allow the parsing of the payload as + // JSON to fail. + session := &sessions.SessionState{AccessToken: "unexpected_access_token"} + email, err := p.GetEmailAddress(session) + assert.NotEqual(t, nil, err) + assert.Equal(t, "", email) +} + +func TestDigitalOceanProviderGetEmailAddressEmailNotPresentInPayload(t *testing.T) { + b := testDigitalOceanBackend("{\"foo\": \"bar\"}") + defer b.Close() + + bURL, _ := url.Parse(b.URL) + p := testDigitalOceanProvider(bURL.Host) + + session := &sessions.SessionState{AccessToken: "imaginary_access_token"} + email, err := p.GetEmailAddress(session) + assert.NotEqual(t, nil, err) + assert.Equal(t, "", email) +} diff --git a/providers/providers.go b/providers/providers.go index 0e264105..fb8cccad 100644 --- a/providers/providers.go +++ b/providers/providers.go @@ -42,6 +42,8 @@ func New(provider string, p *ProviderData) Provider { return NewBitbucketProvider(p) case "nextcloud": return NewNextcloudProvider(p) + case "digitalocean": + return NewDigitalOceanProvider(p) default: return NewGoogleProvider(p) }