Skip to content

Commit

Permalink
Samesite fix (#8390)
Browse files Browse the repository at this point in the history
* Fix for migratoin

* Fix for COOKIE_MODE

- Update to match master

* Fix default value in config template

- samesite = false, not none

* Remove conflicting migration

- Should not have back-ported this from master branch
- Will not cause any serious issues, was a "nice to have" data migration
  • Loading branch information
SchrodingersGat authored Oct 28, 2024
1 parent 343f63c commit de2edc4
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 49 deletions.
32 changes: 23 additions & 9 deletions src/backend/InvenTree/InvenTree/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -1061,26 +1061,40 @@
sys.exit(-1)

COOKIE_MODE = (
str(get_setting('INVENTREE_COOKIE_SAMESITE', 'cookie.samesite', 'None'))
str(get_setting('INVENTREE_COOKIE_SAMESITE', 'cookie.samesite', 'False'))
.lower()
.strip()
)

valid_cookie_modes = {'lax': 'Lax', 'strict': 'Strict', 'none': 'None', 'null': 'None'}
# Valid modes (as per the django settings documentation)
valid_cookie_modes = ['lax', 'strict', 'none']

if COOKIE_MODE not in valid_cookie_modes.keys():
logger.error('Invalid cookie samesite mode: %s', COOKIE_MODE)
sys.exit(-1)

COOKIE_MODE = valid_cookie_modes.get(COOKIE_MODE.lower(), 'None')
if not DEBUG and not TESTING and COOKIE_MODE in valid_cookie_modes:
# Set the cookie mode (in production mode only)
COOKIE_MODE = COOKIE_MODE.capitalize()
else:
# Default to False, as per the Django settings
COOKIE_MODE = False

# Additional CSRF settings
CSRF_HEADER_NAME = 'HTTP_X_CSRFTOKEN'
CSRF_COOKIE_NAME = 'csrftoken'

CSRF_COOKIE_SAMESITE = COOKIE_MODE
SESSION_COOKIE_SAMESITE = COOKIE_MODE
SESSION_COOKIE_SECURE = get_boolean_setting(
'INVENTREE_SESSION_COOKIE_SECURE', 'cookie.secure', False

"""Set the SESSION_COOKIE_SECURE value based on the following rules:
- False if the server is running in DEBUG mode
- True if samesite cookie setting is set to 'None'
- Otherwise, use the value specified in the configuration file (or env var)
"""
SESSION_COOKIE_SECURE = (
False
if DEBUG
else (
SESSION_COOKIE_SAMESITE == 'None'
or get_boolean_setting('INVENTREE_SESSION_COOKIE_SECURE', 'cookie.secure', True)
)
)

USE_X_FORWARDED_HOST = get_boolean_setting(
Expand Down
39 changes: 0 additions & 39 deletions src/backend/InvenTree/common/migrations/0031_auto_20241026_0024.py

This file was deleted.

2 changes: 1 addition & 1 deletion src/backend/InvenTree/config_template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ use_x_forwarded_port: false
# Cookie settings
cookie:
secure: false
samesite: none
samesite: false

# Cross Origin Resource Sharing (CORS) settings (see https://github.com/adamchainz/django-cors-headers)
cors:
Expand Down

0 comments on commit de2edc4

Please sign in to comment.