diff --git a/api/cmd/portainer/main.go b/api/cmd/portainer/main.go index 10d83c51e..f759285da 100644 --- a/api/cmd/portainer/main.go +++ b/api/cmd/portainer/main.go @@ -260,6 +260,7 @@ func initSettings(settingsService portainer.SettingsService, flags *portainer.CL portainer.LDAPGroupSearchSettings{}, }, }, + OAuthSettings: portainer.OAuthSettings{}, AllowBindMountsForRegularUsers: true, AllowPrivilegedModeForRegularUsers: true, EnableHostManagementFeatures: false, diff --git a/api/exec/extension.go b/api/exec/extension.go index cb58ecad6..ab7880a1b 100644 --- a/api/exec/extension.go +++ b/api/exec/extension.go @@ -18,7 +18,8 @@ import ( var extensionDownloadBaseURL = "https://portainer-io-assets.sfo2.digitaloceanspaces.com/extensions/" var extensionBinaryMap = map[portainer.ExtensionID]string{ - portainer.RegistryManagementExtension: "extension-registry-management", + portainer.RegistryManagementExtension: "extension-registry-management", + portainer.OAuthAuthenticationExtension: "extension-oauth-authentication", } // ExtensionManager represents a service used to diff --git a/api/http/handler/auth/authenticate_oauth.go b/api/http/handler/auth/authenticate_oauth.go new file mode 100644 index 000000000..d8559e999 --- /dev/null +++ b/api/http/handler/auth/authenticate_oauth.go @@ -0,0 +1,138 @@ +package auth + +import ( + "encoding/json" + "io/ioutil" + "net/http" + "log" + + "github.com/asaskevich/govalidator" + httperror "github.com/portainer/libhttp/error" + "github.com/portainer/libhttp/request" + "github.com/portainer/portainer" +) + +type oauthPayload struct { + Code string +} + +func (payload *oauthPayload) Validate(r *http.Request) error { + if govalidator.IsNull(payload.Code) { + return portainer.Error("Invalid OAuth authorization code") + } + return nil +} + +func (handler *Handler) authenticateThroughExtension(code, licenseKey string, settings *portainer.OAuthSettings) (string, error) { + extensionURL := handler.ProxyManager.GetExtensionURL(portainer.OAuthAuthenticationExtension) + + encodedConfiguration, err := json.Marshal(settings) + if err != nil { + return "", nil + } + + req, err := http.NewRequest("GET", extensionURL+"/validate", nil) + if err != nil { + return "", err + } + + client := &http.Client{} + req.Header.Set("X-OAuth-Config", string(encodedConfiguration)) + req.Header.Set("X-OAuth-Code", code) + req.Header.Set("X-PortainerExtension-License", licenseKey) + + resp, err := client.Do(req) + if err != nil { + return "", err + } + + defer resp.Body.Close() + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return "", err + } + + type extensionResponse struct { + Username string `json:"Username,omitempty"` + Err string `json:"err,omitempty"` + Details string `json:"details,omitempty"` + } + + var extResp extensionResponse + err = json.Unmarshal(body, &extResp) + if err != nil { + return "", err + } + + if resp.StatusCode != http.StatusOK { + return "", portainer.Error(extResp.Err + ":" + extResp.Details) + } + + return extResp.Username, nil +} + +func (handler *Handler) validateOAuth(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { + var payload oauthPayload + err := request.DecodeAndValidateJSONPayload(r, &payload) + if err != nil { + return &httperror.HandlerError{http.StatusBadRequest, "Invalid request payload", err} + } + + settings, err := handler.SettingsService.Settings() + if err != nil { + return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve settings from the database", err} + } + + if settings.AuthenticationMethod != 3 { + return &httperror.HandlerError{http.StatusForbidden, "OAuth authentication is not enabled", portainer.Error("OAuth authentication is not enabled")} + } + + extension, err := handler.ExtensionService.Extension(portainer.OAuthAuthenticationExtension) + if err == portainer.ErrObjectNotFound { + return &httperror.HandlerError{http.StatusNotFound, "Oauth authentication extension is not enabled", err} + } else if err != nil { + return &httperror.HandlerError{http.StatusInternalServerError, "Unable to find a extension with the specified identifier inside the database", err} + } + + username, err := handler.authenticateThroughExtension(payload.Code, extension.License.LicenseKey, &settings.OAuthSettings) + if err != nil { + log.Printf("[DEBUG] - OAuth authentication error: %s", err) + return &httperror.HandlerError{http.StatusInternalServerError, "Unable to authenticate through OAuth", portainer.ErrUnauthorized} + } + + user, err := handler.UserService.UserByUsername(username) + if err != nil && err != portainer.ErrObjectNotFound { + return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve a user with the specified username from the database", err} + } + + if user == nil && !settings.OAuthSettings.OAuthAutoCreateUsers { + return &httperror.HandlerError{http.StatusForbidden, "Account not created beforehand in Portainer and automatic user provisioning not enabled", portainer.ErrUnauthorized} + } + + if user == nil { + user = &portainer.User{ + Username: username, + Role: portainer.StandardUserRole, + } + + err = handler.UserService.CreateUser(user) + if err != nil { + return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist user inside the database", err} + } + + if settings.OAuthSettings.DefaultTeamID != 0 { + membership := &portainer.TeamMembership{ + UserID: user.ID, + TeamID: settings.OAuthSettings.DefaultTeamID, + Role: portainer.TeamMember, + } + + err = handler.TeamMembershipService.CreateTeamMembership(membership) + if err != nil { + return &httperror.HandlerError{http.StatusInternalServerError, "Unable to persist team membership inside the database", err} + } + } + } + + return handler.writeToken(w, user) +} diff --git a/api/http/handler/auth/handler.go b/api/http/handler/auth/handler.go index 1f0769e08..75e343f23 100644 --- a/api/http/handler/auth/handler.go +++ b/api/http/handler/auth/handler.go @@ -6,6 +6,7 @@ import ( "github.com/gorilla/mux" httperror "github.com/portainer/libhttp/error" "github.com/portainer/portainer" + "github.com/portainer/portainer/http/proxy" "github.com/portainer/portainer/http/security" ) @@ -28,6 +29,8 @@ type Handler struct { SettingsService portainer.SettingsService TeamService portainer.TeamService TeamMembershipService portainer.TeamMembershipService + ExtensionService portainer.ExtensionService + ProxyManager *proxy.Manager } // NewHandler creates a handler to manage authentication operations. @@ -36,6 +39,9 @@ func NewHandler(bouncer *security.RequestBouncer, rateLimiter *security.RateLimi Router: mux.NewRouter(), authDisabled: authDisabled, } + + h.Handle("/auth/oauth/validate", + rateLimiter.LimitAccess(bouncer.PublicAccess(httperror.LoggerHandler(h.validateOAuth)))).Methods(http.MethodPost) h.Handle("/auth", rateLimiter.LimitAccess(bouncer.PublicAccess(httperror.LoggerHandler(h.authenticate)))).Methods(http.MethodPost) diff --git a/api/http/handler/settings/handler.go b/api/http/handler/settings/handler.go index 0acbd2ca6..a9033c701 100644 --- a/api/http/handler/settings/handler.go +++ b/api/http/handler/settings/handler.go @@ -11,6 +11,7 @@ import ( func hideFields(settings *portainer.Settings) { settings.LDAPSettings.Password = "" + settings.OAuthSettings.ClientSecret = "" } // Handler is the HTTP handler used to handle settings operations. diff --git a/api/http/handler/settings/settings_public.go b/api/http/handler/settings/settings_public.go index 9744b319a..cc1e07854 100644 --- a/api/http/handler/settings/settings_public.go +++ b/api/http/handler/settings/settings_public.go @@ -1,6 +1,7 @@ package settings import ( + "fmt" "net/http" httperror "github.com/portainer/libhttp/error" @@ -15,6 +16,7 @@ type publicSettingsResponse struct { AllowPrivilegedModeForRegularUsers bool `json:"AllowPrivilegedModeForRegularUsers"` EnableHostManagementFeatures bool `json:"EnableHostManagementFeatures"` ExternalTemplates bool `json:"ExternalTemplates"` + OAuthLoginURI string `json:"OAuthLoginURI"` } // GET request on /api/settings/public @@ -31,6 +33,11 @@ func (handler *Handler) settingsPublic(w http.ResponseWriter, r *http.Request) * AllowPrivilegedModeForRegularUsers: settings.AllowPrivilegedModeForRegularUsers, EnableHostManagementFeatures: settings.EnableHostManagementFeatures, ExternalTemplates: false, + OAuthLoginURI: fmt.Sprintf("%s?response_type=code&client_id=%s&redirect_uri=%s&scope=%s&prompt=login", + settings.OAuthSettings.AuthorizationURI, + settings.OAuthSettings.ClientID, + settings.OAuthSettings.RedirectURI, + settings.OAuthSettings.Scopes), } if settings.TemplatesURL != "" { diff --git a/api/http/handler/settings/settings_update.go b/api/http/handler/settings/settings_update.go index 5c68fca94..21b9daa99 100644 --- a/api/http/handler/settings/settings_update.go +++ b/api/http/handler/settings/settings_update.go @@ -16,6 +16,7 @@ type settingsUpdatePayload struct { BlackListedLabels []portainer.Pair AuthenticationMethod *int LDAPSettings *portainer.LDAPSettings + OAuthSettings *portainer.OAuthSettings AllowBindMountsForRegularUsers *bool AllowPrivilegedModeForRegularUsers *bool EnableHostManagementFeatures *bool @@ -24,8 +25,8 @@ type settingsUpdatePayload struct { } func (payload *settingsUpdatePayload) Validate(r *http.Request) error { - if *payload.AuthenticationMethod != 1 && *payload.AuthenticationMethod != 2 { - return portainer.Error("Invalid authentication method value. Value must be one of: 1 (internal) or 2 (LDAP/AD)") + if *payload.AuthenticationMethod != 1 && *payload.AuthenticationMethod != 2 && *payload.AuthenticationMethod != 3 { + return portainer.Error("Invalid authentication method value. Value must be one of: 1 (internal), 2 (LDAP/AD) or 3 (OAuth)") } if payload.LogoURL != nil && *payload.LogoURL != "" && !govalidator.IsURL(*payload.LogoURL) { return portainer.Error("Invalid logo URL. Must correspond to a valid URL format") @@ -74,6 +75,15 @@ func (handler *Handler) settingsUpdate(w http.ResponseWriter, r *http.Request) * settings.LDAPSettings.Password = ldapPassword } + if payload.OAuthSettings != nil { + clientSecret := payload.OAuthSettings.ClientSecret + if clientSecret == "" { + clientSecret = settings.OAuthSettings.ClientSecret + } + settings.OAuthSettings = *payload.OAuthSettings + settings.OAuthSettings.ClientSecret = clientSecret + } + if payload.AllowBindMountsForRegularUsers != nil { settings.AllowBindMountsForRegularUsers = *payload.AllowBindMountsForRegularUsers } diff --git a/api/http/handler/users/user_delete.go b/api/http/handler/users/user_delete.go index 1c500bfc1..78f83fe57 100644 --- a/api/http/handler/users/user_delete.go +++ b/api/http/handler/users/user_delete.go @@ -41,6 +41,10 @@ func (handler *Handler) userDelete(w http.ResponseWriter, r *http.Request) *http } func (handler *Handler) deleteAdminUser(w http.ResponseWriter, user *portainer.User) *httperror.HandlerError { + if user.Password == "" { + return handler.deleteUser(w, user) + } + users, err := handler.UserService.Users() if err != nil { return &httperror.HandlerError{http.StatusInternalServerError, "Unable to retrieve users from the database", err} diff --git a/api/http/proxy/manager.go b/api/http/proxy/manager.go index b1e2aa6f4..f7cbbd5dd 100644 --- a/api/http/proxy/manager.go +++ b/api/http/proxy/manager.go @@ -12,7 +12,8 @@ import ( // TODO: contain code related to legacy extension management var extensionPorts = map[portainer.ExtensionID]string{ - portainer.RegistryManagementExtension: "7001", + portainer.RegistryManagementExtension: "7001", + portainer.OAuthAuthenticationExtension: "7002", } type ( @@ -103,6 +104,10 @@ func (manager *Manager) CreateExtensionProxy(extensionID portainer.ExtensionID) return proxy, nil } +func (manager *Manager) GetExtensionURL(extensionID portainer.ExtensionID) string { + return "http://localhost:" + extensionPorts[extensionID] +} + // DeleteExtensionProxy deletes the extension proxy associated to an extension identifier func (manager *Manager) DeleteExtensionProxy(extensionID portainer.ExtensionID) { manager.extensionProxies.Remove(strconv.Itoa(int(extensionID))) diff --git a/api/http/server.go b/api/http/server.go index 1220d94d1..7f3368f25 100644 --- a/api/http/server.go +++ b/api/http/server.go @@ -107,6 +107,8 @@ func (server *Server) Start() error { authHandler.SettingsService = server.SettingsService authHandler.TeamService = server.TeamService authHandler.TeamMembershipService = server.TeamMembershipService + authHandler.ExtensionService = server.ExtensionService + authHandler.ProxyManager = proxyManager var dockerHubHandler = dockerhub.NewHandler(requestBouncer) dockerHubHandler.DockerHubService = server.DockerHubService diff --git a/api/portainer.go b/api/portainer.go index 9ff82bb37..cba90a55e 100644 --- a/api/portainer.go +++ b/api/portainer.go @@ -56,6 +56,20 @@ type ( AutoCreateUsers bool `json:"AutoCreateUsers"` } + // OAuthSettings represents the settings used to authorize with an authorization server + OAuthSettings struct { + ClientID string `json:"ClientID"` + ClientSecret string `json:"ClientSecret,omitempty"` + AccessTokenURI string `json:"AccessTokenURI"` + AuthorizationURI string `json:"AuthorizationURI"` + ResourceURI string `json:"ResourceURI"` + RedirectURI string `json:"RedirectURI"` + UserIdentifier string `json:"UserIdentifier"` + Scopes string `json:"Scopes"` + OAuthAutoCreateUsers bool `json:"OAuthAutoCreateUsers"` + DefaultTeamID TeamID `json:"DefaultTeamID"` + } + // TLSConfiguration represents a TLS configuration TLSConfiguration struct { TLS bool `json:"TLS"` @@ -85,6 +99,7 @@ type ( BlackListedLabels []Pair `json:"BlackListedLabels"` AuthenticationMethod AuthenticationMethod `json:"AuthenticationMethod"` LDAPSettings LDAPSettings `json:"LDAPSettings"` + OAuthSettings OAuthSettings `json:"OAuthSettings"` AllowBindMountsForRegularUsers bool `json:"AllowBindMountsForRegularUsers"` AllowPrivilegedModeForRegularUsers bool `json:"AllowPrivilegedModeForRegularUsers"` SnapshotInterval string `json:"SnapshotInterval"` @@ -834,6 +849,8 @@ const ( AuthenticationInternal // AuthenticationLDAP represents the LDAP authentication method (authentication against a LDAP server) AuthenticationLDAP + //AuthenticationOAuth represents the OAuth authentication method (authentication against a authorization server) + AuthenticationOAuth ) const ( @@ -912,6 +929,8 @@ const ( _ ExtensionID = iota // RegistryManagementExtension represents the registry management extension RegistryManagementExtension + // OAuthAuthenticationExtension represents the OAuth authentication extension + OAuthAuthenticationExtension ) const ( diff --git a/app/extensions/_module.js b/app/extensions/_module.js index 5a936d2cf..7ad877aa6 100644 --- a/app/extensions/_module.js +++ b/app/extensions/_module.js @@ -1,3 +1,4 @@ angular.module('portainer.extensions', [ - 'portainer.extensions.registrymanagement' + 'portainer.extensions.registrymanagement', + 'portainer.extensions.oauth' ]); diff --git a/app/extensions/oauth/__module.js b/app/extensions/oauth/__module.js new file mode 100644 index 000000000..8292353a5 --- /dev/null +++ b/app/extensions/oauth/__module.js @@ -0,0 +1,2 @@ +angular.module('portainer.extensions.oauth', ['ngResource']) + .constant('API_ENDPOINT_OAUTH', 'api/auth/oauth'); diff --git a/app/extensions/oauth/components/oauth-providers-selector/oauth-provider-selector-controller.js b/app/extensions/oauth/components/oauth-providers-selector/oauth-provider-selector-controller.js new file mode 100644 index 000000000..818fef20a --- /dev/null +++ b/app/extensions/oauth/components/oauth-providers-selector/oauth-provider-selector-controller.js @@ -0,0 +1,63 @@ +angular.module('portainer.extensions.oauth') + .controller('OAuthProviderSelectorController', function OAuthProviderSelectorController() { + var ctrl = this; + + this.providers = [ + { + authUrl: 'https://login.microsoftonline.com/TENANT_ID/oauth2/authorize', + accessTokenUrl: 'https://login.microsoftonline.com/TENANT_ID/oauth2/token', + resourceUrl: 'https://graph.windows.net/TENANT_ID/me?api-version=2013-11-08', + userIdentifier: 'userPrincipalName', + scopes: 'id,email,name', + name: 'microsoft' + }, + { + authUrl: 'https://accounts.google.com/o/oauth2/auth', + accessTokenUrl: 'https://accounts.google.com/o/oauth2/token', + resourceUrl: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json', + userIdentifier: 'email', + scopes: 'profile email', + name: 'google' + }, + { + authUrl: 'https://github.com/login/oauth/authorize', + accessTokenUrl: 'https://github.com/login/oauth/access_token', + resourceUrl: 'https://api.github.com/user', + userIdentifier: 'login', + scopes: 'id email name', + name: 'github' + }, + { + authUrl: '', + accessTokenUrl: '', + resourceUrl: '', + userIdentifier: '', + scopes: '', + name: 'custom' + } + ]; + + this.$onInit = onInit; + + function onInit() { + if (ctrl.provider.authUrl) { + ctrl.provider = getProviderByURL(ctrl.provider.authUrl); + } else { + ctrl.provider = ctrl.providers[0]; + } + ctrl.onSelect(ctrl.provider, false); + } + + function getProviderByURL(providerAuthURL) { + if (providerAuthURL.indexOf('login.microsoftonline.com') !== -1) { + return ctrl.providers[0]; + } + else if (providerAuthURL.indexOf('accounts.google.com') !== -1) { + return ctrl.providers[1]; + } + else if (providerAuthURL.indexOf('github.com') !== -1) { + return ctrl.providers[2]; + } + return ctrl.providers[3]; + } + }); diff --git a/app/extensions/oauth/components/oauth-providers-selector/oauth-providers-selector.html b/app/extensions/oauth/components/oauth-providers-selector/oauth-providers-selector.html new file mode 100644 index 000000000..56023908e --- /dev/null +++ b/app/extensions/oauth/components/oauth-providers-selector/oauth-providers-selector.html @@ -0,0 +1,49 @@ +
The users created by the automatic provisioning feature can be added to a default team on creation.
+By assigning newly created users to a team they will be able to access the environments associated to that team. This setting is optional and if not set newly created users won't be able to access any environments.
+ +LDAP authentication
+