mirror of
https://github.com/steveiliop56/tinyauth.git
synced 2026-04-08 14:57:58 +00:00
Compare commits
1 Commits
feat/prese
...
dependabot
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6a9ccf9e76 |
@@ -76,14 +76,10 @@ export const LoginPage = () => {
|
|||||||
isPending: oauthIsPending,
|
isPending: oauthIsPending,
|
||||||
variables: oauthVariables,
|
variables: oauthVariables,
|
||||||
} = useMutation({
|
} = useMutation({
|
||||||
mutationFn: (provider: string) => {
|
mutationFn: (provider: string) =>
|
||||||
const params = isOidc
|
axios.get(
|
||||||
? `?${compiledOIDCParams}`
|
`/api/oauth/url/${provider}${props.redirect_uri ? `?redirect_uri=${encodeURIComponent(props.redirect_uri)}` : ""}`,
|
||||||
: props.redirect_uri
|
),
|
||||||
? `?redirect_uri=${encodeURIComponent(props.redirect_uri)}`
|
|
||||||
: "";
|
|
||||||
return axios.get(`/api/oauth/url/${provider}${params}`);
|
|
||||||
},
|
|
||||||
mutationKey: ["oauth"],
|
mutationKey: ["oauth"],
|
||||||
onSuccess: (data) => {
|
onSuccess: (data) => {
|
||||||
toast.info(t("loginOauthSuccessTitle"), {
|
toast.info(t("loginOauthSuccessTitle"), {
|
||||||
|
|||||||
2
go.mod
2
go.mod
@@ -24,7 +24,7 @@ require (
|
|||||||
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546
|
golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546
|
||||||
golang.org/x/oauth2 v0.36.0
|
golang.org/x/oauth2 v0.36.0
|
||||||
gotest.tools/v3 v3.5.2
|
gotest.tools/v3 v3.5.2
|
||||||
modernc.org/sqlite v1.48.0
|
modernc.org/sqlite v1.48.1
|
||||||
)
|
)
|
||||||
|
|
||||||
require (
|
require (
|
||||||
|
|||||||
4
go.sum
4
go.sum
@@ -389,8 +389,8 @@ modernc.org/opt v0.1.4 h1:2kNGMRiUjrp4LcaPuLY2PzUfqM/w9N23quVwhKt5Qm8=
|
|||||||
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
modernc.org/opt v0.1.4/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
|
||||||
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
|
||||||
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
|
||||||
modernc.org/sqlite v1.48.0 h1:ElZyLop3Q2mHYk5IFPPXADejZrlHu7APbpB0sF78bq4=
|
modernc.org/sqlite v1.48.1 h1:S85iToyU6cgeojybE2XJlSbcsvcWkQ6qqNXJHtW5hWA=
|
||||||
modernc.org/sqlite v1.48.0/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig=
|
modernc.org/sqlite v1.48.1/go.mod h1:hWjRO6Tj/5Ik8ieqxQybiEOUXy0NJFNp2tpvVpKlvig=
|
||||||
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
|
||||||
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
|
||||||
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
|
||||||
|
|||||||
@@ -62,29 +62,7 @@ func (controller *OAuthController) oauthURLHandler(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var reqParams service.OAuthURLParams
|
sessionId, session, err := controller.auth.NewOAuthSession(req.Provider)
|
||||||
|
|
||||||
err = c.BindQuery(&reqParams)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
tlog.App.Error().Err(err).Msg("Failed to bind query parameters")
|
|
||||||
c.JSON(400, gin.H{
|
|
||||||
"status": 400,
|
|
||||||
"message": "Bad Request",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if !controller.isOidcRequest(reqParams) {
|
|
||||||
isRedirectSafe := utils.IsRedirectSafe(reqParams.RedirectURI, controller.config.CookieDomain)
|
|
||||||
|
|
||||||
if !isRedirectSafe {
|
|
||||||
tlog.App.Warn().Str("redirect_uri", reqParams.RedirectURI).Msg("Unsafe redirect URI detected, ignoring")
|
|
||||||
reqParams.RedirectURI = ""
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sessionId, _, err := controller.auth.NewOAuthSession(req.Provider, reqParams)
|
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
tlog.App.Error().Err(err).Msg("Failed to create OAuth session")
|
tlog.App.Error().Err(err).Msg("Failed to create OAuth session")
|
||||||
@@ -107,6 +85,20 @@ func (controller *OAuthController) oauthURLHandler(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.SetCookie(controller.config.OAuthSessionCookieName, sessionId, int(time.Hour.Seconds()), "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true)
|
c.SetCookie(controller.config.OAuthSessionCookieName, sessionId, int(time.Hour.Seconds()), "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true)
|
||||||
|
c.SetCookie(controller.config.CSRFCookieName, session.State, int(time.Hour.Seconds()), "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true)
|
||||||
|
|
||||||
|
redirectURI := c.Query("redirect_uri")
|
||||||
|
isRedirectSafe := utils.IsRedirectSafe(redirectURI, controller.config.CookieDomain)
|
||||||
|
|
||||||
|
if !isRedirectSafe {
|
||||||
|
tlog.App.Warn().Str("redirect_uri", redirectURI).Msg("Unsafe redirect URI detected, ignoring")
|
||||||
|
redirectURI = ""
|
||||||
|
}
|
||||||
|
|
||||||
|
if redirectURI != "" && isRedirectSafe {
|
||||||
|
tlog.App.Debug().Msg("Setting redirect URI cookie")
|
||||||
|
c.SetCookie(controller.config.RedirectCookieName, redirectURI, int(time.Hour.Seconds()), "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true)
|
||||||
|
}
|
||||||
|
|
||||||
c.JSON(200, gin.H{
|
c.JSON(200, gin.H{
|
||||||
"status": 200,
|
"status": 200,
|
||||||
@@ -137,24 +129,20 @@ func (controller *OAuthController) oauthCallbackHandler(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
c.SetCookie(controller.config.OAuthSessionCookieName, "", -1, "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true)
|
c.SetCookie(controller.config.OAuthSessionCookieName, "", -1, "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true)
|
||||||
|
|
||||||
oauthPendingSession, err := controller.auth.GetOAuthPendingSession(sessionIdCookie)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
tlog.App.Error().Err(err).Msg("Failed to get OAuth pending session")
|
|
||||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.config.AppURL))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
defer controller.auth.EndOAuthSession(sessionIdCookie)
|
defer controller.auth.EndOAuthSession(sessionIdCookie)
|
||||||
|
|
||||||
state := c.Query("state")
|
state := c.Query("state")
|
||||||
if state != oauthPendingSession.State {
|
csrfCookie, err := c.Cookie(controller.config.CSRFCookieName)
|
||||||
tlog.App.Warn().Err(err).Msg("CSRF token mismatch")
|
|
||||||
|
if err != nil || state != csrfCookie {
|
||||||
|
tlog.App.Warn().Err(err).Msg("CSRF token mismatch or cookie missing")
|
||||||
|
c.SetCookie(controller.config.CSRFCookieName, "", -1, "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true)
|
||||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.config.AppURL))
|
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.config.AppURL))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.SetCookie(controller.config.CSRFCookieName, "", -1, "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true)
|
||||||
|
|
||||||
code := c.Query("code")
|
code := c.Query("code")
|
||||||
_, err = controller.auth.GetOAuthToken(sessionIdCookie, code)
|
_, err = controller.auth.GetOAuthToken(sessionIdCookie, code)
|
||||||
|
|
||||||
@@ -210,7 +198,7 @@ func (controller *OAuthController) oauthCallbackHandler(c *gin.Context) {
|
|||||||
username = strings.Replace(user.Email, "@", "_", 1)
|
username = strings.Replace(user.Email, "@", "_", 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
svc, err := controller.auth.GetOAuthService(sessionIdCookie)
|
service, err := controller.auth.GetOAuthService(sessionIdCookie)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
tlog.App.Error().Err(err).Msg("Failed to get OAuth service for session")
|
tlog.App.Error().Err(err).Msg("Failed to get OAuth service for session")
|
||||||
@@ -218,8 +206,8 @@ func (controller *OAuthController) oauthCallbackHandler(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if svc.ID() != req.Provider {
|
if service.ID() != req.Provider {
|
||||||
tlog.App.Error().Msgf("OAuth service ID mismatch: expected %s, got %s", svc.ID(), req.Provider)
|
tlog.App.Error().Msgf("OAuth service ID mismatch: expected %s, got %s", service.ID(), req.Provider)
|
||||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.config.AppURL))
|
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.config.AppURL))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -228,9 +216,9 @@ func (controller *OAuthController) oauthCallbackHandler(c *gin.Context) {
|
|||||||
Username: username,
|
Username: username,
|
||||||
Name: name,
|
Name: name,
|
||||||
Email: user.Email,
|
Email: user.Email,
|
||||||
Provider: svc.ID(),
|
Provider: service.ID(),
|
||||||
OAuthGroups: utils.CoalesceToString(user.Groups),
|
OAuthGroups: utils.CoalesceToString(user.Groups),
|
||||||
OAuthName: svc.Name(),
|
OAuthName: service.Name(),
|
||||||
OAuthSub: user.Sub,
|
OAuthSub: user.Sub,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -246,21 +234,16 @@ func (controller *OAuthController) oauthCallbackHandler(c *gin.Context) {
|
|||||||
|
|
||||||
tlog.AuditLoginSuccess(c, sessionCookie.Username, sessionCookie.Provider)
|
tlog.AuditLoginSuccess(c, sessionCookie.Username, sessionCookie.Provider)
|
||||||
|
|
||||||
if controller.isOidcRequest(oauthPendingSession.CallbackParams) {
|
redirectURI, err := c.Cookie(controller.config.RedirectCookieName)
|
||||||
tlog.App.Debug().Msg("OIDC request, redirecting to authorize page")
|
|
||||||
queries, err := query.Values(oauthPendingSession.CallbackParams)
|
if err != nil || !utils.IsRedirectSafe(redirectURI, controller.config.CookieDomain) {
|
||||||
if err != nil {
|
tlog.App.Debug().Msg("No redirect URI cookie found, redirecting to app root")
|
||||||
tlog.App.Error().Err(err).Msg("Failed to encode OIDC callback query")
|
c.Redirect(http.StatusTemporaryRedirect, controller.config.AppURL)
|
||||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/error", controller.config.AppURL))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/authorize?%s", controller.config.AppURL, queries.Encode()))
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
if oauthPendingSession.CallbackParams.RedirectURI != "" {
|
|
||||||
queries, err := query.Values(config.RedirectQuery{
|
queries, err := query.Values(config.RedirectQuery{
|
||||||
RedirectURI: oauthPendingSession.CallbackParams.RedirectURI,
|
RedirectURI: redirectURI,
|
||||||
})
|
})
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -269,16 +252,6 @@ func (controller *OAuthController) oauthCallbackHandler(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
c.SetCookie(controller.config.RedirectCookieName, "", -1, "/", fmt.Sprintf(".%s", controller.config.CookieDomain), controller.config.SecureCookie, true)
|
||||||
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/continue?%s", controller.config.AppURL, queries.Encode()))
|
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s/continue?%s", controller.config.AppURL, queries.Encode()))
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
c.Redirect(http.StatusTemporaryRedirect, controller.config.AppURL)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (controller *OAuthController) isOidcRequest(params service.OAuthURLParams) bool {
|
|
||||||
return params.Scope != "" &&
|
|
||||||
params.ResponseType != "" &&
|
|
||||||
params.ClientID != "" &&
|
|
||||||
params.RedirectURI != ""
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
"github.com/google/go-querystring/query"
|
"github.com/google/go-querystring/query"
|
||||||
|
|
||||||
"github.com/steveiliop56/tinyauth/internal/service"
|
"github.com/steveiliop56/tinyauth/internal/service"
|
||||||
"github.com/steveiliop56/tinyauth/internal/utils"
|
"github.com/steveiliop56/tinyauth/internal/utils"
|
||||||
"github.com/steveiliop56/tinyauth/internal/utils/tlog"
|
"github.com/steveiliop56/tinyauth/internal/utils/tlog"
|
||||||
@@ -377,15 +376,14 @@ func (controller *OIDCController) Userinfo(c *gin.Context) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
var token string
|
|
||||||
|
|
||||||
authorization := c.GetHeader("Authorization")
|
authorization := c.GetHeader("Authorization")
|
||||||
if authorization != "" {
|
|
||||||
tokenType, bearerToken, ok := strings.Cut(authorization, " ")
|
tokenType, token, ok := strings.Cut(authorization, " ")
|
||||||
|
|
||||||
if !ok {
|
if !ok {
|
||||||
tlog.App.Warn().Msg("OIDC userinfo accessed with malformed authorization header")
|
tlog.App.Warn().Msg("OIDC userinfo accessed without authorization header")
|
||||||
c.JSON(401, gin.H{
|
c.JSON(401, gin.H{
|
||||||
"error": "invalid_request",
|
"error": "invalid_grant",
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -393,32 +391,7 @@ func (controller *OIDCController) Userinfo(c *gin.Context) {
|
|||||||
if strings.ToLower(tokenType) != "bearer" {
|
if strings.ToLower(tokenType) != "bearer" {
|
||||||
tlog.App.Warn().Msg("OIDC userinfo accessed with invalid token type")
|
tlog.App.Warn().Msg("OIDC userinfo accessed with invalid token type")
|
||||||
c.JSON(401, gin.H{
|
c.JSON(401, gin.H{
|
||||||
"error": "invalid_request",
|
"error": "invalid_grant",
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
token = bearerToken
|
|
||||||
} else if c.Request.Method == http.MethodPost {
|
|
||||||
if c.ContentType() != "application/x-www-form-urlencoded" {
|
|
||||||
tlog.App.Warn().Msg("OIDC userinfo POST accessed with invalid content type")
|
|
||||||
c.JSON(400, gin.H{
|
|
||||||
"error": "invalid_request",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
token = c.PostForm("access_token")
|
|
||||||
if token == "" {
|
|
||||||
tlog.App.Warn().Msg("OIDC userinfo POST accessed without access_token in body")
|
|
||||||
c.JSON(401, gin.H{
|
|
||||||
"error": "invalid_request",
|
|
||||||
})
|
|
||||||
return
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
tlog.App.Warn().Msg("OIDC userinfo accessed without authorization header")
|
|
||||||
c.JSON(401, gin.H{
|
|
||||||
"error": "invalid_request",
|
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -435,128 +435,6 @@ func TestOIDCController(t *testing.T) {
|
|||||||
assert.False(t, ok, "Did not expect email claim in userinfo response")
|
assert.False(t, ok, "Did not expect email claim in userinfo response")
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
{
|
|
||||||
description: "Ensure userinfo forbids access with no authorization header",
|
|
||||||
middlewares: []gin.HandlerFunc{},
|
|
||||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
|
||||||
req := httptest.NewRequest("GET", "/api/oidc/userinfo", nil)
|
|
||||||
router.ServeHTTP(recorder, req)
|
|
||||||
assert.Equal(t, 401, recorder.Code)
|
|
||||||
|
|
||||||
var res map[string]any
|
|
||||||
err := json.Unmarshal(recorder.Body.Bytes(), &res)
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Equal(t, "invalid_request", res["error"])
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
description: "Ensure userinfo forbids access with malformed authorization header",
|
|
||||||
middlewares: []gin.HandlerFunc{},
|
|
||||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
|
||||||
req := httptest.NewRequest("GET", "/api/oidc/userinfo", nil)
|
|
||||||
req.Header.Set("Authorization", "Bearer")
|
|
||||||
router.ServeHTTP(recorder, req)
|
|
||||||
assert.Equal(t, 401, recorder.Code)
|
|
||||||
|
|
||||||
var res map[string]any
|
|
||||||
err := json.Unmarshal(recorder.Body.Bytes(), &res)
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Equal(t, "invalid_request", res["error"])
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
description: "Ensure userinfo forbids access with invalid token type",
|
|
||||||
middlewares: []gin.HandlerFunc{},
|
|
||||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
|
||||||
req := httptest.NewRequest("GET", "/api/oidc/userinfo", nil)
|
|
||||||
req.Header.Set("Authorization", "Basic some-token")
|
|
||||||
router.ServeHTTP(recorder, req)
|
|
||||||
assert.Equal(t, 401, recorder.Code)
|
|
||||||
|
|
||||||
var res map[string]any
|
|
||||||
err := json.Unmarshal(recorder.Body.Bytes(), &res)
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Equal(t, "invalid_request", res["error"])
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
description: "Ensure userinfo forbids access with empty bearer token",
|
|
||||||
middlewares: []gin.HandlerFunc{},
|
|
||||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
|
||||||
req := httptest.NewRequest("GET", "/api/oidc/userinfo", nil)
|
|
||||||
req.Header.Set("Authorization", "Bearer ")
|
|
||||||
router.ServeHTTP(recorder, req)
|
|
||||||
assert.Equal(t, 401, recorder.Code)
|
|
||||||
|
|
||||||
var res map[string]any
|
|
||||||
err := json.Unmarshal(recorder.Body.Bytes(), &res)
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Equal(t, "invalid_grant", res["error"])
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
description: "Ensure userinfo POST rejects missing access token in body",
|
|
||||||
middlewares: []gin.HandlerFunc{},
|
|
||||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
|
||||||
req := httptest.NewRequest("POST", "/api/oidc/userinfo", strings.NewReader(""))
|
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
router.ServeHTTP(recorder, req)
|
|
||||||
assert.Equal(t, 401, recorder.Code)
|
|
||||||
|
|
||||||
var res map[string]any
|
|
||||||
err := json.Unmarshal(recorder.Body.Bytes(), &res)
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Equal(t, "invalid_request", res["error"])
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
description: "Ensure userinfo POST rejects wrong content type",
|
|
||||||
middlewares: []gin.HandlerFunc{},
|
|
||||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
|
||||||
req := httptest.NewRequest("POST", "/api/oidc/userinfo", strings.NewReader(`{"access_token":"some-token"}`))
|
|
||||||
req.Header.Set("Content-Type", "application/json")
|
|
||||||
router.ServeHTTP(recorder, req)
|
|
||||||
assert.Equal(t, 400, recorder.Code)
|
|
||||||
|
|
||||||
var res map[string]any
|
|
||||||
err := json.Unmarshal(recorder.Body.Bytes(), &res)
|
|
||||||
assert.NoError(t, err)
|
|
||||||
assert.Equal(t, "invalid_request", res["error"])
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
|
||||||
description: "Ensure userinfo accepts access token via POST body",
|
|
||||||
middlewares: []gin.HandlerFunc{
|
|
||||||
simpleCtx,
|
|
||||||
},
|
|
||||||
run: func(t *testing.T, router *gin.Engine, recorder *httptest.ResponseRecorder) {
|
|
||||||
tokenTest, found := getTestByDescription("Ensure we can get a token with a valid request")
|
|
||||||
assert.True(t, found, "Token test not found")
|
|
||||||
tokenRecorder := httptest.NewRecorder()
|
|
||||||
tokenTest(t, router, tokenRecorder)
|
|
||||||
|
|
||||||
var tokenRes map[string]any
|
|
||||||
err := json.Unmarshal(tokenRecorder.Body.Bytes(), &tokenRes)
|
|
||||||
assert.NoError(t, err)
|
|
||||||
|
|
||||||
accessToken := tokenRes["access_token"].(string)
|
|
||||||
assert.NotEmpty(t, accessToken)
|
|
||||||
|
|
||||||
body := url.Values{}
|
|
||||||
body.Set("access_token", accessToken)
|
|
||||||
req := httptest.NewRequest("POST", "/api/oidc/userinfo", strings.NewReader(body.Encode()))
|
|
||||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
|
||||||
router.ServeHTTP(recorder, req)
|
|
||||||
assert.Equal(t, 200, recorder.Code)
|
|
||||||
|
|
||||||
var userInfoRes map[string]any
|
|
||||||
err = json.Unmarshal(recorder.Body.Bytes(), &userInfoRes)
|
|
||||||
assert.NoError(t, err)
|
|
||||||
|
|
||||||
_, ok := userInfoRes["sub"]
|
|
||||||
assert.True(t, ok, "Expected sub claim in userinfo response")
|
|
||||||
},
|
|
||||||
},
|
|
||||||
{
|
{
|
||||||
description: "Ensure plain PKCE succeeds",
|
description: "Ensure plain PKCE succeeds",
|
||||||
middlewares: []gin.HandlerFunc{
|
middlewares: []gin.HandlerFunc{
|
||||||
|
|||||||
@@ -28,26 +28,12 @@ const MaxOAuthPendingSessions = 256
|
|||||||
const OAuthCleanupCount = 16
|
const OAuthCleanupCount = 16
|
||||||
const MaxLoginAttemptRecords = 256
|
const MaxLoginAttemptRecords = 256
|
||||||
|
|
||||||
// slightly modified version of the AuthorizeRequest from the OIDC service to basically accept all
|
|
||||||
// parameters and pass them to the authorize page if needed
|
|
||||||
type OAuthURLParams struct {
|
|
||||||
Scope string `form:"scope" url:"scope"`
|
|
||||||
ResponseType string `form:"response_type" url:"response_type"`
|
|
||||||
ClientID string `form:"client_id" url:"client_id"`
|
|
||||||
RedirectURI string `form:"redirect_uri" url:"redirect_uri"`
|
|
||||||
State string `form:"state" url:"state"`
|
|
||||||
Nonce string `form:"nonce" url:"nonce"`
|
|
||||||
CodeChallenge string `form:"code_challenge" url:"code_challenge"`
|
|
||||||
CodeChallengeMethod string `form:"code_challenge_method" url:"code_challenge_method"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type OAuthPendingSession struct {
|
type OAuthPendingSession struct {
|
||||||
State string
|
State string
|
||||||
Verifier string
|
Verifier string
|
||||||
Token *oauth2.Token
|
Token *oauth2.Token
|
||||||
Service *OAuthServiceImpl
|
Service *OAuthServiceImpl
|
||||||
ExpiresAt time.Time
|
ExpiresAt time.Time
|
||||||
CallbackParams OAuthURLParams
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type LdapGroupsCache struct {
|
type LdapGroupsCache struct {
|
||||||
@@ -612,7 +598,7 @@ func (auth *AuthService) IsBypassedIP(acls config.AppIP, ip string) bool {
|
|||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func (auth *AuthService) NewOAuthSession(serviceName string, params OAuthURLParams) (string, OAuthPendingSession, error) {
|
func (auth *AuthService) NewOAuthSession(serviceName string) (string, OAuthPendingSession, error) {
|
||||||
auth.ensureOAuthSessionLimit()
|
auth.ensureOAuthSessionLimit()
|
||||||
|
|
||||||
service, ok := auth.oauthBroker.GetService(serviceName)
|
service, ok := auth.oauthBroker.GetService(serviceName)
|
||||||
@@ -635,7 +621,6 @@ func (auth *AuthService) NewOAuthSession(serviceName string, params OAuthURLPara
|
|||||||
Verifier: verifier,
|
Verifier: verifier,
|
||||||
Service: &service,
|
Service: &service,
|
||||||
ExpiresAt: time.Now().Add(1 * time.Hour),
|
ExpiresAt: time.Now().Add(1 * time.Hour),
|
||||||
CallbackParams: params,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
auth.oauthMutex.Lock()
|
auth.oauthMutex.Lock()
|
||||||
@@ -646,7 +631,7 @@ func (auth *AuthService) NewOAuthSession(serviceName string, params OAuthURLPara
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (auth *AuthService) GetOAuthURL(sessionId string) (string, error) {
|
func (auth *AuthService) GetOAuthURL(sessionId string) (string, error) {
|
||||||
session, err := auth.GetOAuthPendingSession(sessionId)
|
session, err := auth.getOAuthPendingSession(sessionId)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -656,7 +641,7 @@ func (auth *AuthService) GetOAuthURL(sessionId string) (string, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (auth *AuthService) GetOAuthToken(sessionId string, code string) (*oauth2.Token, error) {
|
func (auth *AuthService) GetOAuthToken(sessionId string, code string) (*oauth2.Token, error) {
|
||||||
session, err := auth.GetOAuthPendingSession(sessionId)
|
session, err := auth.getOAuthPendingSession(sessionId)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -676,7 +661,7 @@ func (auth *AuthService) GetOAuthToken(sessionId string, code string) (*oauth2.T
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (auth *AuthService) GetOAuthUserinfo(sessionId string) (config.Claims, error) {
|
func (auth *AuthService) GetOAuthUserinfo(sessionId string) (config.Claims, error) {
|
||||||
session, err := auth.GetOAuthPendingSession(sessionId)
|
session, err := auth.getOAuthPendingSession(sessionId)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return config.Claims{}, err
|
return config.Claims{}, err
|
||||||
@@ -696,7 +681,7 @@ func (auth *AuthService) GetOAuthUserinfo(sessionId string) (config.Claims, erro
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (auth *AuthService) GetOAuthService(sessionId string) (OAuthServiceImpl, error) {
|
func (auth *AuthService) GetOAuthService(sessionId string) (OAuthServiceImpl, error) {
|
||||||
session, err := auth.GetOAuthPendingSession(sessionId)
|
session, err := auth.getOAuthPendingSession(sessionId)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -730,7 +715,7 @@ func (auth *AuthService) CleanupOAuthSessionsRoutine() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (auth *AuthService) GetOAuthPendingSession(sessionId string) (*OAuthPendingSession, error) {
|
func (auth *AuthService) getOAuthPendingSession(sessionId string) (*OAuthPendingSession, error) {
|
||||||
auth.ensureOAuthSessionLimit()
|
auth.ensureOAuthSessionLimit()
|
||||||
|
|
||||||
auth.oauthMutex.RLock()
|
auth.oauthMutex.RLock()
|
||||||
|
|||||||
Reference in New Issue
Block a user