forked from mtusi2026/mtusi2026lab5
chore: port lab4 solution as lab5 base
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
bucket, key = sys.argv[1:3]
|
||||
base = 'http://s3:9000/' + bucket
|
||||
attempts = (
|
||||
('GET', '/<object>', base + '/' + key, None),
|
||||
('GET', '/', base + '/', None),
|
||||
('PUT', '/anon.txt', base + '/anon.txt', b'x'),
|
||||
)
|
||||
failed = False
|
||||
for method, label, url, data in attempts:
|
||||
try:
|
||||
code = urllib.request.urlopen(urllib.request.Request(url, data=data, method=method), timeout=5).status
|
||||
except urllib.error.HTTPError as error:
|
||||
code = error.code
|
||||
print(method, bucket + label, '->', code)
|
||||
failed = failed or code != 403
|
||||
sys.exit(1 if failed else 0)
|
||||
@@ -0,0 +1,46 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
bucket="${S3_BUCKET:-messenger-attachments}"
|
||||
object="check/$(date +%s)-$$.txt"
|
||||
|
||||
as_api() {
|
||||
docker compose run --rm --no-deps -T -e BUCKET="$bucket" -e OBJECT="$object" --entrypoint sh s3-init -c "$1"
|
||||
}
|
||||
|
||||
echo "## S3 не опубликован наружу, консоль выключена"
|
||||
docker compose ps s3 --format '{{.Service}} ports={{.Ports}}'
|
||||
echo "MINIO_BROWSER=$(docker compose exec -T s3 printenv MINIO_BROWSER)"
|
||||
|
||||
echo
|
||||
echo "## Права пользователя API: только свой bucket"
|
||||
as_api '
|
||||
set -e
|
||||
cd /run/secrets
|
||||
export MC_HOST_api="http://$(cat s3_access_key_id):$(cat s3_secret_access_key)@s3:9000"
|
||||
export MC_HOST_root="http://$(cat s3_root_user):$(cat s3_root_password)@s3:9000"
|
||||
expect() { want=$1; label=$2; shift 2; if "$@" >/dev/null 2>&1; then got=allowed; else got=denied; fi; echo "$label -> $got"; [ "$got" = "$want" ]; }
|
||||
echo probe > /tmp/probe.txt
|
||||
mc mb --ignore-existing root/check-other-bucket >/dev/null
|
||||
mc cp /tmp/probe.txt root/check-other-bucket/probe.txt >/dev/null
|
||||
trap "mc rb --force root/check-other-bucket >/dev/null" EXIT
|
||||
expect allowed "PUT в свой bucket" mc cp /tmp/probe.txt "api/$BUCKET/$OBJECT"
|
||||
expect allowed "GET из своего bucket" mc cat "api/$BUCKET/$OBJECT"
|
||||
expect denied "создание другого bucket" mc mb api/forbidden-bucket
|
||||
expect denied "GET из другого bucket" mc cat api/check-other-bucket/probe.txt
|
||||
expect denied "PUT в другой bucket" mc cp /tmp/probe.txt api/check-other-bucket/new.txt
|
||||
expect denied "изменение политики bucket" mc anonymous set public "api/$BUCKET"
|
||||
expect denied "администрирование пользователей" mc admin user list api
|
||||
'
|
||||
|
||||
echo
|
||||
echo "## Анонимный доступ напрямую к S3, мимо API"
|
||||
python3 scripts/check-s3-anonymous.py "$bucket" "$object"
|
||||
|
||||
as_api '
|
||||
cd /run/secrets
|
||||
export MC_HOST_api="http://$(cat s3_access_key_id):$(cat s3_secret_access_key)@s3:9000"
|
||||
mc rm "api/$BUCKET/$OBJECT" >/dev/null
|
||||
'
|
||||
echo
|
||||
echo "PASS: bucket приватный, у API нет прав вне своего bucket"
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
BASE = os.environ.get('BASE_URL', 'http://localhost:8080')
|
||||
|
||||
|
||||
def call(method, path, body=None, headers=None, with_headers=False):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
content_type = {'Content-Type': 'application/json'} if data else {}
|
||||
request = urllib.request.Request(BASE + path, data=data, method=method, headers={**content_type, **(headers or {})})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=15) as response:
|
||||
result = response.status, json.loads(response.read() or b'null'), response.headers
|
||||
except urllib.error.HTTPError as error:
|
||||
result = error.code, json.loads(error.read() or b'null'), error.headers
|
||||
except OSError as error:
|
||||
result = 0, str(error), {}
|
||||
return result if with_headers else result[:2]
|
||||
|
||||
|
||||
def login():
|
||||
username = 'probe_' + uuid.uuid4().hex[:8]
|
||||
password = 'Probe-check-' + uuid.uuid4().hex
|
||||
print('register ->', call('POST', '/api/v1/users', {'username': username, 'display_name': 'Probe', 'password': password})[0])
|
||||
credential = base64.b64encode((username + ':' + password).encode()).decode()
|
||||
code, session = call('POST', '/api/v1/auth/sessions', headers={'Authorization': 'Basic ' + credential})
|
||||
if code != 201:
|
||||
sys.exit('login failed: %s %s' % (code, session))
|
||||
print('login ->', code, 'expires_at:', session['expires_at'])
|
||||
return {'Authorization': 'Bearer ' + session['token']}
|
||||
|
||||
|
||||
def instances(count):
|
||||
auth = login()
|
||||
for _ in range(count):
|
||||
code, _, headers = call('GET', '/api/v1/users/me', headers=auth, with_headers=True)
|
||||
print('GET /api/v1/users/me ->', code, 'X-Instance-Id:', headers.get('X-Instance-Id'))
|
||||
|
||||
|
||||
def logout():
|
||||
auth = login()
|
||||
print('GET /api/v1/users/me ->', call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
code, body = call('DELETE', '/api/v1/auth/sessions/current', headers=auth)
|
||||
print('DELETE /api/v1/auth/sessions/current ->', code, json.dumps(body, ensure_ascii=False) if body else '')
|
||||
print('GET /api/v1/users/me ->', call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
|
||||
|
||||
def ready(timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if call('GET', '/health/ready')[0] == 200:
|
||||
print('ready')
|
||||
return
|
||||
time.sleep(0.5)
|
||||
sys.exit('not ready within %ds' % timeout)
|
||||
|
||||
|
||||
def status(method, path, authorization=None):
|
||||
code, body = call(method, path, headers={'Authorization': authorization} if authorization else None)
|
||||
print(method, path, '(%s)' % (authorization or 'anonymous'), '->', code, json.dumps(body, ensure_ascii=False))
|
||||
|
||||
|
||||
def expiry(ttl):
|
||||
auth = login()
|
||||
print('GET /api/v1/users/me (fresh) ->', call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
time.sleep(ttl + 1)
|
||||
print('GET /api/v1/users/me (after %ds) ->' % (ttl + 1), call('GET', '/api/v1/users/me', headers=auth)[0])
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
command = sys.argv[1]
|
||||
if command == 'ready':
|
||||
ready()
|
||||
elif command == 'status':
|
||||
status(*sys.argv[2:5])
|
||||
elif command == 'expiry':
|
||||
expiry(int(sys.argv[2]))
|
||||
elif command == 'instances':
|
||||
instances(int(sys.argv[2]))
|
||||
elif command == 'logout':
|
||||
logout()
|
||||
@@ -0,0 +1,9 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
started() {
|
||||
docker inspect -f '{{.Name}} {{.State.Status}} started={{.State.StartedAt}}' $(docker compose ps -aq postgres redis s3 api lb)
|
||||
}
|
||||
started
|
||||
docker compose restart postgres redis s3 api lb
|
||||
started
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?test provides target API instance alias}"
|
||||
project="${COMPOSE_PROJECT_NAME:-messenger-lab5}"
|
||||
labels=$(docker inspect -f '{{index .Config.Labels "com.docker.compose.project"}}/{{index .Config.Labels "com.docker.compose.service"}}' "$TARGET_INSTANCE_ID")
|
||||
if [ "$labels" != "$project/api" ]; then
|
||||
echo "refusing to stop $TARGET_INSTANCE_ID: not an api replica of $project ($labels)" >&2
|
||||
exit 1
|
||||
fi
|
||||
docker stop -t 8 "$TARGET_INSTANCE_ID" >/dev/null
|
||||
docker inspect -f '{{.Name}} {{.State.Status}} finished={{.State.FinishedAt}}' "$TARGET_INSTANCE_ID"
|
||||
Reference in New Issue
Block a user