Files

247 lines
7.2 KiB
Go
Raw Permalink Normal View History

2021-07-24 11:16:34 +01:00
// Copyright 2021 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
2017-02-22 08:14:37 +01:00
package oauth2
import (
"context"
"errors"
"fmt"
"html"
"html/template"
"net/url"
2025-08-23 16:39:05 -04:00
"slices"
2021-07-24 11:16:34 +01:00
"sort"
2017-03-03 16:21:31 +08:00
2022-01-02 21:12:35 +08:00
"code.gitea.io/gitea/models/auth"
"code.gitea.io/gitea/models/db"
2017-02-22 08:14:37 +01:00
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/optional"
2017-03-03 16:21:31 +08:00
"code.gitea.io/gitea/modules/setting"
2017-02-22 08:14:37 +01:00
"github.com/markbates/goth"
"github.com/markbates/goth/providers/openidConnect"
2017-02-22 08:14:37 +01:00
)
2021-08-06 02:11:08 +01:00
// Provider is an interface for describing a single OAuth2 provider
type Provider interface {
Name() string
DisplayName() string
IconHTML(size int) template.HTML
2021-08-06 02:11:08 +01:00
CustomURLSettings() *CustomURLSettings
SupportSSHPublicKey() bool
2021-08-06 02:11:08 +01:00
}
// GothProviderCreator provides a function to create a goth.Provider
type GothProviderCreator interface {
CreateGothProvider(providerName, callbackURL string, source *Source) (goth.Provider, error)
}
// GothProvider is an interface for describing a single OAuth2 provider
type GothProvider interface {
Provider
GothProviderCreator
}
// AuthSourceProvider provides a provider for an AuthSource. Multiple auth sources could use the same registered GothProvider
// So each auth source should have its own DisplayName and IconHTML for display.
// The Name is the GothProvider's name, to help to find the GothProvider to sign in.
// The DisplayName is the auth source config's name, site admin set it on the admin page, the IconURL can also be set there.
type AuthSourceProvider struct {
2021-08-06 02:11:08 +01:00
GothProvider
sourceName, iconURL string
2021-08-06 02:11:08 +01:00
}
func (p *AuthSourceProvider) Name() string {
return p.GothProvider.Name()
2021-08-06 02:11:08 +01:00
}
func (p *AuthSourceProvider) DisplayName() string {
return p.sourceName
}
func (p *AuthSourceProvider) IconHTML(size int) template.HTML {
if p.iconURL != "" {
img := fmt.Sprintf(`<img class="tw-object-contain" width="%d" height="%d" src="%s" alt="%s">`,
size,
size,
html.EscapeString(p.iconURL), html.EscapeString(p.DisplayName()),
)
return template.HTML(img)
2021-08-06 02:11:08 +01:00
}
return p.GothProvider.IconHTML(size)
2021-07-24 11:16:34 +01:00
}
2017-02-22 08:14:37 +01:00
2021-07-24 11:16:34 +01:00
// Providers contains the map of registered OAuth2 providers in Gitea (based on goth)
2022-01-02 21:12:35 +08:00
// key is used to map the OAuth2Provider with the goth provider type (also in AuthSource.OAuth2Config.Provider)
2021-07-24 11:16:34 +01:00
// value is used to store display data
2021-08-06 02:11:08 +01:00
var gothProviders = map[string]GothProvider{}
2025-08-23 16:39:05 -04:00
func isAzureProvider(name string) bool {
return name == "azuread" || name == "microsoftonline" || name == "azureadv2"
}
2021-08-06 02:11:08 +01:00
// RegisterGothProvider registers a GothProvider
func RegisterGothProvider(provider GothProvider) {
if _, has := gothProviders[provider.Name()]; has {
log.Fatal("Duplicate oauth2provider type provided: %s", provider.Name())
}
gothProviders[provider.Name()] = provider
}
2025-08-23 16:39:05 -04:00
// getExistingAzureADAuthSources returns a list of Azure AD provider names that are already configured
func getExistingAzureADAuthSources(ctx context.Context) ([]string, error) {
authSources, err := db.Find[auth.Source](ctx, auth.FindSourcesOptions{
LoginType: auth.OAuth2,
})
if err != nil {
return nil, err
}
var existingAzureProviders []string
for _, source := range authSources {
if oauth2Cfg, ok := source.Cfg.(*Source); ok {
if isAzureProvider(oauth2Cfg.Provider) {
existingAzureProviders = append(existingAzureProviders, oauth2Cfg.Provider)
}
}
}
return existingAzureProviders, nil
}
2025-08-27 19:00:01 +08:00
// GetSupportedOAuth2Providers returns the list of supported OAuth2 providers with context for filtering
2021-08-06 02:11:08 +01:00
// key is used as technical name (like in the callbackURL)
// values to display
2025-08-23 16:39:05 -04:00
// Note: Azure AD providers (azuread, microsoftonline, azureadv2) are filtered out
// unless they already exist in the system to encourage use of OpenID Connect
2025-08-27 19:00:01 +08:00
func GetSupportedOAuth2Providers(ctx context.Context) []Provider {
2021-08-06 02:11:08 +01:00
providers := make([]Provider, 0, len(gothProviders))
2025-08-23 16:39:05 -04:00
existingAzureSources, err := getExistingAzureADAuthSources(ctx)
if err != nil {
log.Error("Failed to get existing OAuth2 auth sources: %v", err)
}
2021-08-06 02:11:08 +01:00
for _, provider := range gothProviders {
2025-08-23 16:39:05 -04:00
if isAzureProvider(provider.Name()) && !slices.Contains(existingAzureSources, provider.Name()) {
continue
}
2021-08-06 02:11:08 +01:00
providers = append(providers, provider)
}
sort.Slice(providers, func(i, j int) bool {
return providers[i].Name() < providers[j].Name()
})
return providers
2017-05-01 15:26:53 +02:00
}
func CreateProviderFromSource(source *auth.Source) (Provider, error) {
oauth2Cfg, ok := source.Cfg.(*Source)
if !ok {
return nil, fmt.Errorf("invalid OAuth2 source config: %v", oauth2Cfg)
}
gothProv := gothProviders[oauth2Cfg.Provider]
return &AuthSourceProvider{GothProvider: gothProv, sourceName: source.Name, iconURL: oauth2Cfg.IconURL}, nil
}
2017-02-22 08:14:37 +01:00
// GetOAuth2Providers returns the list of configured OAuth2 providers
func GetOAuth2Providers(ctx context.Context, isActive optional.Option[bool]) ([]Provider, error) {
authSources, err := db.Find[auth.Source](ctx, auth.FindSourcesOptions{
IsActive: isActive,
LoginType: auth.OAuth2,
})
if err != nil {
return nil, err
2017-02-22 08:14:37 +01:00
}
providers := make([]Provider, 0, len(authSources))
2022-01-02 21:12:35 +08:00
for _, source := range authSources {
provider, err := CreateProviderFromSource(source)
if err != nil {
return nil, err
2021-07-24 11:16:34 +01:00
}
providers = append(providers, provider)
2017-02-22 08:14:37 +01:00
}
sort.Slice(providers, func(i, j int) bool {
return providers[i].Name() < providers[j].Name()
})
2017-02-22 08:14:37 +01:00
return providers, nil
2017-02-22 08:14:37 +01:00
}
2021-08-06 02:11:08 +01:00
// RegisterProviderWithGothic register a OAuth2 provider in goth lib
func RegisterProviderWithGothic(providerName string, source *Source) error {
provider, err := createProvider(providerName, source)
2017-02-22 08:14:37 +01:00
2017-05-01 15:26:53 +02:00
if err == nil && provider != nil {
gothRWMutex.Lock()
defer gothRWMutex.Unlock()
2017-02-22 08:14:37 +01:00
goth.UseProviders(provider)
}
2017-05-01 15:26:53 +02:00
return err
2017-02-22 08:14:37 +01:00
}
2021-08-06 02:11:08 +01:00
// RemoveProviderFromGothic removes the given OAuth2 provider from the goth lib
func RemoveProviderFromGothic(providerName string) {
gothRWMutex.Lock()
defer gothRWMutex.Unlock()
2017-02-22 08:14:37 +01:00
delete(goth.GetProviders(), providerName)
}
// ClearProviders clears all OAuth2 providers from the goth lib
func ClearProviders() {
gothRWMutex.Lock()
defer gothRWMutex.Unlock()
goth.ClearProviders()
}
// GetOIDCEndSessionEndpoint returns the OIDC end_session_endpoint for the
// given provider name. Returns "" if the provider is not OIDC or doesn't
// advertise an end_session_endpoint in its discovery document.
func GetOIDCEndSessionEndpoint(providerName string) string {
gothRWMutex.RLock()
defer gothRWMutex.RUnlock()
provider, ok := goth.GetProviders()[providerName]
if !ok {
return ""
}
oidcProvider, ok := provider.(*openidConnect.Provider)
if !ok || oidcProvider.OpenIDConfig == nil {
return ""
}
return oidcProvider.OpenIDConfig.EndSessionEndpoint
}
var ErrAuthSourceNotActivated = errors.New("auth source is not activated")
2017-02-22 08:14:37 +01:00
// used to create different types of goth providers
2021-08-06 02:11:08 +01:00
func createProvider(providerName string, source *Source) (goth.Provider, error) {
callbackURL := setting.AppURL + "user/oauth2/" + url.PathEscape(providerName) + "/callback"
2017-02-22 08:14:37 +01:00
var provider goth.Provider
2017-05-01 15:26:53 +02:00
var err error
2017-02-22 08:14:37 +01:00
2021-08-06 02:11:08 +01:00
p, ok := gothProviders[source.Provider]
if !ok {
return nil, ErrAuthSourceNotActivated
2021-08-06 02:11:08 +01:00
}
provider, err = p.CreateGothProvider(providerName, callbackURL, source)
if err != nil {
return provider, err
2017-02-22 08:14:37 +01:00
}
// always set the name if provider is created so we can support multiple setups of 1 provider
2024-04-30 14:34:40 +02:00
if provider != nil {
2017-02-22 08:14:37 +01:00
provider.SetName(providerName)
}
2017-05-01 15:26:53 +02:00
return provider, err
}