From b2c151fca1f3ebde4271bc867419d6d2c403033f Mon Sep 17 00:00:00 2001 From: OptiDomain-Backend <3038442986@qq.com> Date: Sun, 9 Aug 2026 13:20:46 +0800 Subject: [PATCH] Add CI and deterministic content types --- .github/workflows/ci.yml | 54 ++++++++++++++++++ AGENTS.md | 3 + README.md | 15 +++++ tests/test_upload_r2.py | 106 +++++++++++++++++++++++++++++++++++ tests/test_worker.mjs | 117 +++++++++++++++++++++++++++++++++++++++ upload_r2.py | 41 +++++++++++++- 6 files changed, 335 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/ci.yml create mode 100644 tests/test_upload_r2.py create mode 100644 tests/test_worker.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..13e2603 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,54 @@ +name: CI + +on: + push: + pull_request: + workflow_dispatch: + +permissions: + contents: read + +jobs: + test: + runs-on: ubuntu-latest + timeout-minutes: 5 + + steps: + - name: Check out repository + uses: actions/checkout@v6 + + - name: Set up Python + uses: actions/setup-python@v6 + with: + python-version: "3.12" + + - name: Install Python dependencies + run: python -m pip install -r requirements.txt + + - name: Test Python uploader + run: | + python -m pip check + python -m unittest discover -s tests -p "test_*.py" -v + + - name: Validate project configuration + run: | + python -m json.tool config.example.json > /dev/null + python -c "import pathlib, tomllib; tomllib.loads(pathlib.Path('wrangler.toml').read_text(encoding='utf-8'))" + + - name: Set up Node.js + uses: actions/setup-node@v6 + with: + node-version: "24" + package-manager-cache: false + + - name: Test Worker and Pages runtime + run: | + node --check worker.mjs + node --test tests/test_worker.mjs + cmp worker.mjs pages-dist/_worker.js + + - name: Verify protected files are not tracked + run: | + test ! -e config.json + ! git ls-files --error-unmatch config.json + ! git ls-files | grep -E '^(\.venv/|\.env|\.dev\.vars)' diff --git a/AGENTS.md b/AGENTS.md index 8852d4f..036e0df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -20,6 +20,7 @@ - 所有 Python、pip、脚本和测试命令默认使用 `.venv\Scripts\python.exe`。 - 安装依赖使用 `.venv\Scripts\python.exe -m pip install -r requirements.txt`。 - 不使用系统 Python 直接运行 `upload_r2.py`。 +- 上传脚本优先按 R2 Object Key、其次按本地文件名判断 `Content-Type`;常见平台差异类型使用 `MIME_TYPE_OVERRIDES`,其余交给 Python `mimetypes`,未知类型回退为 `application/octet-stream`。 ## 安全与发布 @@ -31,7 +32,9 @@ ## 验证 - JavaScript:`node --check worker.mjs` +- Worker 测试:`node --test tests/test_worker.mjs` - Python:`.venv\Scripts\python.exe -m pip check` +- Python 测试:`.venv\Scripts\python.exe -m unittest discover -s tests -p "test_*.py" -v` - 配置示例:使用 Python `json` 模块解析 `config.example.json` - Pages 一致性:比较 `worker.mjs` 与 `pages-dist/_worker.js` - 行为验证至少覆盖根路径成功、缺少 Binding、缺少或无效 `ACCESS_KEYS`、GET、HEAD、403、404、405 和 R2 异常。 diff --git a/README.md b/README.md index 115df3a..d5f366f 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # R2Gate +[![CI](https://github.com/Fiatnorm/R2Gate/actions/workflows/ci.yml/badge.svg)](https://github.com/Fiatnorm/R2Gate/actions/workflows/ci.yml) + R2Gate 是一个精简的 Cloudflare R2 文件读取与上传工具: - Worker / Pages 使用 R2 Binding 读取文件。 @@ -157,6 +159,7 @@ Copy-Item .\config.example.json .\config.json ``` `LOCAL_FILE` 可以是绝对路径,也可以是相对于 `config.json` 的路径。 +上传时会优先根据 R2 Object Key、其次根据本地文件扩展名自动写入 `Content-Type`。脚本为 CSV、XML、ZIP、GZIP、7z、RAR、WebP、FLAC、AAC、AVI、WOFF、WOFF2、TTF、OTF 和 SH 提供跨平台固定映射,其余类型交给 Python `mimetypes` 判断,无法识别时使用 `application/octet-stream`。 运行: @@ -184,3 +187,15 @@ Copy-Item .\config.example.json .\config.json - 不要把 `R2_SECRET_ACCESS_KEY` 放入 Worker、Pages、URL 或前端代码。 - R2 Bucket 应保持非公开,避免通过 `r2.dev` 或 Bucket 自定义域名绕过 Worker。 - `ACCESS_KEYS` 是普通文本访问密码映射,可能出现在 Dashboard、URL、浏览器历史和访问日志中;不要复用重要密码。 + +## 持续集成 + +GitHub Actions 会在 Push、Pull Request 和手动触发时运行以下只读检查: + +- Worker 根路径、鉴权、GET、HEAD、403、404、405 和 R2 异常分支。 +- Python CREATE/UPDATE、`Content-Type` 判断与未知类型回退。 +- Worker 与 Pages 运行时代码一致性。 +- Python 依赖、JSON 和 TOML 配置格式。 +- `config.json`、`.venv` 和本地环境文件未被 Git 跟踪。 + +CI 不包含 Cloudflare 部署步骤,也不需要保存 Cloudflare API Token。 diff --git a/tests/test_upload_r2.py b/tests/test_upload_r2.py new file mode 100644 index 0000000..5c8e5ee --- /dev/null +++ b/tests/test_upload_r2.py @@ -0,0 +1,106 @@ +import contextlib +import io +import json +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +from botocore.exceptions import ClientError + +import upload_r2 + + +class FakeClient: + def __init__(self, exists): + self.exists = exists + self.uploaded = None + + def head_object(self, **kwargs): + if not self.exists: + raise ClientError({"Error": {"Code": "404"}}, "HeadObject") + + def upload_file(self, *args, **kwargs): + self.uploaded = (args, kwargs) + + +class UploadR2Tests(unittest.TestCase): + def run_upload(self, local_name, object_key, exists=False): + with tempfile.TemporaryDirectory() as directory: + directory_path = Path(directory) + local_file = directory_path / local_name + local_file.write_bytes(b"test") + config_path = directory_path / "config.json" + config_path.write_text( + json.dumps( + { + "R2_ACCOUNT_ID": "account-id", + "R2_ACCESS_KEY_ID": "access-key-id", + "R2_SECRET_ACCESS_KEY": "secret-access-key", + "R2_BUCKET_NAME": "bucket-name", + "LOCAL_FILE": local_name, + "R2_OBJECT_KEY": object_key, + } + ), + encoding="utf-8", + ) + client = FakeClient(exists) + output = io.StringIO() + + with ( + patch.object(upload_r2, "CONFIG_PATH", config_path), + patch("boto3.client", return_value=client), + contextlib.redirect_stdout(output), + ): + result = upload_r2.main() + + return result, output.getvalue(), client.uploaded + + def test_create_and_update(self): + for exists, marker in ((False, "[CREATE]"), (True, "[UPDATE]")): + with self.subTest(exists=exists): + result, output, uploaded = self.run_upload( + "payload.bin", "scripts/run.sh", exists + ) + self.assertEqual(result, 0) + self.assertIn(marker, output) + self.assertIn("[SUCCESS] Upload completed", output) + args, kwargs = uploaded + self.assertEqual(args[1:], ("bucket-name", "scripts/run.sh")) + self.assertEqual(kwargs["ExtraArgs"]["ContentType"], "text/x-sh") + + def test_content_type_priority_and_fallbacks(self): + cases = ( + ("payload.txt", "files/data.json", "application/json"), + ("payload.csv", "files/data", "text/csv"), + ("payload.unknown", "files/data", "application/octet-stream"), + ) + + for local_name, object_key, expected in cases: + with self.subTest(object_key=object_key, expected=expected): + result, _, uploaded = self.run_upload(local_name, object_key) + self.assertEqual(result, 0) + self.assertEqual(uploaded[1]["ExtraArgs"]["ContentType"], expected) + + def test_common_mime_overrides(self): + for extension, expected in upload_r2.MIME_TYPE_OVERRIDES.items(): + with self.subTest(extension=extension): + actual = upload_r2.guess_content_type(f"file{extension}") + self.assertEqual(actual, expected) + + def test_missing_config_returns_error(self): + missing_path = Path("missing-config.json").resolve() + error = io.StringIO() + + with ( + patch.object(upload_r2, "CONFIG_PATH", missing_path), + contextlib.redirect_stderr(error), + ): + result = upload_r2.main() + + self.assertEqual(result, 1) + self.assertIn("[ERROR] Config file not found", error.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_worker.mjs b/tests/test_worker.mjs new file mode 100644 index 0000000..0d15a78 --- /dev/null +++ b/tests/test_worker.mjs @@ -0,0 +1,117 @@ +import assert from "node:assert/strict"; +import test from "node:test"; + +import worker from "../worker.mjs"; + + +function makeObject(key) { + return { + body: `body:${key}`, + httpEtag: `etag-${key}`, + writeHttpMetadata(headers) { + headers.set("content-type", "text/plain"); + }, + }; +} + + +function makeBucket({ missing = [], failing = [] } = {}) { + const calls = { get: [], head: [] }; + + return { + calls, + async get(key) { + calls.get.push(key); + if (failing.includes(key)) throw new Error("R2 unavailable"); + return missing.includes(key) ? null : makeObject(key); + }, + async head(key) { + calls.head.push(key); + if (failing.includes(key)) throw new Error("R2 unavailable"); + return missing.includes(key) ? null : makeObject(key); + }, + }; +} + + +test("root reports deployment configuration", async () => { + let response = await worker.fetch(new Request("https://example.com/"), {}); + assert.equal(response.status, 500); + assert.equal(await response.text(), "R2 bucket binding is not configured"); + + const bucket = makeBucket(); + response = await worker.fetch(new Request("https://example.com/"), { BUCKET: bucket }); + assert.equal(response.status, 500); + assert.equal(await response.text(), "ACCESS_KEYS variable is not configured"); + + response = await worker.fetch(new Request("https://example.com/"), { + BUCKET: bucket, + ACCESS_KEYS: "not-json", + }); + assert.equal(response.status, 500); + assert.equal(await response.text(), "Invalid ACCESS_KEYS configuration"); + + response = await worker.fetch(new Request("https://example.com/"), { + BUCKET: bucket, + ACCESS_KEYS: "{}", + }); + assert.equal(response.status, 200); + assert.equal(await response.text(), "R2Gate is running successfully."); +}); + + +test("file access handles keys, GET, HEAD, 404, and 405", async () => { + const bucket = makeBucket({ missing: ["missing.txt"] }); + const env = { + BUCKET: bucket, + ACCESS_KEYS: JSON.stringify({ "private.txt": "file-key" }), + }; + + let response = await worker.fetch(new Request("https://example.com/private.txt"), env); + assert.equal(response.status, 403); + assert.equal(bucket.calls.get.length, 0); + + response = await worker.fetch( + new Request("https://example.com/private.txt?key=file-key"), + env, + ); + assert.equal(response.status, 200); + assert.equal(await response.text(), "body:private.txt"); + assert.equal(response.headers.get("etag"), "etag-private.txt"); + + response = await worker.fetch( + new Request("https://example.com/private.txt?key=file-key", { method: "HEAD" }), + env, + ); + assert.equal(response.status, 200); + assert.equal(await response.text(), ""); + assert.deepEqual(bucket.calls.head, ["private.txt"]); + + response = await worker.fetch(new Request("https://example.com/missing.txt"), env); + assert.equal(response.status, 404); + + response = await worker.fetch( + new Request("https://example.com/private.txt", { method: "POST" }), + env, + ); + assert.equal(response.status, 405); + assert.equal(response.headers.get("allow"), "GET, HEAD"); +}); + + +test("R2 failures return a controlled error", async () => { + const bucket = makeBucket({ failing: ["error.txt"] }); + const originalError = console.error; + console.error = () => {}; + + try { + const response = await worker.fetch(new Request("https://example.com/error.txt"), { + BUCKET: bucket, + ACCESS_KEYS: "{}", + }); + assert.equal(response.status, 500); + assert.equal(await response.text(), "Internal Server Error"); + } finally { + console.error = originalError; + } +}); diff --git a/upload_r2.py b/upload_r2.py index 61aacec..2555893 100644 --- a/upload_r2.py +++ b/upload_r2.py @@ -1,4 +1,5 @@ import json +import mimetypes import sys from pathlib import Path @@ -13,6 +14,37 @@ "R2_OBJECT_KEY", ) +MIME_TYPE_OVERRIDES = { + ".csv": "text/csv", + ".xml": "application/xml", + ".zip": "application/zip", + ".gz": "application/gzip", + ".gzip": "application/gzip", + ".7z": "application/x-7z-compressed", + ".rar": "application/vnd.rar", + ".webp": "image/webp", + ".flac": "audio/flac", + ".aac": "audio/aac", + ".avi": "video/x-msvideo", + ".woff": "font/woff", + ".woff2": "font/woff2", + ".ttf": "font/ttf", + ".otf": "font/otf", + ".sh": "text/x-sh", +} + +def guess_content_type(*file_names): + for file_name in file_names: + override = MIME_TYPE_OVERRIDES.get(Path(file_name).suffix.lower()) + if override: + return override + + guessed_type = mimetypes.guess_type(file_name)[0] + if guessed_type: + return guessed_type + + return "application/octet-stream" + def main(): try: @@ -46,6 +78,8 @@ def main(): print(f"[ERROR] Local file not found: {local_file}", file=sys.stderr) return 1 + content_type = guess_content_type(object_key, local_file.name) + try: import boto3 from botocore.exceptions import ClientError @@ -68,7 +102,12 @@ def main(): raise action = "CREATE" - client.upload_file(str(local_file), bucket, object_key) + client.upload_file( + str(local_file), + bucket, + object_key, + ExtraArgs={"ContentType": content_type}, + ) print(f"[{action}] {object_key}") print("[SUCCESS] Upload completed") return 0