Code Issues Pull Requests Actions Packages Projects Releases 15 Wiki Activity Security Code Quality

Enhance Gitea badges workflow with cache support and additional parameters; update badge awarding script for improved error handling and S3 integration; modify badges.json to adjust worker count and document cache usage in README
Gitea badges / award (push) Canceled after 43s

This commit is contained in:
tienbh committed 2026-11-19 11:59:20 +07:00
1 parent ec8522633b
commit 243eea2aa3
5 files changed
+419 -47

No files matched your search

+77
View File
@@ -0,0 +1,77 @@
"""
Tiny S3 client (AWS SigV4, path-style) for a single JSON cache object.
Stdlib only. Tested target: RustFS / MinIO-compatible endpoints.
"""
import datetime
import gzip
import hashlib
import hmac
import json
import urllib.error
import urllib.parse
import urllib.request
class S3Object:
def __init__(self, endpoint, bucket, key, access_key, secret_key, region="us-east-1"):
u = urllib.parse.urlsplit(endpoint.rstrip("/"))
self.scheme = u.scheme or "https"
self.host = u.netloc or u.path
parts = [bucket] + [p for p in key.split("/") if p]
self.path = "/" + "/".join(urllib.parse.quote(p, safe="-_.~") for p in parts)
self.access_key, self.secret_key, self.region = access_key, secret_key, region
self.label = f"s3://{bucket}/{key}"
def _request(self, method, body=b""):
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(body).hexdigest()
signed_headers = {"host": self.host, "x-amz-content-sha256": payload_hash,
"x-amz-date": amz_date}
names = sorted(signed_headers)
canonical = "\n".join([
method, self.path, "",
"".join(f"{k}:{signed_headers[k]}\n" for k in names),
";".join(names), payload_hash,
])
scope = f"{day}/{self.region}/s3/aws4_request"
to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope,
hashlib.sha256(canonical.encode()).hexdigest()])
k = ("AWS4" + self.secret_key).encode()
for part in (day, self.region, "s3", "aws4_request"):
k = hmac.new(k, part.encode(), hashlib.sha256).digest()
sig = hmac.new(k, to_sign.encode(), hashlib.sha256).hexdigest()
req = urllib.request.Request(f"{self.scheme}://{self.host}{self.path}",
data=body if method == "PUT" else None, method=method)
req.add_header("Host", self.host)
req.add_header("x-amz-content-sha256", payload_hash)
req.add_header("x-amz-date", amz_date)
req.add_header("Authorization",
f"AWS4-HMAC-SHA256 Credential={self.access_key}/{scope}, "
f"SignedHeaders={';'.join(names)}, Signature={sig}")
if method == "PUT":
req.add_header("Content-Type", "application/gzip")
with urllib.request.urlopen(req, timeout=60) as r:
return r.read()
def load_json(self):
"""Return the decoded object, or None if it does not exist yet."""
try:
raw = self._request("GET")
except urllib.error.HTTPError as e:
if e.code == 404:
return None
raise RuntimeError(f"GET {self.label} -> HTTP {e.code}: "
f"{e.read().decode(errors='replace')[:300]}") from None
return json.loads(gzip.decompress(raw))
def save_json(self, obj):
body = gzip.compress(json.dumps(obj, separators=(",", ":")).encode())
try:
self._request("PUT", body)
except urllib.error.HTTPError as e:
raise RuntimeError(f"PUT {self.label} -> HTTP {e.code}: "
f"{e.read().decode(errors='replace')[:300]}") from None
return len(body)