|
| 1 | +package controller |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "net/http" |
| 6 | + "net/http/httptest" |
| 7 | + "net/url" |
| 8 | + "strings" |
| 9 | + "testing" |
| 10 | + "time" |
| 11 | + |
| 12 | + "github.com/gin-gonic/gin" |
| 13 | + "github.com/steveiliop56/ding" |
| 14 | + "github.com/stretchr/testify/assert" |
| 15 | + "github.com/stretchr/testify/require" |
| 16 | + "github.com/tinyauthapp/tinyauth/internal/model" |
| 17 | + "github.com/tinyauthapp/tinyauth/internal/repository" |
| 18 | + "github.com/tinyauthapp/tinyauth/internal/repository/memory" |
| 19 | + "github.com/tinyauthapp/tinyauth/internal/service" |
| 20 | + testutil "github.com/tinyauthapp/tinyauth/internal/test" |
| 21 | + "github.com/tinyauthapp/tinyauth/internal/utils/logger" |
| 22 | +) |
| 23 | + |
| 24 | +func TestOIDCEndSession(t *testing.T) { |
| 25 | + gin.SetMode(gin.TestMode) |
| 26 | + |
| 27 | + tests := []struct { |
| 28 | + description string |
| 29 | + method string |
| 30 | + configureRequest func(values url.Values, idToken string) |
| 31 | + provider *model.OAuthServiceConfig |
| 32 | + expectedStatus int |
| 33 | + expectedRedirect string |
| 34 | + expectedCallback string |
| 35 | + expectSessionGone bool |
| 36 | + validateRedirect func(t *testing.T, location string) |
| 37 | + }{ |
| 38 | + { |
| 39 | + description: "GET cascades a valid end-session request to the upstream provider", |
| 40 | + method: http.MethodGet, |
| 41 | + configureRequest: func(values url.Values, idToken string) { |
| 42 | + values.Set("id_token_hint", idToken) |
| 43 | + values.Set("client_id", "some-client-id") |
| 44 | + values.Set("post_logout_redirect_uri", "https://rp.example.net/logged-out") |
| 45 | + values.Set("state", "state-123") |
| 46 | + }, |
| 47 | + provider: &model.OAuthServiceConfig{ |
| 48 | + ClientID: "upstream-client", |
| 49 | + LogoutURL: "https://id.example.com/api/oidc/end-session", |
| 50 | + }, |
| 51 | + expectedStatus: http.StatusFound, |
| 52 | + expectedCallback: "https://rp.example.net/logged-out?state=state-123", |
| 53 | + expectSessionGone: true, |
| 54 | + validateRedirect: func(t *testing.T, location string) { |
| 55 | + parsed, err := url.Parse(location) |
| 56 | + require.NoError(t, err) |
| 57 | + assert.Equal(t, "id.example.com", parsed.Host) |
| 58 | + assert.Equal(t, "upstream-id-token", parsed.Query().Get("id_token_hint")) |
| 59 | + assert.Equal(t, "upstream-client", parsed.Query().Get("client_id")) |
| 60 | + assert.NotEmpty(t, parsed.Query().Get("state")) |
| 61 | + assert.NotContains(t, parsed.Query().Get("state"), "rp.example.net") |
| 62 | + }, |
| 63 | + }, |
| 64 | + { |
| 65 | + description: "POST redirects directly to a registered post-logout URI", |
| 66 | + method: http.MethodPost, |
| 67 | + configureRequest: func(values url.Values, idToken string) { |
| 68 | + values.Set("id_token_hint", idToken) |
| 69 | + values.Set("post_logout_redirect_uri", "https://rp.example.net/logged-out") |
| 70 | + values.Set("state", "state-123") |
| 71 | + }, |
| 72 | + expectedStatus: http.StatusFound, |
| 73 | + expectedRedirect: "https://rp.example.net/logged-out?state=state-123", |
| 74 | + expectSessionGone: true, |
| 75 | + }, |
| 76 | + { |
| 77 | + description: "Rejects an unregistered post-logout redirect URI", |
| 78 | + method: http.MethodGet, |
| 79 | + configureRequest: func(values url.Values, idToken string) { |
| 80 | + values.Set("id_token_hint", idToken) |
| 81 | + values.Set("post_logout_redirect_uri", "https://evil.example.com/logged-out") |
| 82 | + }, |
| 83 | + expectedStatus: http.StatusBadRequest, |
| 84 | + }, |
| 85 | + { |
| 86 | + description: "Requires confirmation when the ID token hint is missing", |
| 87 | + method: http.MethodGet, |
| 88 | + configureRequest: func(values url.Values, _ string) { |
| 89 | + values.Set("client_id", "some-client-id") |
| 90 | + values.Set("post_logout_redirect_uri", "https://rp.example.net/logged-out") |
| 91 | + }, |
| 92 | + expectedStatus: http.StatusFound, |
| 93 | + expectedRedirect: "https://tinyauth.example.com/logout", |
| 94 | + }, |
| 95 | + { |
| 96 | + description: "Requires confirmation when client ID does not match the token audience", |
| 97 | + method: http.MethodGet, |
| 98 | + configureRequest: func(values url.Values, idToken string) { |
| 99 | + values.Set("id_token_hint", idToken) |
| 100 | + values.Set("client_id", "another-client") |
| 101 | + values.Set("post_logout_redirect_uri", "https://rp.example.net/logged-out") |
| 102 | + }, |
| 103 | + expectedStatus: http.StatusFound, |
| 104 | + expectedRedirect: "https://tinyauth.example.com/logout", |
| 105 | + }, |
| 106 | + } |
| 107 | + |
| 108 | + for _, test := range tests { |
| 109 | + t.Run(test.description, func(t *testing.T) { |
| 110 | + cfg, runtime := testutil.CreateTestConfigs(t) |
| 111 | + ctx, cancel := context.WithCancel(context.Background()) |
| 112 | + t.Cleanup(cancel) |
| 113 | + |
| 114 | + log := logger.NewLogger().WithTestConfig() |
| 115 | + log.Init() |
| 116 | + store := memory.New() |
| 117 | + dg := ding.New(ctx) |
| 118 | + |
| 119 | + oidcService, err := service.NewOIDCService(service.OIDCServiceInput{ |
| 120 | + Log: log, |
| 121 | + Config: &cfg, |
| 122 | + Runtime: &runtime, |
| 123 | + Queries: store, |
| 124 | + Ding: dg, |
| 125 | + }) |
| 126 | + require.NoError(t, err) |
| 127 | + |
| 128 | + policyEngine, err := service.NewPolicyEngine(service.PolicyEngineInput{ |
| 129 | + Log: log, |
| 130 | + Config: &cfg, |
| 131 | + }) |
| 132 | + require.NoError(t, err) |
| 133 | + broker := service.NewOAuthBrokerService(service.OAuthBrokerServiceInput{ |
| 134 | + Log: log, |
| 135 | + Runtime: &runtime, |
| 136 | + Ctx: ctx, |
| 137 | + }) |
| 138 | + authService, err := service.NewAuthService(service.AuthServiceInput{ |
| 139 | + Log: log, |
| 140 | + Config: &cfg, |
| 141 | + Runtime: &runtime, |
| 142 | + Ctx: ctx, |
| 143 | + Ding: dg, |
| 144 | + Queries: store, |
| 145 | + OAuthBroker: broker, |
| 146 | + PolicyEngine: policyEngine, |
| 147 | + }) |
| 148 | + require.NoError(t, err) |
| 149 | + |
| 150 | + userContext := newOAuthUserContext("pocketid", "upstream-id-token") |
| 151 | + client, ok := oidcService.GetClient("some-client-id") |
| 152 | + require.True(t, ok) |
| 153 | + sub := oidcService.CreateSub(*userContext, client.ClientID) |
| 154 | + tokenResponse, err := oidcService.GenerateAccessToken(ctx, client, service.AuthorizeCodeEntry{ |
| 155 | + Scope: "openid", |
| 156 | + Userinfo: service.UserinfoResponse{ |
| 157 | + Sub: sub, |
| 158 | + Email: userContext.GetEmail(), |
| 159 | + PreferredUsername: userContext.GetUsername(), |
| 160 | + }, |
| 161 | + }, time.Now().Unix()) |
| 162 | + require.NoError(t, err) |
| 163 | + |
| 164 | + _, err = store.CreateSession(ctx, repository.CreateSessionParams{ |
| 165 | + UUID: "browser-session", |
| 166 | + Username: userContext.GetUsername(), |
| 167 | + Email: userContext.GetEmail(), |
| 168 | + Name: userContext.GetName(), |
| 169 | + Provider: "pocketid", |
| 170 | + Expiry: time.Now().Add(time.Hour).Unix(), |
| 171 | + CreatedAt: time.Now().Unix(), |
| 172 | + OAuthName: "Pocket ID", |
| 173 | + OAuthSub: "upstream-sub", |
| 174 | + OAuthIDToken: "upstream-id-token", |
| 175 | + }) |
| 176 | + require.NoError(t, err) |
| 177 | + |
| 178 | + if test.provider != nil { |
| 179 | + runtime.OAuthProviders = map[string]model.OAuthServiceConfig{ |
| 180 | + "pocketid": *test.provider, |
| 181 | + } |
| 182 | + } |
| 183 | + |
| 184 | + router := gin.New() |
| 185 | + router.Use(func(c *gin.Context) { |
| 186 | + c.Set("context", userContext) |
| 187 | + c.Next() |
| 188 | + }) |
| 189 | + NewOIDCController(OIDCControllerInput{ |
| 190 | + Log: log, |
| 191 | + OIDCService: oidcService, |
| 192 | + AuthService: authService, |
| 193 | + RuntimeConfig: &runtime, |
| 194 | + RouterGroup: router.Group("/api"), |
| 195 | + MainRouter: &router.RouterGroup, |
| 196 | + }) |
| 197 | + NewUserController(UserControllerInput{ |
| 198 | + Log: log, |
| 199 | + StaticConfig: &cfg, |
| 200 | + RuntimeConfig: &runtime, |
| 201 | + RouterGroup: router.Group("/api"), |
| 202 | + AuthService: authService, |
| 203 | + }) |
| 204 | + |
| 205 | + values := url.Values{} |
| 206 | + test.configureRequest(values, tokenResponse.IDToken) |
| 207 | + requestURL := "/api/oidc/end-session" |
| 208 | + var request *http.Request |
| 209 | + if test.method == http.MethodPost { |
| 210 | + request = httptest.NewRequest(test.method, requestURL, strings.NewReader(values.Encode())) |
| 211 | + request.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 212 | + } else { |
| 213 | + request = httptest.NewRequest(test.method, requestURL+"?"+values.Encode(), nil) |
| 214 | + } |
| 215 | + request.AddCookie(&http.Cookie{Name: runtime.SessionCookieName, Value: "browser-session"}) |
| 216 | + |
| 217 | + recorder := httptest.NewRecorder() |
| 218 | + router.ServeHTTP(recorder, request) |
| 219 | + |
| 220 | + assert.Equal(t, test.expectedStatus, recorder.Code) |
| 221 | + if test.expectedRedirect != "" { |
| 222 | + assert.Equal(t, test.expectedRedirect, recorder.Header().Get("Location")) |
| 223 | + } |
| 224 | + if test.validateRedirect != nil { |
| 225 | + test.validateRedirect(t, recorder.Header().Get("Location")) |
| 226 | + } |
| 227 | + if test.expectedCallback != "" { |
| 228 | + providerRedirect, err := url.Parse(recorder.Header().Get("Location")) |
| 229 | + require.NoError(t, err) |
| 230 | + callbackRecorder := httptest.NewRecorder() |
| 231 | + callbackRequest := httptest.NewRequest( |
| 232 | + http.MethodGet, |
| 233 | + "/api/user/logout/callback?state="+url.QueryEscape(providerRedirect.Query().Get("state")), |
| 234 | + nil, |
| 235 | + ) |
| 236 | + router.ServeHTTP(callbackRecorder, callbackRequest) |
| 237 | + assert.Equal(t, http.StatusFound, callbackRecorder.Code) |
| 238 | + assert.Equal(t, test.expectedCallback, callbackRecorder.Header().Get("Location")) |
| 239 | + |
| 240 | + callbackRecorder = httptest.NewRecorder() |
| 241 | + router.ServeHTTP(callbackRecorder, callbackRequest) |
| 242 | + assert.Equal(t, http.StatusFound, callbackRecorder.Code) |
| 243 | + assert.Equal(t, runtime.AppURL, callbackRecorder.Header().Get("Location")) |
| 244 | + } |
| 245 | + |
| 246 | + _, err = store.GetSession(ctx, "browser-session") |
| 247 | + if test.expectSessionGone { |
| 248 | + require.ErrorIs(t, err, repository.ErrNotFound) |
| 249 | + } else { |
| 250 | + require.NoError(t, err) |
| 251 | + } |
| 252 | + }) |
| 253 | + } |
| 254 | +} |
0 commit comments