Skip to content
Merged
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 common/email_oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,10 @@ const (
// are derived for the console only.
EmailOAuthSecretConfiguredOption = "EmailOAuthSecretConfigured"
EmailOAuthSharedSendGrantedOption = "EmailOAuthSharedSendGranted"
// EmailOAuthRedirectURIOption shows the console the redirect URI the
// authorization flow sends, so the one registered with the provider is
// the one in use whichever website address the console was opened on.
EmailOAuthRedirectURIOption = "EmailOAuthRedirectURI"
)

// EmailOAuthEndpoints holds every provider URL so tests can point them at a
Expand Down
27 changes: 27 additions & 0 deletions common/session_cookie.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package common
import (
"fmt"
"net"
"net/http"
"net/url"
"os"
"strings"
Expand Down Expand Up @@ -41,6 +42,32 @@ func NormalizeOrigin(raw string) (string, error) {
return parsedURL.Scheme + "://" + net.JoinHostPort(hostname, port), nil
}

// RequestBrowserOrigin returns the normalized origin of the page that sent a
// browser request, from a single Origin header or else a single Referer.
func RequestBrowserOrigin(request *http.Request) (string, bool) {
originValues := request.Header.Values("Origin")
if len(originValues) > 1 {
return "", false
}
if len(originValues) == 1 {
if strings.Contains(originValues[0], ",") {
return "", false
}
origin, err := NormalizeOrigin(originValues[0])
return origin, err == nil
}
refererValues := request.Header.Values("Referer")
if len(refererValues) != 1 {
return "", false
}
referer, err := url.Parse(strings.TrimSpace(refererValues[0]))
if err != nil || referer.Scheme == "" || referer.Host == "" || referer.User != nil {
return "", false
}
origin, err := NormalizeOrigin(referer.Scheme + "://" + referer.Host)
return origin, err == nil
}

func InitSessionCookieSettings() error {
secureRaw := strings.TrimSpace(os.Getenv("SESSION_COOKIE_SECURE"))
trustedURLsRaw := strings.TrimSpace(os.Getenv("SESSION_COOKIE_TRUSTED_URL"))
Expand Down
74 changes: 69 additions & 5 deletions controller/auth_flow_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -623,16 +623,18 @@ func TestSecurityLoginRequiresConfiguredFactors(t *testing.T) {
}

type authFlowTestOAuthProvider struct {
exchangeErr error
userInfoErr error
exchangeCalls int
userInfoCalls int
exchangeErr error
userInfoErr error
exchangeCalls int
userInfoCalls int
callbackAddress string
}

func (*authFlowTestOAuthProvider) GetName() string { return "Auth Flow Test" }
func (*authFlowTestOAuthProvider) IsEnabled() bool { return true }
func (provider *authFlowTestOAuthProvider) ExchangeToken(context.Context, string, *gin.Context) (*oauth.OAuthToken, error) {
func (provider *authFlowTestOAuthProvider) ExchangeToken(_ context.Context, _ string, c *gin.Context) (*oauth.OAuthToken, error) {
provider.exchangeCalls++
provider.callbackAddress = oauth.CallbackAddress(c)
if provider.exchangeErr != nil {
return nil, provider.exchangeErr
}
Expand Down Expand Up @@ -702,6 +704,68 @@ func TestGenerateOAuthCodeCarriesAffiliateInLoginFlow(t *testing.T) {
assert.Empty(t, flow.SessionId)
}

func TestOAuthCallbackRepeatsRedirectAddressOfStartingLine(t *testing.T) {
provider := setupAuthFlowControllerTest(t)
previousAddress, previousAlternates := system_setting.ServerAddress, system_setting.AlternateServerAddresses()
system_setting.ServerAddress = "https://main.example.com"
system_setting.SetAlternateServerAddresses([]string{"https://line2.example.com"})
t.Cleanup(func() {
system_setting.ServerAddress = previousAddress
system_setting.SetAlternateServerAddresses(previousAlternates)
})
router := gin.New()
router.POST("/api/oauth/state", GenerateOAuthCode)
router.GET("/api/oauth/:provider", HandleOAuth)

for _, test := range []struct {
name string
origin string
expected string
}{
{name: "alternate line", origin: "https://line2.example.com", expected: "https://line2.example.com"},
{name: "primary line", origin: "https://main.example.com", expected: "https://main.example.com"},
{name: "unconfigured origin", origin: "https://attacker.example", expected: "https://main.example.com"},
} {
t.Run(test.name, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/oauth/state", strings.NewReader(`{"provider":"auth-flow-test","intent":"login"}`))
request.Host = "main.example.com"
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Origin", test.origin)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
var result struct {
Data struct {
FlowToken string `json:"flow_token"`
} `json:"data"`
}
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
require.NotEmpty(t, result.Data.FlowToken, response.Body.String())

// The callback reaches the server through another line; the flow decides.
request = httptest.NewRequest(http.MethodGet, "/api/oauth/auth-flow-test?state="+result.Data.FlowToken+"&code=test", nil)
request.Host = "main.example.com"
router.ServeHTTP(httptest.NewRecorder(), request)
assert.Equal(t, test.expected, provider.callbackAddress)
})
}

// A line removed after the flow started is no longer used as redirect_uri.
request := httptest.NewRequest(http.MethodPost, "/api/oauth/state", strings.NewReader(`{"provider":"auth-flow-test","intent":"login"}`))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Origin", "https://line2.example.com")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
var result struct {
Data struct {
FlowToken string `json:"flow_token"`
} `json:"data"`
}
require.NoError(t, common.Unmarshal(response.Body.Bytes(), &result))
system_setting.SetAlternateServerAddresses(nil)
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/oauth/auth-flow-test?state="+result.Data.FlowToken+"&code=test", nil))
assert.Equal(t, "https://main.example.com", provider.callbackAddress)
}

func TestGenerateOAuthCodeBindsFlowToAuthenticatedSession(t *testing.T) {
_, identity := setupSecurityEnrollmentTest(t)
oauth.Register("auth-flow-test", &authFlowTestOAuthProvider{})
Expand Down
10 changes: 9 additions & 1 deletion controller/email_oauth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,12 +115,20 @@ func TestEmailOAuthAuthorizationStoresMailboxOnce(t *testing.T) {
options := httptest.NewRecorder()
context, _ := gin.CreateTestContext(options)
context.Request = httptest.NewRequest(http.MethodGet, "/api/option/", nil)
// The console is open on an alternate line; the redirect URI to
// register stays the one the authorization flow sent.
previousAlternates := system_setting.AlternateServerAddresses()
system_setting.SetAlternateServerAddresses([]string{"https://line2.example.com"})
t.Cleanup(func() { system_setting.SetAlternateServerAddresses(previousAlternates) })
context.Request.Host = "line2.example.com"
context.Request.Header.Set("Origin", "https://line2.example.com")
GetOptions(context)
assert.NotContains(t, options.Body.String(), "refresh-granted")
assert.NotContains(t, options.Body.String(), "client-secret")
assert.NotContains(t, options.Body.String(), common.EmailOAuthRefreshTokenOption)
assert.Contains(t, options.Body.String(), `"key":"EmailOAuthEmail","value":"`+test.email+`"`)
assert.Contains(t, options.Body.String(), `"key":"EmailOAuthSecretConfigured","value":"true"`)
assert.Contains(t, options.Body.String(), `"key":"EmailOAuthRedirectURI","value":"`+emailOAuthTestRedirectURI+`"`)

// Replaying the same state is rejected without a second exchange.
replay := completeEmailOAuth(identity, body)
Expand Down Expand Up @@ -304,7 +312,7 @@ func TestEmailOAuthSenderOptionAcceptsOneBareAddress(t *testing.T) {
assert.Empty(t, common.OptionMap[common.EmailOAuthFromOption])
assert.Contains(t, update(common.EmailOAuthFromOption, "shared@contoso.example"), `"success":true`)
assert.Contains(t, update(common.EmailOAuthFromOption, ""), `"success":true`)
for _, key := range []string{common.EmailOAuthScopesOption, common.EmailOAuthSharedSendGrantedOption} {
for _, key := range []string{common.EmailOAuthScopesOption, common.EmailOAuthSharedSendGrantedOption, common.EmailOAuthRedirectURIOption} {
assert.Contains(t, update(key, "https://graph.microsoft.com/Mail.Send.Shared"), `"message_key":"This setting is managed by the mailbox authorization flow"`, key)
}
}
Expand Down
4 changes: 2 additions & 2 deletions controller/misc.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ func GetStatus(c *gin.Context) {
"footer_html": common.Footer,
"wechat_qrcode": common.WeChatAccountQRCodeImageURL,
"wechat_login": common.WeChatAuthEnabled,
"server_address": system_setting.ServerAddress,
"server_address": service.RequestServerAddress(c.Request),
"turnstile_check": common.TurnstileCheckEnabled,
"turnstile_site_key": common.TurnstileSiteKey,
"docs_link": operation_setting.GetGeneralSetting().DocsLink,
Expand Down Expand Up @@ -270,7 +270,7 @@ func SendPasswordResetEmail(c *gin.Context) {
if user, err := model.GetUniqueUserByEmail(email); err == nil {
code := common.GenerateVerificationCode(0)
common.RegisterVerificationCodeWithKey(email, code, common.PasswordResetPurpose)
link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", system_setting.ServerAddress, email, code)
link := fmt.Sprintf("%s/user/reset?email=%s&token=%s", service.RequestServerAddress(c.Request), email, code)
lang := user.GetSetting().Language
if lang == "" {
lang = i18n.StatedLang(c)
Expand Down
14 changes: 11 additions & 3 deletions controller/oauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ type oauthStateRequest struct {
}

type oauthFlowPayload struct {
// SiteAddress is the website line the flow started on; its redirect_uri
// must be repeated when the code is exchanged.
SiteAddress string `json:"site_address,omitempty"`
AffiliateCode string `json:"affiliate_code,omitempty"`
Verification *service.OAuthVerificationFlow `json:"verification,omitempty"`
Telegram *oauth.TelegramOAuthFlow `json:"telegram,omitempty"`
Expand Down Expand Up @@ -62,10 +65,10 @@ func GenerateOAuthCode(c *gin.Context) {
}
userID := 0
sessionID := ""
flowPayload := oauthFlowPayload{AffiliateCode: request.Aff}
flowPayload := oauthFlowPayload{AffiliateCode: request.Aff, SiteAddress: service.RequestServerAddress(c.Request)}
bindingStarted := false
if request.Provider == "telegram" {
telegramFlow, err := oauth.NewTelegramOAuthFlow()
telegramFlow, err := oauth.NewTelegramOAuthFlow(flowPayload.SiteAddress)
if err != nil {
writeSecurityOperationError(c, err)
return
Expand Down Expand Up @@ -249,7 +252,12 @@ func HandleOAuth(c *gin.Context) {
})
return
}
// 5. Exchange code for token
// 5. Exchange code for token with the redirect_uri of the line the flow started on
// (an unreadable payload falls back to ServerAddress; later steps reject it).
var sitePayload oauthFlowPayload
if err := common.UnmarshalJsonStr(pendingFlow.Payload, &sitePayload); err == nil {
c.Set(oauth.SiteAddressContextKey, sitePayload.SiteAddress)
}
code := c.Query("code")
token, err := provider.ExchangeToken(c.Request.Context(), code, c)
if err != nil {
Expand Down
4 changes: 3 additions & 1 deletion controller/option.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ func GetOptions(c *gin.Context) {
common.OptionMapRWMutex.Lock()
for k, v := range common.OptionMap {
if k == "theme.frontend" || k == "billing_setting.billing_mode" || k == "billing_setting.billing_expr" || k == "ResendKeyConfigured" || k == common.EmailOAuthSecretConfiguredOption ||
k == common.EmailOAuthScopesOption || k == common.EmailOAuthSharedSendGrantedOption {
k == common.EmailOAuthScopesOption || k == common.EmailOAuthSharedSendGrantedOption || k == common.EmailOAuthRedirectURIOption {
continue
}
value := common.Interface2String(v)
Expand All @@ -113,6 +113,8 @@ func GetOptions(c *gin.Context) {
Key: common.EmailOAuthSecretConfiguredOption, Value: strconv.FormatBool(strings.TrimSpace(common.OptionMap[common.EmailOAuthClientSecretOption]) != ""),
}, &model.Option{
Key: common.EmailOAuthSharedSendGrantedOption, Value: strconv.FormatBool(common.EmailOAuthSharedSendGranted(common.OptionMap[common.EmailOAuthScopesOption])),
}, &model.Option{
Key: common.EmailOAuthRedirectURIOption, Value: emailOAuthRedirectURI(),
})
common.OptionMapRWMutex.Unlock()
// Display the same effective expressions used by pricing and settlement,
Expand Down
10 changes: 4 additions & 6 deletions controller/return_path.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
package controller

import (
"strings"

"github.com/QuantumNous/new-api/setting/system_setting"
"github.com/QuantumNous/new-api/service"
"github.com/gin-gonic/gin"
)

func paymentReturnPath(suffix string) string {
base := strings.TrimRight(system_setting.ServerAddress, "/")
return base + suffix
func paymentReturnPath(c *gin.Context, suffix string) string {
return service.RequestServerAddress(c.Request) + suffix
}
Loading