@@ -29,6 +29,19 @@ def test_ai_prompt_rejects_requests_without_api_key(client, monkeypatch):
2929 assert "API key required" in response .json ["message" ]
3030
3131
32+ def test_ai_prompt_rejects_loopback_requests_without_api_key (client , monkeypatch ):
33+ monkeypatch .setenv ("POLICYENGINE_API_AI_ANALYSIS_API_KEY" , "secret-key" )
34+
35+ response = client .post (
36+ "/us/ai-prompts/simulation_analysis" ,
37+ json = valid_input_us ,
38+ environ_base = {"REMOTE_ADDR" : "127.0.0.1" },
39+ )
40+
41+ assert response .status_code == 401
42+ assert "API key required" in response .json ["message" ]
43+
44+
3245def test_ai_prompt_allows_requests_with_api_key (client , monkeypatch ):
3346 monkeypatch .setenv ("POLICYENGINE_API_AI_ANALYSIS_API_KEY" , "secret-key" )
3447
@@ -65,6 +78,23 @@ def test_tracer_analysis_rejects_requests_without_api_key(client, monkeypatch):
6578 assert "API key required" in response .json ["message" ]
6679
6780
81+ def test_requests_fail_closed_when_api_key_is_not_configured (client , monkeypatch ):
82+ monkeypatch .delenv ("POLICYENGINE_API_AI_ANALYSIS_API_KEY" , raising = False )
83+
84+ response = client .post (
85+ "/us/tracer-analysis" ,
86+ json = {
87+ "household_id" : 1500 ,
88+ "policy_id" : 2 ,
89+ "variable" : "disposable_income" ,
90+ },
91+ environ_base = {"REMOTE_ADDR" : "203.0.113.10" },
92+ )
93+
94+ assert response .status_code == 401
95+ assert "not configured" in response .json ["message" ]
96+
97+
6898def test_tracer_analysis_allows_requests_with_api_key (client , monkeypatch ):
6999 monkeypatch .setenv ("POLICYENGINE_API_AI_ANALYSIS_API_KEY" , "secret-key" )
70100
@@ -85,6 +115,4 @@ def test_tracer_analysis_allows_requests_with_api_key(client, monkeypatch):
85115
86116 assert response .status_code == 200
87117 assert response .json ["result" ] == "Existing analysis"
88- mock_execute_analysis .assert_called_once_with (
89- "us" , 1500 , 2 , "disposable_income"
90- )
118+ mock_execute_analysis .assert_called_once_with ("us" , 1500 , 2 , "disposable_income" )
0 commit comments