Skip to content

Commit

Permalink
fix: add __HOST prefix to cookies (#175)
Browse files Browse the repository at this point in the history
  • Loading branch information
stonith404 authored Jan 24, 2025
1 parent ef1aeb7 commit 164ce6a
Show file tree
Hide file tree
Showing 21 changed files with 80 additions and 46 deletions.
12 changes: 10 additions & 2 deletions backend/internal/controller/user_controller.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package controller

import (
"github.com/stonith404/pocket-id/backend/internal/utils/cookie"
"net/http"
"strconv"
"time"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -184,7 +186,10 @@ func (uc *UserController) exchangeOneTimeAccessTokenHandler(c *gin.Context) {
return
}

utils.AddAccessTokenCookie(c, uc.appConfigService.DbConfig.SessionDuration.Value, token)
sessionDurationInMinutesParsed, _ := strconv.Atoi(uc.appConfigService.DbConfig.SessionDuration.Value)
maxAge := sessionDurationInMinutesParsed * 60
cookie.AddAccessTokenCookie(c, maxAge, token)

c.JSON(http.StatusOK, userDto)
}

Expand All @@ -201,7 +206,10 @@ func (uc *UserController) getSetupAccessTokenHandler(c *gin.Context) {
return
}

utils.AddAccessTokenCookie(c, uc.appConfigService.DbConfig.SessionDuration.Value, token)
sessionDurationInMinutesParsed, _ := strconv.Atoi(uc.appConfigService.DbConfig.SessionDuration.Value)
maxAge := sessionDurationInMinutesParsed * 60
cookie.AddAccessTokenCookie(c, maxAge, token)

c.JSON(http.StatusOK, userDto)
}

Expand Down
18 changes: 11 additions & 7 deletions backend/internal/controller/webauthn_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import (
"github.com/stonith404/pocket-id/backend/internal/common"
"github.com/stonith404/pocket-id/backend/internal/dto"
"github.com/stonith404/pocket-id/backend/internal/middleware"
"github.com/stonith404/pocket-id/backend/internal/utils"
"github.com/stonith404/pocket-id/backend/internal/utils/cookie"
"net/http"
"strconv"
"time"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -42,12 +43,12 @@ func (wc *WebauthnController) beginRegistrationHandler(c *gin.Context) {
return
}

c.SetCookie("session_id", options.SessionID, int(options.Timeout.Seconds()), "/", "", true, true)
cookie.AddSessionIdCookie(c, int(options.Timeout.Seconds()), options.SessionID)
c.JSON(http.StatusOK, options.Response)
}

func (wc *WebauthnController) verifyRegistrationHandler(c *gin.Context) {
sessionID, err := c.Cookie("session_id")
sessionID, err := c.Cookie(cookie.SessionIdCookieName)
if err != nil {
c.Error(&common.MissingSessionIdError{})
return
Expand Down Expand Up @@ -76,12 +77,12 @@ func (wc *WebauthnController) beginLoginHandler(c *gin.Context) {
return
}

c.SetCookie("session_id", options.SessionID, int(options.Timeout.Seconds()), "/", "", true, true)
cookie.AddSessionIdCookie(c, int(options.Timeout.Seconds()), options.SessionID)
c.JSON(http.StatusOK, options.Response)
}

func (wc *WebauthnController) verifyLoginHandler(c *gin.Context) {
sessionID, err := c.Cookie("session_id")
sessionID, err := c.Cookie(cookie.SessionIdCookieName)
if err != nil {
c.Error(&common.MissingSessionIdError{})
return
Expand All @@ -105,7 +106,10 @@ func (wc *WebauthnController) verifyLoginHandler(c *gin.Context) {
return
}

utils.AddAccessTokenCookie(c, wc.appConfigService.DbConfig.SessionDuration.Value, token)
sessionDurationInMinutesParsed, _ := strconv.Atoi(wc.appConfigService.DbConfig.SessionDuration.Value)
maxAge := sessionDurationInMinutesParsed * 60
cookie.AddAccessTokenCookie(c, maxAge, token)

c.JSON(http.StatusOK, userDto)
}

Expand Down Expand Up @@ -165,6 +169,6 @@ func (wc *WebauthnController) updateCredentialHandler(c *gin.Context) {
}

func (wc *WebauthnController) logoutHandler(c *gin.Context) {
utils.AddAccessTokenCookie(c, "0", "")
cookie.AddAccessTokenCookie(c, 0, "")
c.Status(http.StatusNoContent)
}
3 changes: 2 additions & 1 deletion backend/internal/middleware/jwt_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/stonith404/pocket-id/backend/internal/common"
"github.com/stonith404/pocket-id/backend/internal/service"
"github.com/stonith404/pocket-id/backend/internal/utils/cookie"
"strings"
)

Expand All @@ -19,7 +20,7 @@ func NewJwtAuthMiddleware(jwtService *service.JwtService, ignoreUnauthenticated
func (m *JwtAuthMiddleware) Add(adminOnly bool) gin.HandlerFunc {
return func(c *gin.Context) {
// Extract the token from the cookie or the Authorization header
token, err := c.Cookie("access_token")
token, err := c.Cookie(cookie.AccessTokenCookieName)
if err != nil {
authorizationHeaderSplitted := strings.Split(c.GetHeader("Authorization"), " ")
if len(authorizationHeaderSplitted) == 2 {
Expand Down
13 changes: 13 additions & 0 deletions backend/internal/utils/cookie/add_cookie.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package cookie

import (
"github.com/gin-gonic/gin"
)

func AddAccessTokenCookie(c *gin.Context, maxAgeInSeconds int, token string) {
c.SetCookie(AccessTokenCookieName, token, maxAgeInSeconds, "/", "", true, true)
}

func AddSessionIdCookie(c *gin.Context, maxAgeInSeconds int, sessionID string) {
c.SetCookie(SessionIdCookieName, sessionID, maxAgeInSeconds, "/", "", true, true)
}
16 changes: 16 additions & 0 deletions backend/internal/utils/cookie/cookie_names.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package cookie

import (
"github.com/stonith404/pocket-id/backend/internal/common"
"strings"
)

var AccessTokenCookieName = "__Host-access_token"
var SessionIdCookieName = "__Host-session"

func init() {
if strings.HasPrefix(common.EnvConfig.AppURL, "http://") {
AccessTokenCookieName = "access_token"
SessionIdCookieName = "session"
}
}
12 changes: 0 additions & 12 deletions backend/internal/utils/cookie_util.go

This file was deleted.

3 changes: 2 additions & 1 deletion frontend/src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { env } from '$env/dynamic/private';
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import type { Handle, HandleServerError } from '@sveltejs/kit';
import { AxiosError } from 'axios';
import jwt from 'jsonwebtoken';
Expand All @@ -9,7 +10,7 @@ import jwt from 'jsonwebtoken';
process.env.INTERNAL_BACKEND_URL = env.INTERNAL_BACKEND_URL ?? 'http://localhost:8080';

export const handle: Handle = async ({ event, resolve }) => {
const accessToken = event.cookies.get('access_token');
const accessToken = event.cookies.get(ACCESS_TOKEN_COOKIE_NAME);

let isSignedIn: boolean = false;
let isAdmin: boolean = false;
Expand Down
2 changes: 2 additions & 0 deletions frontend/src/lib/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const HTTPS_ENABLED = process.env.PUBLIC_APP_URL?.startsWith('https://') ?? false;
export const ACCESS_TOKEN_COOKIE_NAME = HTTPS_ENABLED ? '__Host-access_token' : 'access_token';
5 changes: 3 additions & 2 deletions frontend/src/routes/+layout.server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import AppConfigService from '$lib/services/app-config-service';
import UserService from '$lib/services/user-service';
import type { LayoutServerLoad } from './$types';

export const load: LayoutServerLoad = async ({ cookies }) => {
const userService = new UserService(cookies.get('access_token'));
const appConfigService = new AppConfigService(cookies.get('access_token'));
const userService = new UserService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const appConfigService = new AppConfigService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));

const user = await userService
.getCurrent()
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/routes/authorize/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import OidcService from '$lib/services/oidc-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ url, cookies }) => {
const clientId = url.searchParams.get('client_id');
const oidcService = new OidcService(cookies.get('access_token'));
const oidcService = new OidcService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));

const client = await oidcService.getClient(clientId!);

Expand Down
5 changes: 3 additions & 2 deletions frontend/src/routes/settings/account/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import UserService from '$lib/services/user-service';
import WebAuthnService from '$lib/services/webauthn-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies }) => {
const webauthnService = new WebAuthnService(cookies.get('access_token'));
const userService = new UserService(cookies.get('access_token'));
const webauthnService = new WebAuthnService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const userService = new UserService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const account = await userService.getCurrent();
const passkeys = await webauthnService.listCredentials();
return {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import AppConfigService from '$lib/services/app-config-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies }) => {
const appConfigService = new AppConfigService(cookies.get('access_token'));
const appConfigService = new AppConfigService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const appConfig = await appConfigService.list(true);
return { appConfig };
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import OIDCService from '$lib/services/oidc-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies }) => {
const oidcService = new OIDCService(cookies.get('access_token'));
const oidcService = new OIDCService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const clients = await oidcService.listClients();
return clients;
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import OidcService from '$lib/services/oidc-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ params, cookies }) => {
const oidcService = new OidcService(cookies.get('access_token'));
const oidcService = new OidcService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
return await oidcService.getClient(params.id);
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import UserGroupService from '$lib/services/user-group-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies }) => {
const userGroupService = new UserGroupService(cookies.get('access_token'));
const userGroupService = new UserGroupService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const userGroups = await userGroupService.list();
return userGroups;
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import UserGroupService from '$lib/services/user-group-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ params, cookies }) => {
const userGroupService = new UserGroupService(cookies.get('access_token'));
const userGroupService = new UserGroupService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const userGroup = await userGroupService.get(params.id);

return { userGroup };
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/routes/settings/admin/users/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import UserService from '$lib/services/user-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies }) => {
const userService = new UserService(cookies.get('access_token'));
const userService = new UserService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const users = await userService.list();
return users;
};
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import UserService from '$lib/services/user-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ params, cookies }) => {
const userService = new UserService(cookies.get('access_token'));
const userService = new UserService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const user = await userService.get(params.id);
return user;
};
3 changes: 2 additions & 1 deletion frontend/src/routes/settings/audit-log/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { ACCESS_TOKEN_COOKIE_NAME } from '$lib/constants';
import AuditLogService from '$lib/services/audit-log-service';
import type { PageServerLoad } from './$types';

export const load: PageServerLoad = async ({ cookies }) => {
const auditLogService = new AuditLogService(cookies.get('access_token'));
const auditLogService = new AuditLogService(cookies.get(ACCESS_TOKEN_COOKIE_NAME));
const auditLogs = await auditLogService.list({
sort: {
column: 'createdAt',
Expand Down
5 changes: 0 additions & 5 deletions reverse-proxy/Caddyfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,4 @@
reverse_proxy /api/* http://localhost:{$BACKEND_PORT:8080}
reverse_proxy /.well-known/* http://localhost:{$BACKEND_PORT:8080}
reverse_proxy /* http://localhost:{$PORT:3000}

log {
output file /var/log/caddy/access.log
level WARN
}
}
5 changes: 0 additions & 5 deletions reverse-proxy/Caddyfile.trust-proxy
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,4 @@
reverse_proxy /* http://localhost:{$PORT:3000} {
trusted_proxies 0.0.0.0/0
}

log {
output file /var/log/caddy/access.log
level WARN
}
}

0 comments on commit 164ce6a

Please sign in to comment.