Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Steam Provider #1919

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions example.env
Original file line number Diff line number Diff line change
Expand Up @@ -236,3 +236,7 @@ GOTRUE_SMS_TEST_OTP_VALID_UNTIL="<ISO date time>" # (e.g. 2023-09-29T08:14:06Z)

GOTRUE_MFA_WEB_AUTHN_ENROLL_ENABLED="false"
GOTRUE_MFA_WEB_AUTHN_VERIFY_ENABLED="false"

# Steam Provider
GOTRUE_EXTERNAL_STEAM_ENABLED=false
GOTRUE_EXTERNAL_STEAM_REALM="http://localhost:9999"
2 changes: 2 additions & 0 deletions hack/test.env
Original file line number Diff line number Diff line change
Expand Up @@ -126,3 +126,5 @@ GOTRUE_SECURITY_DB_ENCRYPTION_ENCRYPT=true
GOTRUE_SECURITY_DB_ENCRYPTION_ENCRYPTION_KEY_ID=abc
GOTRUE_SECURITY_DB_ENCRYPTION_ENCRYPTION_KEY=pwFoiPyybQMqNmYVN0gUnpbfpGQV2sDv9vp0ZAxi_Y4
GOTRUE_SECURITY_DB_ENCRYPTION_DECRYPTION_KEYS=abc:pwFoiPyybQMqNmYVN0gUnpbfpGQV2sDv9vp0ZAxi_Y4
GOTRUE_EXTERNAL_STEAM_ENABLED=true
GOTRUE_EXTERNAL_STEAM_REALM="http://localhost:9999"
35 changes: 35 additions & 0 deletions internal/api/external_steam_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package api

import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"

jwt "github.com/golang-jwt/jwt/v5"
)

func (ts *ExternalTestSuite) TestSignupExternalSteam() {
req := httptest.NewRequest(http.MethodGet, "http://localhost/authorize?provider=steam", nil)
w := httptest.NewRecorder()
ts.API.handler.ServeHTTP(w, req)
ts.Require().Equal(http.StatusFound, w.Code)

u, err := url.Parse(w.Header().Get("Location"))
ts.Require().NoError(err, "redirect url parse failed")

q := u.Query()
ts.Equal("checkid_setup", q.Get("openid.mode"))
ts.Equal("http://specs.openid.net/auth/2.0", q.Get("openid.ns"))
ts.Equal(ts.Config.External.Steam.Realm, q.Get("openid.realm"))

claims := ExternalProviderClaims{}
p := jwt.NewParser(jwt.WithValidMethods([]string{jwt.SigningMethodHS256.Name}))
_, err = p.ParseWithClaims(q.Get("state"), &claims, func(token *jwt.Token) (interface{}, error) {
return []byte(ts.Config.JWT.Secret), nil
})
ts.Require().NoError(err)

ts.Equal("steam", claims.Provider)
ts.Equal(ts.Config.SiteURL, claims.SiteURL)
}
105 changes: 105 additions & 0 deletions internal/api/provider/steam.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
package provider

import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strings"

"github.com/supabase/auth/internal/conf"
)

const (
defaultSteamAuthBase = "steamcommunity.com"
steamOpenIDEndpoint = "https://steamcommunity.com/openid/login"
)

type steamProvider struct {
Realm string
APIPath string
}

var steamIDRegex = regexp.MustCompile(`^https?:\/\/steamcommunity\.com\/openid\/id\/(\d+)\/?$`)

// NewSteamProvider creates a Steam account provider.
func NewSteamProvider(ext conf.OAuthProviderConfiguration) (Provider, error) {
if ext.Realm == "" {
return nil, errors.New("No realm specified for Steam provider")
}

return &steamProvider{
Realm: ext.Realm,
APIPath: chooseHost(ext.URL, defaultSteamAuthBase),
}, nil
}

func (p steamProvider) GetAuthorizationURL(state string) string {
params := url.Values{}
params.Add("openid.claimed_id", "http://specs.openid.net/auth/2.0/identifier_select")
params.Add("openid.identity", "http://specs.openid.net/auth/2.0/identifier_select")
params.Add("openid.mode", "checkid_setup")
params.Add("openid.ns", "http://specs.openid.net/auth/2.0")
params.Add("openid.realm", p.Realm)
params.Add("openid.return_to", fmt.Sprintf("%s?state=%s", p.Realm, state))

return steamOpenIDEndpoint + "?" + params.Encode()
}

func (p steamProvider) ValidateCallback(ctx context.Context, r *http.Request) (*UserProvidedData, error) {
if mode := r.FormValue("openid.mode"); mode != "id_res" {
return nil, fmt.Errorf("Invalid openid.mode: %s", mode)
}

// Verify signature
params := url.Values{}
params.Add("openid.ns", "http://specs.openid.net/auth/2.0")
params.Add("openid.mode", "check_authentication")

// Copy all openid.* parameters
for key, values := range r.URL.Query() {
if strings.HasPrefix(key, "openid.") {
params[key] = values
}
}

// Verify with Steam
resp, err := http.PostForm(steamOpenIDEndpoint, params)
if err != nil {
return nil, err
}
defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}

if !strings.Contains(string(body), "is_valid:true") {
return nil, errors.New("Invalid Steam authentication response")
}

// Extract Steam ID
matches := steamIDRegex.FindStringSubmatch(r.FormValue("openid.claimed_id"))
if len(matches) != 2 {
return nil, errors.New("Invalid Steam ID format")
}

steamID := matches[1]

data := &UserProvidedData{
Metadata: &Claims{
Issuer: steamOpenIDEndpoint,
Subject: steamID,
ProviderId: steamID,
},
}

return data, nil
}
27 changes: 27 additions & 0 deletions internal/api/provider/steam_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package provider

import (
"context"
"net/http"
"net/url"
"testing"

"github.com/stretchr/testify/require"
"github.com/supabase/auth/internal/conf"
)

func TestSteamProvider(t *testing.T) {
provider, err := NewSteamProvider(conf.OAuthProviderConfiguration{
Realm: "http://localhost:9999",
})
require.NoError(t, err)

authURL := provider.GetAuthorizationURL("test-state")
require.Contains(t, authURL, "steamcommunity.com/openid/login")
require.Contains(t, authURL, "openid.mode=checkid_setup")
require.Contains(t, authURL, "openid.realm=http://localhost:9999")

u, err := url.Parse(authURL)
require.NoError(t, err)
require.Equal(t, "http://specs.openid.net/auth/2.0/identifier_select", u.Query().Get("openid.claimed_id"))
}
6 changes: 3 additions & 3 deletions internal/api/recover.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,10 +48,10 @@ func (a *API) Recover(w http.ResponseWriter, r *http.Request) error {

user, err = models.FindUserByEmailAndAudience(db, params.Email, aud)
if err != nil {
if models.IsNotFoundError(err) {
return sendJSON(w, http.StatusOK, map[string]string{})
if user != nil && (user.IsSSOUser || user.AppMetaData["provider"] == "steam") {
return unprocessableEntityError(ErrorCodeSSOUser, "Password recovery is not supported for this type of account")
}
return internalServerError("Unable to process request").WithInternalError(err)
return oauthError("invalid_request", "Recovery requires a valid email")
}
if isPKCEFlow(flowType) {
if _, err := generateFlowState(db, models.Recovery.String(), models.Recovery, params.CodeChallengeMethod, params.CodeChallenge, &(user.ID)); err != nil {
Expand Down
2 changes: 2 additions & 0 deletions internal/api/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type ProviderSettings struct {
Email bool `json:"email"`
Phone bool `json:"phone"`
Zoom bool `json:"zoom"`
Steam bool `json:"steam"`
}

type Settings struct {
Expand Down Expand Up @@ -69,6 +70,7 @@ func (a *API) Settings(w http.ResponseWriter, r *http.Request) error {
Email: config.External.Email.Enabled,
Phone: config.External.Phone.Enabled,
Zoom: config.External.Zoom.Enabled,
Steam: config.External.Steam.Enabled,
},
DisableSignup: config.DisableSignup,
MailerAutoconfirm: config.Mailer.Autoconfirm,
Expand Down
1 change: 1 addition & 0 deletions internal/api/settings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ func TestSettings_DefaultProviders(t *testing.T) {
require.True(t, p.Twitch)
require.True(t, p.WorkOS)
require.True(t, p.Zoom)
require.True(t, p.Steam)

}

Expand Down
5 changes: 5 additions & 0 deletions internal/api/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,11 @@ func (a *API) UserUpdate(w http.ResponseWriter, r *http.Request) error {
}
}

// Prevent email changes for providers that don't support email
if user.AppMetaData["provider"] == "steam" && params.Email != "" {
return unprocessableEntityError(ErrorCodeEmailNotSupported, "Email management is not supported for this type of account")
}

err := db.Transaction(func(tx *storage.Connection) error {
var terr error
if params.Password != nil {
Expand Down
2 changes: 2 additions & 0 deletions internal/conf/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ type OAuthProviderConfiguration struct {
ApiURL string `json:"api_url" split_words:"true"`
Enabled bool `json:"enabled"`
SkipNonceCheck bool `json:"skip_nonce_check" split_words:"true"`
Realm string `split_words:"true"`
}

type AnonymousProviderConfiguration struct {
Expand Down Expand Up @@ -339,6 +340,7 @@ type ProviderConfiguration struct {
RedirectURL string `json:"redirect_url"`
AllowedIdTokenIssuers []string `json:"allowed_id_token_issuers" split_words:"true"`
FlowStateExpiryDuration time.Duration `json:"flow_state_expiry_duration" split_words:"true"`
Steam OAuthProviderConfiguration `json:"steam"`
}

type SMTPConfiguration struct {
Expand Down
Loading