diff --git a/bookshelf/main.py b/bookshelf/main.py index 789bec2e..0dad688f 100644 --- a/bookshelf/main.py +++ b/bookshelf/main.py @@ -13,6 +13,8 @@ # limitations under the License. import logging +import os +import secrets import firestore from flask import current_app, flash, Flask, Markup, redirect, render_template @@ -45,8 +47,14 @@ def upload_image_file(img): app = Flask(__name__) +# Flask signs session cookies with SECRET_KEY, so it must never be a value +# published in source code. Set the FLASK_SECRET_KEY environment variable to +# a long random value shared by every instance of the app. If it isn't set, +# a random key is generated for this process only: sessions (used here for +# flashed messages) then don't survive restarts and aren't shared between +# instances. app.config.update( - SECRET_KEY='secret', + SECRET_KEY=os.environ.get('FLASK_SECRET_KEY') or secrets.token_hex(32), MAX_CONTENT_LENGTH=8 * 1024 * 1024, ALLOWED_EXTENSIONS=set(['png', 'jpg', 'jpeg', 'gif']) ) diff --git a/optional-kubernetes-engine/Makefile b/optional-kubernetes-engine/Makefile index 4c1cbf3e..df88e57a 100644 --- a/optional-kubernetes-engine/Makefile +++ b/optional-kubernetes-engine/Makefile @@ -28,6 +28,11 @@ template: sed -i ".tmpl" "s/\[GCLOUD_PROJECT\]/$(GCLOUD_PROJECT)/g" bookshelf-frontend.yaml sed -i ".tmpl" "s/\[GCLOUD_PROJECT\]/$(GCLOUD_PROJECT)/g" bookshelf-worker.yaml +.PHONY: create-secret +create-secret: + kubectl create secret generic bookshelf-secrets \ + --from-literal=flask-secret-key="$$(python3 -c 'import secrets; print(secrets.token_hex(32))')" + .PHONY: create-service create-service: kubectl create -f bookshelf-service.yaml @@ -41,7 +46,7 @@ deploy-worker: push template kubectl create -f bookshelf-worker.yaml .PHONY: deploy -deploy: deploy-frontend deploy-worker create-service +deploy: create-secret deploy-frontend deploy-worker create-service .PHONY: delete delete: diff --git a/optional-kubernetes-engine/README.md b/optional-kubernetes-engine/README.md index 9acb98b4..57cfa4a5 100644 --- a/optional-kubernetes-engine/README.md +++ b/optional-kubernetes-engine/README.md @@ -47,6 +47,21 @@ Alternatively, you can use make: Modify config.py and enter your Cloud Project ID into the `PROJECT_ID` and `CLOUD_STORAGE_BUCKET` field. The remaining configuration values are only needed if you wish to use a different database or if you wish to enable log-in via oauth2, which requires a domain name. +## Create the session secret key + +The application signs session cookies with a secret key that it reads from the `FLASK_SECRET_KEY` environment variable. The key is not stored in the source code, and the application does not start without it. Generate a random key and store it in a Kubernetes Secret, which the frontend and worker manifests reference: + + kubectl create secret generic bookshelf-secrets \ + --from-literal=flask-secret-key="$(python3 -c 'import secrets; print(secrets.token_hex(32))')" + +Alternatively, you can use make: + + make create-secret + +To run the application locally, set the variable in your shell first: + + export FLASK_SECRET_KEY="$(python3 -c 'import secrets; print(secrets.token_hex(32))')" + ## Build the bookshelf container Before the application can be deployed to Kubernetes Engine, you will need build and push the image to [Google Container Registry](https://cloud.google.com/container-registry/). diff --git a/optional-kubernetes-engine/bookshelf-frontend.yaml b/optional-kubernetes-engine/bookshelf-frontend.yaml index 5db2d638..b999502d 100644 --- a/optional-kubernetes-engine/bookshelf-frontend.yaml +++ b/optional-kubernetes-engine/bookshelf-frontend.yaml @@ -51,6 +51,14 @@ spec: env: - name: PROCESSES value: bookshelf + # Flask signs session cookies with this key. It is read from a + # Kubernetes Secret so that it is never stored in source code. See the + # README for how to create the secret. + - name: FLASK_SECRET_KEY + valueFrom: + secretKeyRef: + name: bookshelf-secrets + key: flask-secret-key # The bookshelf process listens on port 8080 for web traffic by default. ports: - name: http-server diff --git a/optional-kubernetes-engine/bookshelf-worker.yaml b/optional-kubernetes-engine/bookshelf-worker.yaml index 979437b6..e7547884 100644 --- a/optional-kubernetes-engine/bookshelf-worker.yaml +++ b/optional-kubernetes-engine/bookshelf-worker.yaml @@ -51,3 +51,11 @@ spec: env: - name: PROCESSES value: worker + # The worker loads the same config module as the frontend, which + # requires this key. It is read from a Kubernetes Secret so that it is + # never stored in source code. See the README for how to create it. + - name: FLASK_SECRET_KEY + valueFrom: + secretKeyRef: + name: bookshelf-secrets + key: flask-secret-key diff --git a/optional-kubernetes-engine/config.py b/optional-kubernetes-engine/config.py index 7da9b4cc..e135e916 100644 --- a/optional-kubernetes-engine/config.py +++ b/optional-kubernetes-engine/config.py @@ -20,8 +20,11 @@ import os -# The secret key is used by Flask to encrypt session cookies. -SECRET_KEY = 'secret' +# The secret key is used by Flask to sign session cookies. It must be a strong +# random value supplied through the FLASK_SECRET_KEY environment variable. +# There is intentionally no default: a hardcoded or predictable key lets +# anyone forge session cookies. +SECRET_KEY = os.environ['FLASK_SECRET_KEY'] # There are three different ways to store the data in the application. # You can choose 'datastore', 'cloudsql', or 'mongodb'. Be sure to diff --git a/optional-kubernetes-engine/conftest.py b/optional-kubernetes-engine/conftest.py new file mode 100644 index 00000000..a2cd7877 --- /dev/null +++ b/optional-kubernetes-engine/conftest.py @@ -0,0 +1,23 @@ +# Copyright 2026 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Test configuration that must run before tests/conftest.py imports config.""" + +import binascii +import os + +# config.py requires FLASK_SECRET_KEY and has no default. Use a random key for +# each test run unless the caller already provided one. +os.environ.setdefault( + 'FLASK_SECRET_KEY', binascii.hexlify(os.urandom(32)).decode('ascii'))