179 lines
9.2 KiB
Python
179 lines
9.2 KiB
Python
"""Run against a disposable gateway and private S3 bucket. Uses curl's AWS SigV4 for object checks."""
|
|
import concurrent.futures
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import time
|
|
import uuid
|
|
from urllib.error import HTTPError
|
|
from urllib.request import urlopen
|
|
|
|
from smoke import call, make_request
|
|
|
|
|
|
def upload(path, jpeg, *, user="owner", status=201, request_key=None):
|
|
boundary = uuid.uuid4().hex
|
|
request = make_request("POST", path, None, user)
|
|
request.add_header("Content-Type", f"multipart/form-data; boundary={boundary}")
|
|
if request_key is not None:
|
|
request.add_header("Idempotency-Key", str(request_key))
|
|
request.data = (f'--{boundary}\r\nContent-Disposition: form-data; name="image"; filename="photo.jpg"\r\n'
|
|
f'Content-Type: image/jpeg\r\n\r\n').encode() + jpeg + f"\r\n--{boundary}--\r\n".encode()
|
|
if status == 413:
|
|
command = ["curl", "-sS", "--max-time", "15", "-o", os.devnull, "-w", "%{http_code}",
|
|
"-X", "POST", "--data-binary", "@-", request.full_url]
|
|
for name, value in request.header_items():
|
|
command += ["-H", f"{name}: {value}"]
|
|
result = subprocess.run(command, input=request.data, capture_output=True)
|
|
assert result.returncode == 0 and result.stdout == b"413", (result.returncode, result.stdout)
|
|
return b""
|
|
return response(request, status)
|
|
|
|
|
|
def response(request, status):
|
|
try:
|
|
result = urlopen(request, timeout=25)
|
|
except HTTPError as failure:
|
|
result = failure
|
|
with result:
|
|
body = result.read()
|
|
assert result.status == status, (request.method, request.selector, result.status, body[:300])
|
|
return body
|
|
|
|
|
|
def storage_status(house, item, photo, filename, collection="items"):
|
|
endpoint = os.environ["ATLAS_MEDIA_ENDPOINT"].rstrip("/")
|
|
region = os.environ["ATLAS_MEDIA_REGION"]
|
|
bucket = os.environ["ATLAS_MEDIA_BUCKET"]
|
|
key = os.environ["ATLAS_MEDIA_ACCESS_KEY"]
|
|
secret = os.environ["ATLAS_MEDIA_SECRET_KEY"]
|
|
url = f"{endpoint}/{bucket}/households/{house}/{collection}/{item}/{photo}/{filename}"
|
|
credentials = f'user = {key}:{secret}\n'
|
|
result = subprocess.run(["curl", "-sS", "--max-time", "5", "-o", os.devnull, "-w", "%{http_code}",
|
|
"--aws-sigv4", f"aws:amz:{region}:s3", "--config", "-", url],
|
|
input=credentials, capture_output=True, text=True)
|
|
return result.stdout.strip() if result.returncode == 0 else "000"
|
|
|
|
|
|
def await_absence(house, item, photo, collection="items"):
|
|
for _ in range(25):
|
|
if all(storage_status(house, item, photo, variant, collection) == "404"
|
|
for variant in ("image.jpg", "thumb.jpg")):
|
|
return
|
|
time.sleep(1)
|
|
raise AssertionError(f"Storage keys for {photo} still exist")
|
|
|
|
|
|
def verify_location_photos(house, space, jpeg):
|
|
import json
|
|
|
|
room = call("POST", space + "/locations", {"name": "带照片的房间"}, status=201)["id"]
|
|
child = call("POST", space + "/locations", {"name": "收纳柜", "parentId": room}, status=201)["id"]
|
|
location = f"{space}/locations/{child}"
|
|
photos = location + "/photos"
|
|
assert call("GET", photos) == [] and call("GET", location)["coverPhotoId"] is None
|
|
upload(photos, jpeg, user="viewer", status=403)
|
|
call("GET", photos, user="other", status=404)
|
|
upload(photos, b"x" * (6 * 1024 * 1024), status=413)
|
|
key = uuid.uuid4()
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
|
receipts = list(pool.map(lambda _: json.loads(upload(photos, jpeg, request_key=key)), range(2)))
|
|
assert receipts[0] == receipts[1] and call("GET", photos) == [receipts[0]]
|
|
first = receipts[0]["id"]
|
|
second = json.loads(upload(photos, jpeg))["id"]
|
|
assert call("GET", location)["coverPhotoId"] == first
|
|
asset = f"{photos}/{first}"
|
|
full = response(make_request("GET", asset, None, "owner"), 200)
|
|
thumb = response(make_request("GET", asset + "?thumbnail=true", None, "viewer"), 200)
|
|
assert full[:2] == thumb[:2] == b"\xff\xd8" and len(full) > len(thumb)
|
|
assert all(storage_status(house, child, first, variant, "locations") == "200"
|
|
for variant in ("image.jpg", "thumb.jpg"))
|
|
call("DELETE", asset, user="viewer", status=403)
|
|
call("DELETE", asset, status=202)
|
|
await_absence(house, child, first, "locations")
|
|
assert call("GET", location)["coverPhotoId"] == second
|
|
call("DELETE", location, status=204)
|
|
call("GET", photos, status=404)
|
|
await_absence(house, child, second, "locations")
|
|
room_photo = json.loads(upload(f"{space}/locations/{room}/photos", jpeg))["id"]
|
|
print("PASS location photo routing, cover, permissions, retry and location cleanup", flush=True)
|
|
return room, room_photo
|
|
|
|
|
|
def main():
|
|
import json
|
|
|
|
jpeg = Path(os.environ["ATLAS_SMOKE_JPEG"]).read_bytes()
|
|
house = call("POST", "/api/households", {"name": "图片验收", "displayName": "测试"}, status=201)["id"]
|
|
space = f"/api/households/{house}"
|
|
location = call("POST", space + "/locations", {"name": "抽屉"}, status=201)["id"]
|
|
item = call("POST", space + "/items", {"name": "储物盒", "quantity": 1, "locationId": location}, status=201)
|
|
photos = f"{space}/items/{item['id']}/photos"
|
|
code = call("POST", space + "/invitations", {"role": "VIEWER"}, status=201)["code"]
|
|
call("POST", "/api/households/invitations/redeem", {"code": code, "displayName": "访客"}, user="viewer")
|
|
try:
|
|
assert call("GET", photos) == []
|
|
upload(photos, jpeg, user="viewer", status=403)
|
|
upload(photos, b"not a picture", status=415)
|
|
upload(photos, b"x" * (5 * 1024 * 1024 + 1), status=413)
|
|
upload(photos, b"x" * (6 * 1024 * 1024), status=413)
|
|
key = uuid.uuid4()
|
|
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
|
|
receipts = list(pool.map(lambda _: json.loads(upload(photos, jpeg, request_key=key)), range(2)))
|
|
assert receipts[0] == receipts[1] and call("GET", photos) == [receipts[0]]
|
|
photo = receipts[0]["id"]
|
|
assert call("GET", space + "/items")[0]["coverPhotoId"] == photo
|
|
assert call("GET", space + "/items?favorites=true") == []
|
|
call("PUT", f"{space}/items/{item['id']}/preference", {"favorite": True})
|
|
assert len(call("GET", space + "/items?favorites=true")) == 1
|
|
assert call("GET", space + "/items?favorites=true", user="viewer") == []
|
|
resource = f"{photos}/{photo}"
|
|
full = response(make_request("GET", resource, None, "owner"), 200)
|
|
thumb = response(make_request("GET", resource + "?thumbnail=true", None, "viewer"), 200)
|
|
assert full[:2] == thumb[:2] == b"\xff\xd8" and len(full) > len(thumb)
|
|
call("GET", resource, user="other", status=404)
|
|
call("GET", resource, user=None, status=401)
|
|
assert all(storage_status(house, item["id"], photo, variant) == "200" for variant in ("image.jpg", "thumb.jpg"))
|
|
call("DELETE", resource, user="viewer", status=403)
|
|
call("DELETE", resource, status=202)
|
|
call("GET", resource, status=404)
|
|
await_absence(house, item["id"], photo)
|
|
archived = json.loads(upload(photos, jpeg))["id"]
|
|
call("DELETE", f"{space}/items/{item['id']}?version={item['version']}", status=204)
|
|
await_absence(house, item["id"], archived)
|
|
second = call("POST", space + "/items", {"name": "相册", "quantity": 1, "locationId": location}, status=201)
|
|
remaining = json.loads(upload(f"{space}/items/{second['id']}/photos", jpeg))["id"]
|
|
room, room_photo = verify_location_photos(house, space, jpeg)
|
|
call("DELETE", space, user="viewer", status=403)
|
|
call("DELETE", f"/api/admin/households/{house}", status=403)
|
|
call("DELETE", space, status=202)
|
|
call("GET", space, status=404)
|
|
await_absence(house, second["id"], remaining)
|
|
await_absence(house, room, room_photo, "locations")
|
|
print("PASS upload limits, retry deduplication, thumbnail, authorization, favorites and OSS cleanup")
|
|
if os.environ.get("ATLAS_SMOKE_ADMIN_TOKEN"):
|
|
from smoke import TOKENS
|
|
TOKENS["admin"] = os.environ["ATLAS_SMOKE_ADMIN_TOKEN"]
|
|
another = call("POST", "/api/households", {"name": "管理端验收"}, status=201)["id"]
|
|
api = f"/api/households/{another}"
|
|
admin = f"/api/admin/households/{another}"
|
|
place = call("POST", api + "/locations", {"name": "盒子"}, status=201)["id"]
|
|
second = call("POST", api + "/items", {"name": "纸盒", "quantity": 1, "locationId": place}, status=201)
|
|
attached = json.loads(upload(f"{api}/items/{second['id']}/photos", jpeg))["id"]
|
|
place_photo = json.loads(upload(f"{api}/locations/{place}/photos", jpeg))["id"]
|
|
assert call("GET", admin, user="admin")["photos"] == 2
|
|
call("DELETE", admin, user="admin", status=202)
|
|
call("GET", api, status=404)
|
|
await_absence(another, second["id"], attached)
|
|
await_absence(another, place, place_photo, "locations")
|
|
print("PASS dedicated OIDC admin client, role, audited deletion and both OSS objects")
|
|
finally:
|
|
try:
|
|
call("DELETE", space, status=202)
|
|
except AssertionError:
|
|
pass
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|