Skip to content

Commit d2af763

Browse files
committed
add ask token to bypass csrf and pow if needed
1 parent 52ba787 commit d2af763

File tree

4 files changed

+22
-3
lines changed

4 files changed

+22
-3
lines changed

.github/workflows/deploy.yaml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,12 @@ jobs:
3434
- name: Deploy
3535
uses: DefangLabs/[email protected]
3636
with:
37-
config-env-vars: OPENAI_API_KEY SECRET_KEY SEGMENT_WRITE_KEY
37+
config-env-vars: ASK_TOKEN OPENAI_API_KEY SECRET_KEY SEGMENT_WRITE_KEY
3838
mode: production
3939
provider: aws
4040

4141
env:
42+
ASK_TOKEN: ${{ secrets.ASK_TOKEN }}
4243
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
4344
SECRET_KEY: ${{ secrets.SECRET_KEY }}
4445
SEGMENT_WRITE_KEY: ${{ secrets.SEGMENT_WRITE_KEY }}

app/app.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,26 @@ def validate_pow(nonce, data, difficulty):
3131
def index():
3232
return render_template('index.html', debug=os.getenv('DEBUG'))
3333

34+
@app.before_request
35+
def exempt_csrf_for_ask_token():
36+
if request.endpoint == 'ask':
37+
ask_token = request.headers.get('Ask-Token')
38+
# If ask token matches the expected value, bypass CSRF protection
39+
if ask_token and ask_token == os.getenv('ASK_TOKEN'):
40+
print(f"CSRF protection exempted for endpoint '{request.endpoint}' due to valid Ask-Token")
41+
csrf.exempt(app.view_functions['ask'])
42+
else:
43+
print(f"CSRF protection enabled for endpoint: {request.endpoint}")
44+
3445
@app.route('/ask', methods=['POST'])
3546
def ask():
36-
if not validate_pow(request.headers.get('X-Nonce'), request.get_data(), 0x50000):
37-
return jsonify({"error": "Invalid proof of work"}), 400
47+
ask_token = request.headers.get('Ask-Token')
48+
# If ask token matches the expected value, bypass PoW validation
49+
if ask_token != os.getenv('ASK_TOKEN'):
50+
if not validate_pow(request.headers.get('X-Nonce'), request.get_data(), 0x50000):
51+
return jsonify({"error": "Invalid Proof of Work"}), 400
52+
else:
53+
print(f"Proof of Work validation skipped for endpoint: {request.endpoint} due to valid Ask-Token")
3854

3955
data = request.get_json()
4056
query = data.get('query')

compose.dev.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ services:
99
protocol: tcp
1010
mode: ingress
1111
environment:
12+
ASK_TOKEN: asktoken
1213
FLASK_APP: app.py
1314
SECRET_KEY: supersecret
1415
SEGMENT_WRITE_KEY: ${SEGMENT_WRITE_KEY} # Set your Segment write key here or in the .env file

compose.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ services:
1212
protocol: tcp
1313
mode: ingress
1414
environment:
15+
ASK_TOKEN:
1516
FLASK_APP: app.py
1617
DEBUG: 0
1718
SECRET_KEY:

0 commit comments

Comments
 (0)