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

WIP: Refresh session param for whoami endpoint, PLATFORM-6607 #48

Merged
merged 18 commits into from
Jan 19, 2022
Merged
Show file tree
Hide file tree
Changes from 13 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
10 changes: 10 additions & 0 deletions driver/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ const (
ViperKeySessionPath = "session.cookie.path"
ViperKeySessionPersistentCookie = "session.cookie.persistent"
ViperKeySessionWhoAmIAAL = "session.whoami.required_aal"
ViperKeySessionWhoAmIRefresh = "session.whoami.refresh"
ViperKeySessionRefreshTimeWindow = "session.refresh_time_window"
ViperKeyCookieSameSite = "cookies.same_site"
ViperKeyCookieDomain = "cookies.domain"
ViperKeyCookiePath = "cookies.path"
Expand Down Expand Up @@ -1029,6 +1031,14 @@ func (p *Config) SessionWhoAmIAAL() string {
return p.p.String(ViperKeySessionWhoAmIAAL)
}

func (p *Config) SessionWhoAmIRefresh() bool {
return p.p.Bool(ViperKeySessionWhoAmIRefresh)
}

func (p *Config) SessionRefreshTimeWindow() time.Duration {
return p.p.DurationF(ViperKeySessionRefreshTimeWindow, p.SessionLifespan())
}

func (p *Config) SelfServiceSettingsRequiredAAL() string {
return p.p.String(ViperKeySelfServiceSettingsRequiredAAL)
}
Expand Down
18 changes: 18 additions & 0 deletions embedx/config.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -2115,6 +2115,12 @@
"properties": {
"required_aal": {
"$ref": "#/definitions/featureRequiredAal"
},
"refresh": {
abador marked this conversation as resolved.
Show resolved Hide resolved
"title": "Allow session refresh from whoami endpoint",
"description": "If set to true will will allow to refresh session lifespan if ?refresh=true is present",
harnash marked this conversation as resolved.
Show resolved Hide resolved
"type": "boolean",
"default": false
}
},
"additionalProperties": false
Expand Down Expand Up @@ -2168,6 +2174,18 @@
}
},
"additionalProperties": false
},
"refresh_time_window": {
"title": "Session refresh time window",
"description": "Time window when session can be refreshed to avoid excess refreshes. It is calculated as duration from the session expiration time.",
"type": "string",
"pattern": "^[0-9]+(ns|us|ms|s|m|h)$",
"default": "24h",
"examples": [
"1h",
"1m",
"1s"
]
}
}
},
Expand Down
5 changes: 4 additions & 1 deletion internal/testhelpers/handler_mock.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,8 @@ func NewNoRedirectClientWithCookies(t *testing.T) *http.Client {
}
}

func MockHydrateCookieClient(t *testing.T, c *http.Client, u string) {
func MockHydrateCookieClient(t *testing.T, c *http.Client, u string) *http.Cookie {
var sessionCookie *http.Cookie
res, err := c.Get(u)
require.NoError(t, err)
defer res.Body.Close()
Expand All @@ -102,9 +103,11 @@ func MockHydrateCookieClient(t *testing.T, c *http.Client, u string) {
for _, c := range res.Cookies() {
if c.Name == config.DefaultSessionCookieName {
found = true
sessionCookie = c
}
}
require.True(t, found)
return sessionCookie
}

func MockSessionCreateHandlerWithIdentity(t *testing.T, reg mockDeps, i *identity.Identity) (httprouter.Handle, *session.Session) {
Expand Down
115 changes: 113 additions & 2 deletions session/handler.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package session

import (
"fmt"
"net/http"
"time"

Expand Down Expand Up @@ -48,6 +49,8 @@ func NewHandler(
const (
RouteCollection = "/sessions"
RouteWhoami = RouteCollection + "/whoami"
RouteSessionRefresh = RouteCollection + "/refresh"
RouteSessionRefreshId = RouteSessionRefresh + "/:id"
RouteIdentity = "/identities"
RouteIdentityManagement = RouteIdentity + "/:id/sessions"
RouteIdentitySession = RouteIdentity + "/:id/session"
Expand All @@ -60,6 +63,8 @@ func (h *Handler) RegisterAdminRoutes(admin *x.RouterAdmin) {
admin.Handle(m, RouteWhoami, x.RedirectToPublicRoute(h.r))
}
admin.DELETE(RouteIdentityManagement, h.deleteIdentitySessions)
admin.PATCH(RouteSessionRefresh, h.adminCurrentSessionRefresh)
admin.PATCH(RouteSessionRefreshId, h.adminSessionRefresh)
admin.GET(RouteIdentitySession, h.session)
}

Expand Down Expand Up @@ -104,6 +109,12 @@ type toSession struct {
// Returns a session object in the body or 401 if the credentials are invalid or no credentials were sent.
// Additionally when the request it successful it adds the user ID to the 'X-Kratos-Authenticated-Identity-Id' header in the response.
//
// It is also possible to refresh the session lifespan of a current session by adding a `refresh=true` param to the request url.
// By default session refresh on this endpoint is disabled.
// Session refresh can be enabled only after setting `session.whoami.refresh` to true in the config.
abador marked this conversation as resolved.
Show resolved Hide resolved
// After enabling this option any refresh request will set the session life equal to `session.lifespan`.
// If you want to refresh the session only some time before session expiration you can set a proper value for `session.refresh_time_window`
abador marked this conversation as resolved.
Show resolved Hide resolved
//
// If you call this endpoint from a server-side application, you must forward the HTTP Cookie Header to this endpoint:
//
// ```js
Expand Down Expand Up @@ -135,6 +146,7 @@ type toSession struct {
// - AJAX calls. Remember to send credentials and set up CORS correctly!
// - Reverse proxies and API Gateways
// - Server-side calls - use the `X-Session-Token` header!
// - Session refresh
//
// This endpoint authenticates users by checking
//
Expand All @@ -159,7 +171,7 @@ type toSession struct {
// 401: jsonError
// 403: jsonError
// 500: jsonError
func (h *Handler) whoami(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
func (h *Handler) whoami(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {
s, err := h.r.SessionManager().FetchFromRequest(r.Context(), r)
if err != nil {
h.r.Audit().WithRequest(r).WithError(err).Info("No valid session cookie found.")
Expand All @@ -168,7 +180,8 @@ func (h *Handler) whoami(w http.ResponseWriter, r *http.Request, ps httprouter.P
}

var aalErr *ErrAALNotSatisfied
if err := h.r.SessionManager().DoesSessionSatisfy(r, s, h.r.Config(r.Context()).SessionWhoAmIAAL()); errors.As(err, &aalErr) {
c := h.r.Config(r.Context())
if err := h.r.SessionManager().DoesSessionSatisfy(r, s, c.SessionWhoAmIAAL()); errors.As(err, &aalErr) {
h.r.Audit().WithRequest(r).WithError(err).Info("Session was found but AAL is not satisfied for calling this endpoint.")
h.r.Writer().WriteError(w, r, err)
return
Expand All @@ -178,6 +191,17 @@ func (h *Handler) whoami(w http.ResponseWriter, r *http.Request, ps httprouter.P
return
}

// Refresh session if param was true
refresh := r.URL.Query().Get("refresh")
abador marked this conversation as resolved.
Show resolved Hide resolved
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add this to the OpenAPI spec :)

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fix in b69eb97

if c.SessionWhoAmIRefresh() && refresh == "true" && s.CanBeRefreshed(c) {
abador marked this conversation as resolved.
Show resolved Hide resolved
abador marked this conversation as resolved.
Show resolved Hide resolved
s = s.Refresh(c)
if err := h.r.SessionPersister().UpsertSession(r.Context(), s); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
h.r.SessionManager().IssueCookie(r.Context(), w, r, s)
}

// s.Devices = nil
s.Identity = s.Identity.CopyWithoutCredentials()

Expand Down Expand Up @@ -314,6 +338,93 @@ func (h *Handler) session(w http.ResponseWriter, r *http.Request, ps httprouter.
h.r.Writer().Write(w, r, &AdminIdentitySessionResponse{Session: s, Token: s.Token, Identity: i})
}

// swagger:parameters adminSessionRefresh
// nolint:deadcode,unused
type adminSessionRefresh struct {
// ID is the session's ID.
//
// required: true
// in: path
ID string `json:"id"`
}

// swagger:route PATCH /sessions/refresh/{id} v0alpha2 adminSessionRefresh
//
// Calling this endpoint refreshes a given session.
// If `session.refresh_time_window` is set it will only refresh the session after this time has passed.
abador marked this conversation as resolved.
Show resolved Hide resolved
//
// This endpoint is useful for:
//
// - Session refresh
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 200: session
// 404: jsonError
// 500: jsonError
func (h *Handler) adminSessionRefresh(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
iID, err := uuid.FromString(ps.ByName("id"))
if err != nil {
h.r.Writer().WriteError(w, r, herodot.ErrBadRequest.WithError(err.Error()).WithDebug("could not parse UUID"))
return
}
s, err := h.r.SessionPersister().GetSession(r.Context(), iID)
if err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
c := h.r.Config(r.Context())
if s.CanBeRefreshed(c) {
if err := h.r.SessionPersister().UpsertSession(r.Context(), s.Refresh(c)); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
}

h.r.Writer().Write(w, r, s)
}

// swagger:route GET /sessions/refresh v0alpha2 adminIdentitySession
//
// Calling this endpoint refreshes a given session.
// If `session.refresh_time_window` is set it will only refresh the session after this time has passed.
abador marked this conversation as resolved.
Show resolved Hide resolved
//
// This endpoint is useful for:
//
// - Session refresh
//
// Schemes: http, https
//
// Security:
// oryAccessToken:
//
// Responses:
// 200: successfulAdminIdentitySession
// 404: jsonError
// 500: jsonError
func (h *Handler) adminCurrentSessionRefresh(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
s, err := h.r.SessionManager().FetchFromRequest(r.Context(), r)
fmt.Printf("\n %+v \n", r.Cookies())
if err != nil {
h.r.Audit().WithRequest(r).WithError(err).Info("No valid session cookie found.")
h.r.Writer().WriteError(w, r, herodot.ErrUnauthorized.WithWrap(err).WithReasonf("No valid session cookie found."))
return
}
c := h.r.Config(r.Context())
if s.CanBeRefreshed(c) {
if err := h.r.SessionPersister().UpsertSession(r.Context(), s.Refresh(c)); err != nil {
h.r.Writer().WriteError(w, r, err)
return
}
}

h.r.Writer().Write(w, r, s)
}

// fandom-end

func (h *Handler) IsAuthenticated(wrap httprouter.Handle, onUnauthenticated httprouter.Handle) httprouter.Handle {
Expand Down
Loading