test: adapt HTTP checks to persistent Bearer sessions
This commit is contained in:
@@ -1,5 +1,5 @@
|
|||||||
PYTHON ?= python3
|
PYTHON ?= python3
|
||||||
BASE_URL ?= http://localhost:8080
|
BASE_URL ?= http://127.0.0.1:8082
|
||||||
CA_FILE ?=
|
CA_FILE ?=
|
||||||
ACTION_SCRIPT ?=
|
ACTION_SCRIPT ?=
|
||||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||||
|
|||||||
+2
-5
@@ -35,10 +35,7 @@ services:
|
|||||||
memswap_limit: 128m
|
memswap_limit: 128m
|
||||||
migrate:
|
migrate:
|
||||||
image: ${API_IMAGE:-mtusi-messenger:lab2}
|
image: ${API_IMAGE:-mtusi-messenger:lab2}
|
||||||
build:
|
pull_policy: never
|
||||||
context: .
|
|
||||||
args:
|
|
||||||
VCS_REF: ${VCS_REF:-unknown}
|
|
||||||
command: [python, -m, src.migrate]
|
command: [python, -m, src.migrate]
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL_FILE: /run/secrets/database_url
|
DATABASE_URL_FILE: /run/secrets/database_url
|
||||||
@@ -72,7 +69,7 @@ services:
|
|||||||
memswap_limit: 512m
|
memswap_limit: 512m
|
||||||
pids_limit: 128
|
pids_limit: 128
|
||||||
read_only: true
|
read_only: true
|
||||||
tmpfs: [/tmp:rw,noexec,nosuid,size=16m]
|
tmpfs: ["/tmp:rw,noexec,nosuid,size=16m"]
|
||||||
cap_drop: [ALL]
|
cap_drop: [ALL]
|
||||||
security_opt: [no-new-privileges:true]
|
security_opt: [no-new-privileges:true]
|
||||||
stop_grace_period: 10s
|
stop_grace_period: 10s
|
||||||
|
|||||||
+4
-2
@@ -150,7 +150,8 @@ class PostgresRepository:
|
|||||||
try:
|
try:
|
||||||
with self.database.connection() as conn:
|
with self.database.connection() as conn:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"INSERT INTO messages(id,chat_id,sender_id,text,created_at) "
|
"INSERT INTO messages(id,chat_id,sender_id,"
|
||||||
|
"text,created_at) "
|
||||||
"VALUES(%s,%s,%s,%s,%s)",
|
"VALUES(%s,%s,%s,%s,%s)",
|
||||||
(
|
(
|
||||||
message.id,
|
message.id,
|
||||||
@@ -174,7 +175,8 @@ class PostgresRepository:
|
|||||||
with self.database.connection() as conn:
|
with self.database.connection() as conn:
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id "
|
"SELECT c.id,c.title,c.created_at,ARRAY(SELECT user_id "
|
||||||
"FROM members WHERE chat_id=c.id ORDER BY position) member_ids "
|
"FROM members WHERE chat_id=c.id "
|
||||||
|
"ORDER BY position) member_ids "
|
||||||
"FROM chats c JOIN members own ON own.chat_id=c.id "
|
"FROM chats c JOIN members own ON own.chat_id=c.id "
|
||||||
"WHERE own.user_id=%s "
|
"WHERE own.user_id=%s "
|
||||||
+ condition
|
+ condition
|
||||||
|
|||||||
@@ -10,7 +10,9 @@ from jsonschema import Draft202012Validator, FormatChecker
|
|||||||
CONTRACT = json.loads(
|
CONTRACT = json.loads(
|
||||||
(Path(__file__).parents[1] / "contracts/openapi.json").read_text()
|
(Path(__file__).parents[1] / "contracts/openapi.json").read_text()
|
||||||
)
|
)
|
||||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8082")
|
||||||
|
PASSWORD = "Synthetic-Password-🌍-123"
|
||||||
|
TOKENS = {}
|
||||||
|
|
||||||
|
|
||||||
def check(result: httpx.Response, status: int, schema: str) -> dict:
|
def check(result: httpx.Response, status: int, schema: str) -> dict:
|
||||||
@@ -38,9 +40,23 @@ def check(result: httpx.Response, status: int, schema: str) -> dict:
|
|||||||
|
|
||||||
|
|
||||||
def register(client: httpx.Client, **overrides) -> dict:
|
def register(client: httpx.Client, **overrides) -> dict:
|
||||||
data = {"username": "u_" + uuid4().hex[:24], "display_name": "Алиса 🌍"}
|
data = {
|
||||||
|
"username": "u_" + uuid4().hex[:24],
|
||||||
|
"display_name": "Алиса 🌍",
|
||||||
|
"password": PASSWORD,
|
||||||
|
}
|
||||||
data.update(overrides)
|
data.update(overrides)
|
||||||
return check(client.post("/api/v1/users", json=data), 201, "User")
|
user = check(client.post("/api/v1/users", json=data), 201, "User")
|
||||||
|
session = check(
|
||||||
|
client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
auth=httpx.BasicAuth(data["username"], data["password"]),
|
||||||
|
),
|
||||||
|
201,
|
||||||
|
"Session",
|
||||||
|
)
|
||||||
|
TOKENS[user["id"]] = session["token"]
|
||||||
|
return user
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -62,7 +78,7 @@ def chat(client, actors):
|
|||||||
return check(
|
return check(
|
||||||
client.post(
|
client.post(
|
||||||
"/api/v1/chats",
|
"/api/v1/chats",
|
||||||
headers={"X-User-Id": alice["id"]},
|
headers=headers(alice),
|
||||||
json={"title": "Учёба 🌍", "member_ids": [alice["id"], bob["id"]]},
|
json={"title": "Учёба 🌍", "member_ids": [alice["id"], bob["id"]]},
|
||||||
),
|
),
|
||||||
201,
|
201,
|
||||||
@@ -71,7 +87,7 @@ def chat(client, actors):
|
|||||||
|
|
||||||
|
|
||||||
def headers(actor: dict) -> dict:
|
def headers(actor: dict) -> dict:
|
||||||
return {"X-User-Id": actor["id"]}
|
return {"Authorization": "Bearer " + TOKENS[actor["id"]]}
|
||||||
|
|
||||||
|
|
||||||
def history(client, actor, chat_id, limit=7):
|
def history(client, actor, chat_id, limit=7):
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ from uuid import UUID, uuid4
|
|||||||
|
|
||||||
import httpx
|
import httpx
|
||||||
import pytest
|
import pytest
|
||||||
from conftest import BASE_URL, check, headers, history, register
|
from conftest import BASE_URL, PASSWORD, check, headers, history, register
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("path", ["/health/live", "/health/ready"])
|
@pytest.mark.parametrize("path", ["/health/live", "/health/ready"])
|
||||||
@@ -54,6 +54,8 @@ def test_identity(client, actors):
|
|||||||
],
|
],
|
||||||
)
|
)
|
||||||
def test_invalid_user(client, data):
|
def test_invalid_user(client, data):
|
||||||
|
if isinstance(data, dict):
|
||||||
|
data = {"password": PASSWORD, **data}
|
||||||
check(client.post("/api/v1/users", content=json.dumps(data)), 400, "Error")
|
check(client.post("/api/v1/users", content=json.dumps(data)), 400, "Error")
|
||||||
|
|
||||||
|
|
||||||
@@ -72,7 +74,11 @@ def test_duplicate_username(client, actors):
|
|||||||
check(
|
check(
|
||||||
client.post(
|
client.post(
|
||||||
"/api/v1/users",
|
"/api/v1/users",
|
||||||
json={"username": actors[0]["username"], "display_name": "B"},
|
json={
|
||||||
|
"username": actors[0]["username"],
|
||||||
|
"display_name": "B",
|
||||||
|
"password": PASSWORD,
|
||||||
|
},
|
||||||
),
|
),
|
||||||
409,
|
409,
|
||||||
"Error",
|
"Error",
|
||||||
@@ -383,7 +389,11 @@ def test_registration_race(client):
|
|||||||
barrier.wait(timeout=15)
|
barrier.wait(timeout=15)
|
||||||
result = conn.post(
|
result = conn.post(
|
||||||
"/api/v1/users",
|
"/api/v1/users",
|
||||||
json={"username": username, "display_name": "Test"},
|
json={
|
||||||
|
"username": username,
|
||||||
|
"display_name": "Test",
|
||||||
|
"password": PASSWORD,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
check(
|
check(
|
||||||
result,
|
result,
|
||||||
|
|||||||
@@ -0,0 +1,114 @@
|
|||||||
|
from uuid import uuid4
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
import pytest
|
||||||
|
from conftest import PASSWORD, TOKENS, check, headers, register
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"password", ["", "x" * 11, "x" * 129, " " * 12, 42, True, None]
|
||||||
|
)
|
||||||
|
def test_password_validation(client, password):
|
||||||
|
check(
|
||||||
|
client.post(
|
||||||
|
"/api/v1/users",
|
||||||
|
json={
|
||||||
|
"username": "pwd_" + uuid4().hex[:20],
|
||||||
|
"display_name": "Test",
|
||||||
|
"password": password,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
400,
|
||||||
|
"Error",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_full_utf8_password(client):
|
||||||
|
password = "🌍" * 127 + ":"
|
||||||
|
user = register(client, password=password)
|
||||||
|
assert (
|
||||||
|
check(
|
||||||
|
client.get("/api/v1/users/me", headers=headers(user)), 200, "User"
|
||||||
|
)
|
||||||
|
== user
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"authorization", [None, "Basic broken", "Bearer unknown", "Basic /w=="]
|
||||||
|
)
|
||||||
|
def test_bad_basic(client, authorization):
|
||||||
|
result = client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
headers={"Authorization": authorization} if authorization else {},
|
||||||
|
)
|
||||||
|
check(result, 401, "Error")
|
||||||
|
assert (
|
||||||
|
result.headers["www-authenticate"]
|
||||||
|
== 'Basic realm="messenger", charset="UTF-8"'
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_wrong_password_and_unknown_user(client):
|
||||||
|
user = register(client)
|
||||||
|
for username in [user["username"], "missing_" + uuid4().hex[:20]]:
|
||||||
|
result = client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
auth=httpx.BasicAuth(username, PASSWORD + "wrong"),
|
||||||
|
)
|
||||||
|
data = check(result, 401, "Error")
|
||||||
|
assert data["error"]["message"] == "Authentication required"
|
||||||
|
|
||||||
|
|
||||||
|
def test_logout_is_not_revived_by_cache(client):
|
||||||
|
user = register(client)
|
||||||
|
auth = headers(user)
|
||||||
|
check(client.get("/api/v1/users/me", headers=auth), 200, "User")
|
||||||
|
result = client.delete("/api/v1/auth/sessions/current", headers=auth)
|
||||||
|
assert result.status_code == 204 and result.content == b""
|
||||||
|
assert result.headers["x-request-id"]
|
||||||
|
check(client.get("/api/v1/users/me", headers=auth), 401, "Error")
|
||||||
|
check(
|
||||||
|
client.delete("/api/v1/auth/sessions/current", headers=auth),
|
||||||
|
401,
|
||||||
|
"Error",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_only_current_session_revoked(client):
|
||||||
|
user = register(client)
|
||||||
|
another = check(
|
||||||
|
client.post(
|
||||||
|
"/api/v1/auth/sessions",
|
||||||
|
auth=httpx.BasicAuth(user["username"], PASSWORD),
|
||||||
|
),
|
||||||
|
201,
|
||||||
|
"Session",
|
||||||
|
)
|
||||||
|
assert another["token"] != TOKENS[user["id"]]
|
||||||
|
assert len(another["token"]) >= 32
|
||||||
|
assert (
|
||||||
|
client.delete(
|
||||||
|
"/api/v1/auth/sessions/current", headers=headers(user)
|
||||||
|
).status_code
|
||||||
|
== 204
|
||||||
|
)
|
||||||
|
result = client.get(
|
||||||
|
"/api/v1/users/me",
|
||||||
|
headers={"Authorization": "Bearer " + another["token"]},
|
||||||
|
)
|
||||||
|
assert check(result, 200, "User") == user
|
||||||
|
|
||||||
|
|
||||||
|
def test_bearer_source_and_ignored_user_header(client, actors):
|
||||||
|
alice, bob, _ = actors
|
||||||
|
auth = {**headers(alice), "X-User-Id": bob["id"]}
|
||||||
|
assert (
|
||||||
|
check(client.get("/api/v1/users/me", headers=auth), 200, "User")["id"]
|
||||||
|
== alice["id"]
|
||||||
|
)
|
||||||
|
result = client.get(
|
||||||
|
"/api/v1/users/me", auth=httpx.BasicAuth(alice["username"], PASSWORD)
|
||||||
|
)
|
||||||
|
check(result, 401, "Error")
|
||||||
|
assert result.headers["www-authenticate"] == 'Bearer realm="messenger"'
|
||||||
Reference in New Issue
Block a user