Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

14.6 KB
Raw Blame
package oauth

import (
	"context"
	"encoding/base64"

	"fmt"
	"net/url"
	"strings"
	"time"

	"github.com/getfider/fider/app"
	"github.com/getfider/fider/app/models/cmd"
	"github.com/getfider/fider/app/models/dto"
	"github.com/getfider/fider/app/models/entity"
	"github.com/getfider/fider/app/models/enum"
	"github.com/getfider/fider/app/models/query"
	"github.com/getfider/fider/app/pkg/bus"
	"github.com/getfider/fider/app/pkg/env"
	"github.com/getfider/fider/app/pkg/errors"
	"github.com/getfider/fider/app/pkg/jsonq"
	"github.com/getfider/fider/app/pkg/jwt"
	"github.com/getfider/fider/app/pkg/netguard"
	"github.com/getfider/fider/app/pkg/validate"
	"github.com/getfider/fider/app/pkg/web"
	"golang.org/x/oauth2"
	"golang.org/x/oauth2/facebook"
	"golang.org/x/oauth2/github"
)

func init() {
	bus.Register(Service{})
}

type Service struct{}

func (s Service) Name() string {
	return "HTTP"
}

func (s Service) Category() string {
	return "OAuth"
}

func (s Service) Enabled() bool {
	return true
}

func (s Service) Init() {
	bus.AddHandler(parseOAuthRawProfile)
	bus.AddHandler(getOAuthAuthorizationURL)
	bus.AddHandler(getOAuthProfile)
	bus.AddHandler(getOAuthRawProfile)
	bus.AddHandler(listActiveOAuthProviders)
	bus.AddHandler(listAllOAuthProviders)
}

func getProviderStatus(key string) int {
	if key == "" {
		return enum.OAuthConfigDisabled
	}
	return enum.OAuthConfigEnabled
}

var (
	systemProviders = []*entity.OAuthConfig{
		{
			Provider:          app.FacebookProvider,
			DisplayName:       "Facebook",
			ProfileURL:        "https://graph.facebook.com/me?fields=name,email",
			Status:            getProviderStatus(env.Config.OAuth.Facebook.AppID),
			IsTrusted:         false,
			ClientID:          env.Config.OAuth.Facebook.AppID,
			ClientSecret:      env.Config.OAuth.Facebook.Secret,
			Scope:             "public_profile email",
			AuthorizeURL:      facebook.Endpoint.AuthURL,
			TokenURL:          facebook.Endpoint.TokenURL,
			JSONUserIDPath:    "id",
			JSONUserNamePath:  "name",
			JSONUserEmailPath: "email",
		},
		{
			Provider:          app.GoogleProvider,
			DisplayName:       "Google",
			ProfileURL:        "https://www.googleapis.com/oauth2/v2/userinfo",
			Status:            getProviderStatus(env.Config.OAuth.Google.ClientID),
			IsTrusted:         false,
			ClientID:          env.Config.OAuth.Google.ClientID,
			ClientSecret:      env.Config.OAuth.Google.Secret,
			Scope:             "profile email",
			AuthorizeURL:      "https://accounts.google.com/o/oauth2/v2/auth",
			TokenURL:          "https://www.googleapis.com/oauth2/v4/token",
			JSONUserIDPath:    "id",
			JSONUserNamePath:  "name",
			JSONUserEmailPath: "email",
		},
		{
			Provider:          app.GitHubProvider,
			DisplayName:       "GitHub",
			ProfileURL:        "https://api.github.com/user",
			Status:            getProviderStatus(env.Config.OAuth.GitHub.ClientID),
			IsTrusted:         false,
			ClientID:          env.Config.OAuth.GitHub.ClientID,
			ClientSecret:      env.Config.OAuth.GitHub.Secret,
			Scope:             "user:email",
			AuthorizeURL:      github.Endpoint.AuthURL,
			TokenURL:          github.Endpoint.TokenURL,
			JSONUserIDPath:    "id",
			JSONUserNamePath:  "name, login",
			JSONUserEmailPath: "email",
		},
	}
)

func parseOAuthRawProfile(ctx context.Context, c *cmd.ParseOAuthRawProfile) error {
	config, err := getConfig(ctx, c.Provider)
	if err != nil {
		return err
	}

	query := jsonq.New(c.Body)

	// Extract and combine name parts
	name := extractCompositeName(query, config.JSONUserNamePath)

	// Extract roles if path is configured
	var roles []string
	if config.JSONUserRolesPath != "" {
		roles = extractRolesFromJSON(c.Body, config.JSONUserRolesPath)
	}

	profile := &dto.OAuthUserProfile{
		ID:    strings.TrimSpace(query.String(config.JSONUserIDPath)),
		Name:  name,
		Email: strings.ToLower(strings.TrimSpace(query.String(config.JSONUserEmailPath))),
		Roles: roles,
	}

	if profile.ID == "" {
		return app.ErrUserIDRequired
	}

	if profile.Name == "" && profile.Email != "" {
		parts := strings.Split(profile.Email, "@")
		profile.Name = parts[0]
	}

	if profile.Name == "" {
		profile.Name = "Anonymous"
	}

	if len(validate.Email(ctx, profile.Email)) != 0 {
		profile.Email = ""
	}

	c.Result = profile
	return nil
}

// extractCompositeName handles composite name selectors
// Format can be:
// - Simple path: "name"
// - Fallback paths: "name, login" (tries name, if empty tries login)
// - Composite paths: "firstname + ' ' + lastname" (combines multiple fields)
func extractCompositeName(query *jsonq.Query, namePath string) string {
	// Check if it's a composite path (contains '+')
	if strings.Contains(namePath, "+") {
		// Split by '+' and process each part
		parts := strings.Split(namePath, "+")
		var result strings.Builder

		for _, part := range parts {
			part = strings.TrimSpace(part)

			// If it's a string literal (enclosed in quotes or single quotes)
			if (strings.HasPrefix(part, "'") && strings.HasSuffix(part, "'")) ||
				(strings.HasPrefix(part, "\"") && strings.HasSuffix(part, "\"")) {
				// Extract the literal without quotes
				literal := part[1 : len(part)-1]
				result.WriteString(literal)
			} else {
				// It's a JSON path
				value := strings.TrimSpace(query.String(part))
				if value != "" {
					result.WriteString(value)
				}
			}
		}

		return strings.TrimSpace(result.String())
	}

	// Handle fallback paths (comma-separated)
	paths := strings.Split(namePath, ",")
	for _, path := range paths {
		path = strings.TrimSpace(path)
		value := strings.TrimSpace(query.String(path))
		if value != "" {
			return value
		}
	}

	return ""
}

// extractRolesFromJSON extracts role strings from a JSON body at the given path.
// Supports formats:
// - "roles" for array of strings: ["ROLE_ADMIN", "ROLE_USER"]
// - "roles[].id" for array of objects: [{"id": "ROLE_ADMIN"}, {"id": "ROLE_USER"}]
// - "user.roles[].name" for nested array of objects
// - "role" for a single string or comma-separated value
func extractRolesFromJSON(jsonBody string, rolesPath string) []string {
	rolesPath = strings.TrimSpace(rolesPath)
	if rolesPath == "" {
		return nil
	}

	q := jsonq.New(jsonBody)

	// "roles[].id" — array of objects, extract field from each
	if strings.Contains(rolesPath, "[].") {
		parts := strings.SplitN(rolesPath, "[].", 2)
		return trimNonEmpty(q.ArrayFieldStrings(parts[0], parts[1]))
	}

	// "roles" — array of strings or single (possibly comma-separated) string
	values := q.Strings(rolesPath)
	if len(values) == 0 {
		return nil
	}

	// Single string may contain comma-separated roles
	if len(values) == 1 && strings.Contains(values[0], ",") {
		values = strings.Split(values[0], ",")
	}

	return trimNonEmpty(values)
}

// trimNonEmpty trims whitespace from each string and returns only non-empty values.
func trimNonEmpty(ss []string) []string {
	if ss == nil {
		return nil
	}
	result := make([]string, 0, len(ss))
	for _, s := range ss {
		if s = strings.TrimSpace(s); s != "" {
			result = append(result, s)
		}
	}
	if len(result) == 0 {
		return nil
	}
	return result
}

func getOAuthAuthorizationURL(ctx context.Context, q *query.GetOAuthAuthorizationURL) error {
	config, err := getConfig(ctx, q.Provider)
	if err != nil {
		return err
	}

	oauthBaseURL := web.OAuthBaseURL(ctx)
	authURL, _ := url.Parse(config.AuthorizeURL)
	parameters := getProviderInitialParams(authURL)
	parameters.Add("client_id", config.ClientID)
	parameters.Add("scope", config.Scope)
	parameters.Add("redirect_uri", fmt.Sprintf("%s/oauth/%s/callback", oauthBaseURL, q.Provider))
	parameters.Add("response_type", "code")

	state, err := jwt.Encode(jwt.OAuthStateClaims{
		Redirect:   q.Redirect,
		Identifier: q.Identifier,
		Code:       q.Code,
		Metadata: jwt.Metadata{
			ExpiresAt: jwt.Time(time.Now().Add(10 * time.Minute)),
		},
	})

	if err != nil {
		return err
	}

	parameters.Add("state", state)

	authURL.RawQuery = parameters.Encode()
	q.Result = authURL.String()
	return nil
}

func getOAuthProfile(ctx context.Context, q *query.GetOAuthProfile) error {
	config, err := getConfig(ctx, q.Provider)
	if err != nil {
		return err
	}

	if config.Status == enum.OAuthConfigDisabled {
		return errors.New("Provider %s is disabled", q.Provider)
	}

	rawProfile := &query.GetOAuthRawProfile{Provider: q.Provider, Code: q.Code}
	err = bus.Dispatch(ctx, rawProfile)
	if err != nil {
		return err
	}

	parseRawProfile := &cmd.ParseOAuthRawProfile{Provider: q.Provider, Body: rawProfile.Result}
	err = bus.Dispatch(ctx, parseRawProfile)
	if err != nil {
		return err
	}

	q.Result = parseRawProfile.Result
	return nil
}

func getOAuthRawProfile(ctx context.Context, q *query.GetOAuthRawProfile) error {
	config, err := getConfig(ctx, q.Provider)
	if err != nil {
		return err
	}

	// Guard against SSRF: TokenURL triggers a server-side request during the token exchange.
	if msgs := validate.WebhookURL(config.TokenURL); len(msgs) > 0 {
		return errors.New("Token URL is not allowed: %s", strings.Join(msgs, "; "))
	}

	oauthBaseURL := web.OAuthBaseURL(ctx)
	exchange := (&oauth2.Config{
		ClientID:     config.ClientID,
		ClientSecret: config.ClientSecret,
		Endpoint: oauth2.Endpoint{
			AuthURL:  config.AuthorizeURL,
			TokenURL: config.TokenURL,
		},
		RedirectURL: fmt.Sprintf("%s/oauth/%s/callback", oauthBaseURL, q.Provider),
	}).Exchange

	guard := requiresSSRFGuard(q.Provider, config)
	oauthToken, err := exchange(tokenExchangeContext(ctx, guard), q.Code)
	if err != nil {
		return err
	}

	if config.ProfileURL == "" {
		parts := strings.Split(oauthToken.AccessToken, ".")
		if len(parts) != 3 {
			return errors.New("AccessToken is not JWT")
		}

		body, _ := base64.RawURLEncoding.DecodeString(parts[1])
		q.Result = string(body)
		return nil
	}

	// Guard against SSRF: ProfileURL is user-configurable and fetched server-side.
	if msgs := validate.WebhookURL(config.ProfileURL); len(msgs) > 0 {
		return errors.New("Profile URL is not allowed: %s", strings.Join(msgs, "; "))
	}

	req := newProfileRequest(guard, config.ProfileURL, oauthToken.AccessToken)

	if err := bus.Dispatch(ctx, req); err != nil {
		return err
	}

	if req.ResponseStatusCode != 200 {
		return errors.New("Failed to request profile. Status Code: %d. Body: %s", req.ResponseStatusCode, string(req.ResponseBody))
	}

	q.Result = string(req.ResponseBody)
	return nil
}

func listActiveOAuthProviders(ctx context.Context, q *query.ListActiveOAuthProviders) error {
	allOAuthProviders := &query.ListAllOAuthProviders{}
	err := bus.Dispatch(ctx, allOAuthProviders)
	if err != nil {
		return err
	}

	list := make([]*dto.OAuthProviderOption, 0)
	for _, p := range allOAuthProviders.Result {
		if p.IsEnabled {
			list = append(list, p)
		}
	}
	q.Result = list
	return nil
}

func listAllOAuthProviders(ctx context.Context, q *query.ListAllOAuthProviders) error {
	oauthProviders := &query.ListCustomOAuthConfig{}
	err := bus.Dispatch(ctx, oauthProviders)
	if err != nil {
		return errors.Wrap(err, "failed to get list of custom OAuth providers")
	}

	oauthProviders.Result = append(oauthProviders.Result, systemProviders...)

	list := make([]*dto.OAuthProviderOption, 0)

	oauthBaseURL := web.OAuthBaseURL(ctx)
	for _, p := range oauthProviders.Result {
		isCustomProvider := isCustomOAuthProvider(p.Provider)
		isEnabled := p.Status == enum.OAuthConfigEnabled

		// For built-in (non-custom) providers, check tenant-level override
		if !isCustomProvider && isEnabled {
			tenantStatus := &query.GetTenantProviderStatus{Provider: p.Provider}
			if err := bus.Dispatch(ctx, tenantStatus); err == nil && tenantStatus.Result != nil {
				isEnabled = tenantStatus.Result.IsEnabled
			}
		}

		list = append(list, &dto.OAuthProviderOption{
			Provider:         p.Provider,
			DisplayName:      p.DisplayName,
			ClientID:         p.ClientID,
			URL:              fmt.Sprintf("/oauth/%s", p.Provider),
			CallbackURL:      fmt.Sprintf("%s/oauth/%s/callback", oauthBaseURL, p.Provider),
			IsCustomProvider: isCustomProvider,
			LogoBlobKey:      p.LogoBlobKey,
			IsEnabled:        isEnabled,
		})
	}

	q.Result = list
	return nil
}

// isCustomOAuthProvider reports whether provider is a tenant-defined (custom)
// OAuth provider. Custom provider keys are prefixed with "_".
func isCustomOAuthProvider(provider string) bool {
	return strings.HasPrefix(provider, "_")
}

// requiresSSRFGuard reports whether outbound requests for this provider must
// use the dial-time SSRF guard. Only the built-in system provider configs (with
// their fixed, public Token/Profile URLs) are exempt. Anything else is guarded,
// including a tenant-stored config whose provider key has no "_" prefix (e.g.
// "github" when the built-in GitHub provider is not enabled and getConfig falls
// through to GetCustomOAuthConfigByProvider), so the check fails closed.
func requiresSSRFGuard(provider string, config *entity.OAuthConfig) bool {
	if isCustomOAuthProvider(provider) {
		return true
	}
	for _, p := range systemProviders {
		if p == config {
			return false
		}
	}
	return true
}

// tokenExchangeContext returns the context to pass to oauth2's Exchange.
//
// Custom providers have admin-configurable Token/Profile URLs, so the SSRF
// guard is enforced at dial time for them (the validate.WebhookURL preflight
// can be bypassed via DNS rebinding): when guard is true the context carries
// the guarded HTTP client (see netguard.ClientFor). Built-in providers use
// fixed public URLs and keep oauth2's default client, which honours
// HTTP(S)_PROXY.
func tokenExchangeContext(ctx context.Context, guard bool) context.Context {
	if !guard {
		return ctx
	}
	return context.WithValue(ctx, oauth2.HTTPClient, netguard.ClientFor(true))
}

// newProfileRequest builds the request that fetches the user profile after the
// token exchange. When guard is true it blocks private network targets.
func newProfileRequest(guard bool, profileURL, accessToken string) *cmd.HTTPRequest {
	return &cmd.HTTPRequest{
		URL:    profileURL,
		Method: "GET",
		Headers: map[string]string{
			"Authorization": "Bearer " + accessToken,
		},
		BlockPrivateNetworkTargets: guard,
	}
}

func getConfig(ctx context.Context, provider string) (*entity.OAuthConfig, error) {
	for _, config := range systemProviders {
		if config.Status == enum.OAuthConfigEnabled && config.Provider == provider {
			// Check tenant-level override for built-in providers
			tenantStatus := &query.GetTenantProviderStatus{Provider: provider}
			if err := bus.Dispatch(ctx, tenantStatus); err == nil && tenantStatus.Result != nil {
				if !tenantStatus.Result.IsEnabled {
					return nil, fmt.Errorf("provider %s is disabled for this tenant", provider)
				}
			}
			return config, nil
		}
	}

	getCustomOAuth := &query.GetCustomOAuthConfigByProvider{Provider: provider}
	err := bus.Dispatch(ctx, getCustomOAuth)
	if err != nil {
		return nil, err
	}

	return getCustomOAuth.Result, nil
}