Skeleton contracts / contracts (pull_request) Blocked by required conditions
75 lines
2.3 KiB
Python
75 lines
2.3 KiB
Python
"""Создаёт bucket ключом Admin. Ключ не печатает. 200 и 409 считаются успехом."""
|
|
import datetime
|
|
import hashlib
|
|
import hmac
|
|
import os
|
|
import ssl
|
|
import sys
|
|
import urllib.error
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
|
|
def request(method, endpoint, access, secret, bucket, cafile):
|
|
host = urllib.parse.urlparse(endpoint).netloc
|
|
now = datetime.datetime.now(datetime.timezone.utc)
|
|
amz_date = now.strftime("%Y%m%dT%H%M%SZ")
|
|
day = amz_date[:8]
|
|
payload_hash = hashlib.sha256(b"").hexdigest()
|
|
path = "/" + urllib.parse.quote(bucket, safe="")
|
|
canonical_headers = (
|
|
f"host:{host}\n"
|
|
f"x-amz-content-sha256:{payload_hash}\n"
|
|
f"x-amz-date:{amz_date}\n"
|
|
)
|
|
signed = "host;x-amz-content-sha256;x-amz-date"
|
|
canonical = "\n".join([method, path, "", canonical_headers, signed, payload_hash])
|
|
scope = f"{day}/us-east-1/s3/aws4_request"
|
|
string_to_sign = "\n".join([
|
|
"AWS4-HMAC-SHA256",
|
|
amz_date,
|
|
scope,
|
|
hashlib.sha256(canonical.encode()).hexdigest(),
|
|
])
|
|
|
|
def mac(key, msg):
|
|
return hmac.new(key, msg.encode(), hashlib.sha256).digest()
|
|
|
|
signing = mac(("AWS4" + secret).encode(), day)
|
|
signing = mac(signing, "us-east-1")
|
|
signing = mac(signing, "s3")
|
|
signing = mac(signing, "aws4_request")
|
|
signature = hmac.new(signing, string_to_sign.encode(), hashlib.sha256).hexdigest()
|
|
auth = (
|
|
f"AWS4-HMAC-SHA256 Credential={access}/{scope}, "
|
|
f"SignedHeaders={signed}, Signature={signature}"
|
|
)
|
|
req = urllib.request.Request(endpoint + path, data=b"", method=method)
|
|
req.add_header("x-amz-date", amz_date)
|
|
req.add_header("x-amz-content-sha256", payload_hash)
|
|
req.add_header("Authorization", auth)
|
|
ctx = ssl.create_default_context(cafile=cafile)
|
|
try:
|
|
with urllib.request.urlopen(req, context=ctx, timeout=15) as response:
|
|
return response.status
|
|
except urllib.error.HTTPError as error:
|
|
return error.code
|
|
|
|
|
|
def main():
|
|
status = request(
|
|
"PUT",
|
|
os.environ["S3_ENDPOINT"],
|
|
os.environ["S3_ADMIN_ACCESS"],
|
|
os.environ["S3_ADMIN_SECRET"],
|
|
os.environ["S3_BUCKET"],
|
|
os.environ["CA_FILE"],
|
|
)
|
|
print(f"ensure-bucket {status}")
|
|
if status not in (200, 409):
|
|
sys.exit(1)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|