Commit82c5fa56Recorded6 Sep 2026Repositorysigil-cloudflare
Add Cloudflare R2 client with SigV4 and binary object operations
Changed
.gitignore | 2 ++
AGENTS.md | 12 ++++++++++++
LICENSE | 27 +++++++++++++++++++++++++++
README.md | 86 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
package.sgl | 17 +++++++++++++++++
sigil.lock | 52 ++++++++++++++++++++++++++++++++++++++++++++++++++++
src/cloudflare/r2.sgl | 73 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
src/cloudflare/r2/signing.sgl | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test/http.mjs | 67 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
test/test-network.sgl | 23 +++++++++++++++++++++++
test/test-signing.sgl | 36 ++++++++++++++++++++++++++++++++++++
11 files changed, 470 insertions(+)Diff
.gitignoreadded
@@ -0,0 +1,2 @@
+1
build/+2
.sigil/AGENTS.mdadded
@@ -0,0 +1,12 @@
+1
# sigil-cloudflare+2
+3
Reusable Cloudflare clients for Sigil, initially R2. Use hierarchical modules:+4
`(cloudflare r2)`, `(cloudflare r2 signing)`, and future `(cloudflare SERVICE ...)`.+5
Keep Rezvibe permissions, UI, image validation and branding policy in Rezvibe.+6
Never log credentials, Authorization headers, signed URLs or private object data.+7
Binary object bodies must remain bytevectors throughout transport. Use sigil-http+8
and sigil-crypto. Preserve raw-key UTF-8 signing semantics and test against an+9
independent reference, including maximum key sizes and malformed input.+10
Run `sigil test --sgl --strict` and `node test/http.mjs`; the latter starts an+11
ephemeral loopback fake service. Tests must never use real credentials or R2.+12
No live-provider verification has been performed. Keep README limits accurate.LICENSEadded
@@ -0,0 +1,27 @@
+1
BSD 3-Clause License+2
+3
Copyright (c) 2026, David Wilson+4
All rights reserved.+5
+6
Redistribution and use in source and binary forms, with or without+7
modification, are permitted provided that the following conditions are met:+8
+9
1. Redistributions of source code must retain the above copyright notice, this+10
list of conditions and the following disclaimer.+11
2. Redistributions in binary form must reproduce the above copyright notice,+12
this list of conditions and the following disclaimer in the documentation+13
and/or other materials provided with the distribution.+14
3. Neither the name of the copyright holder nor the names of its contributors+15
may be used to endorse or promote products derived from this software without+16
specific prior written permission.+17
+18
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND+19
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED+20
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE+21
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR+22
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES+23
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;+24
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON+25
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT+26
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS+27
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.README.mdadded
@@ -0,0 +1,86 @@
+1
# sigil-cloudflare+2
+3
Cloudflare services for Sigil, starting with R2 object storage. Modules use+4
hierarchical namespaces: `(cloudflare r2)` and `(cloudflare r2 signing)`.+5
+6
The initial client supports binary PUT, GET, HEAD and DELETE, S3 Signature V4+7
with R2's `auto` region, and public URLs through a separately configured custom+8
domain. It uses sigil-http and sigil-crypto directly. No external signing process,+9
AWS SDK, automatic redirect following or automatic retry is involved.+10
+11
## Use+12
+13
```scheme+14
(import (sigil core) (sigil io) (sigil process) (cloudflare r2))+15
+16
(define storage+17
(r2-client (getenv "R2_ACCOUNT_ID")+18
(getenv "R2_ACCESS_KEY_ID")+19
(getenv "R2_SECRET_ACCESS_KEY")+20
"rezvibe-assets"+21
public-base-url: "https://assets.rezvibe.com"))+22
+23
(define result+24
(r2-put-object storage "examples/hello.txt" (string->utf8 "Hello!")+25
content-type: "text/plain" cache-control: "public, max-age=3600"))+26
+27
(when (and result (= (dict-ref result status:) 200))+28
(display (r2-public-url storage "examples/hello.txt")))+29
+30
(r2-head-object storage "examples/hello.txt")+31
(r2-get-object storage "examples/hello.txt")+32
(r2-delete-object storage "examples/hello.txt")+33
```+34
+35
Supply bucket-scoped R2 S3 credentials on the server, never in a browser or log.+36
The client returns sigil-http's dictionary with `status:`, ordered header alist+37
`headers:` and bytevector `body:`. Non-2xx responses are returned for the caller+38
to handle; connection/framing failures return `#f`. An uncertain failed PUT may+39
already have reached storage. Use unique application-generated object keys and+40
explicit reconciliation/retry policy. Never log signed headers or response bodies.+41
The closure-based client does not expose credentials through record accessors.+42
+43
Object keys are raw UTF-8 strings, not URL-encoded strings. The signer preserves+44
slashes and dot segments and encodes reserved bytes; applications should generate+45
safe keys and should not use `.`/`..` segments for public browser URLs. Public base+46
URL must be an HTTPS origin without a trailing slash. Configure that custom domain+47
on the R2 bucket; this helper does not create DNS or enable public access.+48
+49
## Scope and limits+50
+51
Calls buffer request/response bodies in memory. Set application upload limits;+52
use this initial API for bounded assets. The timeout is sigil-http's connection+53
and idle I/O timeout, not a total operation budget. Responses with a mismatched+54
Content-Length are rejected. Generic response buffering/chunk framing retain+55
sigil-http's limits. Streaming/multipart uploads, presigned URLs, jurisdictional+56
endpoints, list operations, DNS/bucket administration and image processing are+57
not implemented. This is not a complete Cloudflare API client.+58
+59
Public logos and private support attachments require separate application access+60
policies and storage configuration. The library does not authorize customers or+61
validate image formats; Rezvibe must do that at its own boundary.+62
+63
## Verification+64
+65
```sh+66
sigil deps install+67
sigil build+68
sigil test --sgl --strict+69
node test/http.mjs+70
```+71
+72
Node 18+ is needed only for the independent fake HTTP service. Tests use public+73
AWS signature vectors, UTF-8/query/header edge cases and a binary round trip+74
through actual Sigil HTTP with signatures verified independently using Node crypto.+75
They also check deletion, error status, truncated response rejection and that+76
redirects/retries do not send extra requests. `test-port:` explicitly enables+77
an HTTP endpoint restricted to 127.0.0.1 for fake-service tests; use fake credentials.+78
+79
No live R2 bucket has been tested yet. Cloudflare bucket credentials, the custom+80
domain and Rezvibe's in-page upload integration remain to be configured.+81
+82
References: [Cloudflare R2 S3 API](https://developers.cloudflare.com/r2/api/s3/api/),+83
[custom domains](https://developers.cloudflare.com/r2/buckets/public-buckets/),+84
[AWS SigV4 examples](https://docs.aws.amazon.com/AmazonS3/latest/developerguide/sig-v4-header-based-auth.html).+85
+86
BSD-3-Clause; see LICENSE.package.sgladded
@@ -0,0 +1,17 @@
+1
(package+2
name: "sigil-cloudflare"+3
version: "0.1.0"+4
sigil: "0.21"+5
description: "Cloudflare R2 object storage client for Sigil"+6
license: "BSD-3-Clause"+7
configs: (list+8
(config name: 'dev output-dir: "build/dev" debug?: #t optimize: 0)+9
(config name: 'release output-dir: "build/release" debug?: #f optimize: 2))+10
dependencies: (list+11
(from-git url: "codeberg:sigil/sigil-http" version: "^0.18.6")+12
(from-git url: "codeberg:sigil/sigil-crypto" version: "^0.16.0"))+13
dev-dependencies: (list+14
(from-git url: "codeberg:sigil/sigil" package: "sigil-test" version: ">=0.21")+15
(from-git url: "codeberg:sigil/sigil" package: "sigil-test-runner" version: ">=0.21"))+16
tasks: (list (task name: 'build description: "Compile Cloudflare modules"+17
steps: (list (compile-sigil-modules sources: "src/**/*.sgl" output-dir: (config-output-subdir "lib"))))))sigil.lockadded
@@ -0,0 +1,52 @@
+1
;; Auto-generated by sigil deps install. Do not edit.+2
(lock+3
(package name: "sigil-stdlib"+4
url: "codeberg:sigil/sigil"+5
ref: ">=0.21, <1.0"+6
sha: "8643e9abf19038c5f4961d41748427dbd623cb15"+7
package-selector: "sigil-stdlib"+8
version: "0.21.0")+9
(package name: "sigil-test"+10
url: "codeberg:sigil/sigil"+11
ref: ">=0.21"+12
sha: "8643e9abf19038c5f4961d41748427dbd623cb15"+13
package-selector: "sigil-test"+14
version: "0.21.0")+15
(package name: "sigil-test-runner"+16
url: "codeberg:sigil/sigil"+17
ref: ">=0.21"+18
sha: "8643e9abf19038c5f4961d41748427dbd623cb15"+19
package-selector: "sigil-test-runner"+20
version: "0.21.0")+21
(package name: "sigil-http"+22
url: "codeberg:sigil/sigil-http"+23
ref: "^0.18.6"+24
sha: "fbe1eb4afed4e84ef91db23feff20d4bfddba4ab"+25
version: "0.18.6")+26
(package name: "sigil-crypto"+27
url: "codeberg:sigil/sigil-crypto"+28
ref: "^0.16.0"+29
sha: "debba4462b7ff4de143db9e0792b8606fdc455bc"+30
version: "0.16.5")+31
(package name: "sigil-json"+32
url: "codeberg:sigil/sigil-json"+33
ref: "^0.16.0"+34
sha: "55c9e74712b5f79b45d41c65cfe0aef2c8f7e155"+35
version: "0.16.0")+36
(package name: "sigil-sqlite"+37
url: "codeberg:sigil/sigil-sqlite"+38
ref: "^0.16.0"+39
sha: "569ef1063dda8f5989968644af31fc09c64b4bfe"+40
version: "0.16.3")+41
(package name: "sigil-tls"+42
url: "codeberg:sigil/sigil-tls"+43
ref: "^0.16.5"+44
sha: "4cde885f8bbb15b1457b0293a5b9fa7d292cfc46"+45
version: "0.16.6")+46
(package name: "sigil-lib"+47
url: "codeberg:sigil/sigil"+48
ref: "^0.19"+49
sha: "8643e9abf19038c5f4961d41748427dbd623cb15"+50
package-selector: "sigil-lib"+51
version: "0.21.0")+52
)src/cloudflare/r2.sgladded
@@ -0,0 +1,73 @@
+1
;;; Cloudflare R2's S3 API. All calls are synchronous, buffered and do not retry.+2
(define-library (cloudflare r2)+3
(import (sigil core) (sigil io) (sigil string) (sigil list) (sigil time)+4
(sigil http client) (cloudflare r2 signing))+5
(export r2-client r2-put-object r2-get-object r2-head-object r2-delete-object r2-public-url)+6
(begin+7
;; A closure deliberately keeps credentials out of printed client values.+8
(define (r2-client account-id access-key-id secret-access-key bucket+9
(keys: (public-base-url #f) (timeout 30) (test-port #f)))+10
(unless (and (string? account-id) (= (string-length account-id) 32)+11
(every (lambda (c) (or (and (char<=? #\0 c) (char<=? c #\9)) (and (char<=? #\a c) (char<=? c #\f))))+12
(string->list account-id)))+13
(error "R2 account ID must be 32 lowercase hex characters"))+14
(unless (and (string? bucket) (<= 3 (string-length bucket) 63)+15
(every (lambda (c) (or (and (char<=? #\a c) (char<=? c #\z)) (and (char<=? #\0 c) (char<=? c #\9)) (char=? c #\-))) (string->list bucket))+16
(not (char=? (string-ref bucket 0) #\-))+17
(not (char=? (string-ref bucket (- (string-length bucket) 1)) #\-)))+18
(error "Invalid R2 bucket name"))+19
(unless (and (string? access-key-id) (> (string-length access-key-id) 0)+20
(every char-alphabetic-or-numeric? (string->list access-key-id))+21
(string? secret-access-key) (> (string-length secret-access-key) 0)+22
(number? timeout) (> timeout 0))+23
(error "Invalid R2 credentials or timeout"))+24
(when test-port+25
(unless (and (integer? test-port) (<= 1 test-port 65535)) (error "Invalid R2 loopback test port")))+26
(when public-base-url (validate-public-origin public-base-url))+27
(let* ((host (if test-port (string-append "127.0.0.1:" (number->string test-port))+28
(string-append account-id ".r2.cloudflarestorage.com")))+29
(origin (string-append (if test-port "http://" "https://") host)))+30
(lambda (action key body headers)+31
(validate-key key)+32
(if (eq? action 'public-url)+33
(and public-base-url (string-append public-base-url "/" (r2-uri-encode key preserve-slashes?: #t)))+34
(let* ((now (current-second))+35
(stamp (string-append (string-join (string-split (format-date now #t) "-") "") "T"+36
(string-join (string-split (format-time now #t) ":") "") "Z"))+37
(signed (r2-sign-request action (string-append "/" bucket "/" key) '()+38
(cons (cons "host" host) headers) (or body (make-bytevector 0))+39
access-key-id secret-access-key stamp))+40
;; The HTTP client supplies Host itself. Sending it twice can+41
;; invalidate the signature; sign once, send once.+42
(wire-headers (filter (lambda (h) (not (string=? (car h) "host"))) (dict-ref signed headers:)))+43
(result (http-fetch-bytes action (string-append origin (dict-ref signed path:))+44
headers: wire-headers body: body timeout: timeout)))+45
(when result+46
(let* ((length-header (assoc "content-length" (dict-ref result headers:)))+47
(expected (and length-header (string->number (cdr length-header)))))+48
(when (and (not (eq? action 'HEAD)) expected+49
(not (= expected (bytevector-length (dict-ref result body:)))))+50
(set! result #f))))+51
result)))))+52
(define (char-alphabetic-or-numeric? c)+53
(or (and (char<=? #\a c) (char<=? c #\z)) (and (char<=? #\A c) (char<=? c #\Z)) (and (char<=? #\0 c) (char<=? c #\9))))+54
(define (validate-public-origin origin)+55
;; A public URL is a separate R2 custom-domain origin, never the signed API.+56
(let ((url (and (string? origin) (parse-url origin))))+57
(unless (and url (string=? (url-scheme url) "https")+58
(not (url-query url)) (string=? (url-path url) "/")+59
(not (string-contains? origin "@")) (not (string-contains? origin "#"))+60
(not (string-contains? origin "\r")) (not (string-contains? origin "\n"))+61
(not (char=? (string-ref origin (- (string-length origin) 1)) #\/)))+62
(error "R2 public base URL must be an HTTPS origin without a trailing slash"))))+63
(define (validate-key key)+64
(unless (and (string? key) (<= 1 (bytevector-length (string->utf8 key)) 1024))+65
(error "R2 object key must contain 1 to 1024 UTF-8 bytes")))+66
(define (r2-put-object client key bytes (keys: (content-type "application/octet-stream") (cache-control #f)))+67
(unless (bytevector? bytes) (error "R2 upload body must be a bytevector"))+68
(client 'PUT key bytes (append (list (cons "content-type" content-type))+69
(if cache-control (list (cons "cache-control" cache-control)) '()))))+70
(define (r2-get-object client key) (client 'GET key #f '()))+71
(define (r2-head-object client key) (client 'HEAD key #f '()))+72
(define (r2-delete-object client key) (client 'DELETE key #f '()))+73
(define (r2-public-url client key) (client 'public-url key #f '()))))src/cloudflare/r2/signing.sgladded
@@ -0,0 +1,75 @@
+1
;;; S3 Signature Version 4. Inputs are raw paths/query strings, never pre-escaped.+2
(define-library (cloudflare r2 signing)+3
(import (sigil core) (sigil io) (sigil math) (sigil string) (sigil list) (sigil crypto))+4
(export r2-uri-encode r2-canonical-query r2-sign-request)+5
(begin+6
(define hex "0123456789ABCDEF")+7
(define (r2-uri-encode value (keys: (preserve-slashes? #f)))+8
(let ((bytes (string->utf8 value)))+9
(let loop ((i 0) (out '()))+10
(if (= i (bytevector-length bytes)) (string-join (reverse out) "")+11
(let ((b (bytevector-u8-ref bytes i)))+12
(loop (+ i 1)+13
(cons (if (or (<= 65 b 90) (<= 97 b 122) (<= 48 b 57)+14
(member b '(45 46 95 126)) (and preserve-slashes? (= b 47)))+15
(string (integer->char b))+16
(string #\% (string-ref hex (quotient b 16)) (string-ref hex (modulo b 16)))) out)))))))+17
(define (r2-canonical-query query)+18
(string-join+19
(map (lambda (p) (string-append (car p) "=" (cdr p)))+20
(list-sort (lambda (a b) (or (string<? (car a) (car b))+21
(and (string=? (car a) (car b)) (string<? (cdr a) (cdr b)))))+22
(map (lambda (p) (cons (r2-uri-encode (car p)) (r2-uri-encode (cdr p)))) query))) "&"))+23
(define (header-value value)+24
(unless (and (string? value)+25
(not (string-contains? value "\r")) (not (string-contains? value "\n")))+26
(error "Invalid signing header value"))+27
(let loop ((chars (string->list value)) (out '()) (space? #f))+28
(cond ((null? chars) (list->string (reverse out)))+29
((or (char=? (car chars) #\space) (char=? (car chars) #\tab))+30
(loop (cdr chars) out (not (null? out))))+31
(else (loop (cdr chars)+32
(cons (car chars) (if space? (cons #\space out) out)) #f)))))+33
(define (normalize-headers headers)+34
(let loop ((entries headers) (out '()))+35
(if (null? entries) (list-sort (lambda (a b) (string<? (car a) (car b))) out)+36
(let* ((p (car entries)) (name (string-downcase (car p))))+37
(unless (and (> (string-length name) 0)+38
(every (lambda (c) (or (and (char<=? #\a c) (char<=? c #\z)) (and (char<=? #\0 c) (char<=? c #\9)) (char=? c #\-))) (string->list name)))+39
(error "Invalid signing header name"))+40
(when (assoc name out) (error "Duplicate signing header"))+41
(loop (cdr entries) (cons (cons name (header-value (cdr p))) out))))))+42
;; Result contains signed headers and canonical details: it is sensitive and+43
;; must never be logged. A region override supports official AWS test vectors.+44
(define (r2-sign-request method path query headers payload access-key secret-key timestamp+45
(keys: (region "auto")))+46
(unless (and (= (string-length timestamp) 16)+47
(char=? (string-ref timestamp 8) #\T) (char=? (string-ref timestamp 15) #\Z)+48
(every char-numeric? (append (string->list (substring timestamp 0 8))+49
(string->list (substring timestamp 9 15)))))+50
(error "Invalid signing timestamp"))+51
(let* ((body-hash (sha256 payload))+52
(base (normalize-headers headers)))+53
(unless (assoc "host" base) (error "Signing requires host header"))+54
(when (or (assoc "authorization" base) (assoc "x-amz-date" base) (assoc "x-amz-content-sha256" base))+55
(error "Reserved signing header"))+56
(let* ((signed (normalize-headers (append base+57
(list (cons "x-amz-date" timestamp) (cons "x-amz-content-sha256" body-hash)))))+58
(names (string-join (map car signed) ";"))+59
(uri (r2-uri-encode path preserve-slashes?: #t))+60
(qs (r2-canonical-query query))+61
(canonical (string-append (symbol->string method) "\n" uri "\n" qs "\n"+62
(apply string-append (map (lambda (p) (string-append (car p) ":" (cdr p) "\n")) signed))+63
"\n" names "\n" body-hash))+64
(date (substring timestamp 0 8))+65
(scope (string-append date "/" region "/s3/aws4_request"))+66
(to-sign (string-append "AWS4-HMAC-SHA256\n" timestamp "\n" scope "\n" (sha256 canonical)))+67
(key (hmac-sha256-bytes+68
(hmac-sha256-bytes+69
(hmac-sha256-bytes+70
(hmac-sha256-bytes (string-append "AWS4" secret-key) date) region) "s3") "aws4_request"))+71
(signature (hmac-sha256 key to-sign))+72
(authorization (string-append "AWS4-HMAC-SHA256 Credential=" access-key "/" scope+73
", SignedHeaders=" names ", Signature=" signature)))+74
#{ headers: (cons (cons "authorization" authorization) signed)+75
canonical-request: canonical signature: signature path: uri query: qs })))))test/http.mjsadded
@@ -0,0 +1,67 @@
+1
import http from 'node:http';+2
import assert from 'node:assert/strict';+3
import { createHash, createHmac } from 'node:crypto';+4
import { spawn } from 'node:child_process';+5
+6
const hash = data => createHash('sha256').update(data).digest('hex');+7
const hmac = (key, data) => createHmac('sha256', key).update(data).digest();+8
const objects = new Map();+9
let requests = 0;+10
let failure;+11
const server = http.createServer(async (req, res) => {+12
try {+13
const chunks = [];+14
for await (const chunk of req) chunks.push(chunk);+15
const body = Buffer.concat(chunks);+16
requests++;+17
const auth = req.headers.authorization;+18
const match = /^AWS4-HMAC-SHA256 Credential=TESTACCESS\/(\d{8})\/auto\/s3\/aws4_request, SignedHeaders=([^,]+), Signature=([a-f0-9]{64})$/.exec(auth);+19
assert.ok(match, 'well-formed R2 authorization');+20
assert.equal(req.rawHeaders.filter(x => x.toLowerCase() === 'host').length, 1);+21
assert.equal(req.headers['x-amz-content-sha256'], hash(body));+22
const names = match[2].split(';');+23
const headers = names.map(name => `${name}:${req.headers[name]}\n`).join('');+24
const canonical = `${req.method}\n${req.url}\n\n${headers}\n${match[2]}\n${hash(body)}`;+25
const scope = `${match[1]}/auto/s3/aws4_request`;+26
const toSign = `AWS4-HMAC-SHA256\n${req.headers['x-amz-date']}\n${scope}\n${hash(canonical)}`;+27
const key = hmac(hmac(hmac(hmac('AWS4test-secret', match[1]), 'auto'), 's3'), 'aws4_request');+28
assert.equal(hmac(key, toSign).toString('hex'), match[3], 'independently verified signature');+29
if (req.url === '/test-assets/redirect') {+30
res.writeHead(307, { location: `http://127.0.0.1:${server.address().port}/must-not-follow` });+31
return res.end();+32
}+33
if (req.url === '/test-assets/denied') { res.writeHead(403); return res.end('AccessDenied'); }+34
if (req.url === '/test-assets/truncated') {+35
res.writeHead(200, { 'content-length': '10' }); return res.end('short');+36
}+37
assert.equal(req.url, '/test-assets/logos/%C3%A9%20%2B%25%E9%9B%AA.png');+38
if (req.method === 'PUT') {+39
assert.equal(req.headers['content-length'], '65536');+40
assert.equal(req.headers['content-type'], 'image/png');+41
assert.equal(req.headers['cache-control'], 'public, max-age=3600');+42
assert.deepEqual(body, Buffer.from(Array.from({ length: 65536 }, (_, i) => i % 256)));+43
objects.set(req.url, body);+44
res.writeHead(200, { etag: '"test-etag"', 'content-length': '0' }); return res.end();+45
}+46
if (req.method === 'DELETE') { objects.delete(req.url); res.writeHead(204); return res.end(); }+47
if (!objects.has(req.url)) { res.writeHead(404); return res.end('NoSuchKey'); }+48
res.writeHead(200, { 'content-length': String(objects.get(req.url).length), 'content-type': 'image/png' });+49
res.end(req.method === 'HEAD' ? undefined : objects.get(req.url));+50
} catch (error) {+51
failure ??= error;+52
res.writeHead(500); res.end('Fake service assertion failed');+53
}+54
});+55
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+56
try {+57
const child = spawn('sigil', ['test', '--sgl', '--strict', ...process.argv.slice(2)], {+58
stdio: 'inherit', env: { ...process.env, R2_TEST_PORT: String(server.address().port) },+59
});+60
const timeout = setTimeout(() => child.kill('SIGTERM'), 180_000);+61
const code = await new Promise((resolve, reject) => { child.once('error', reject); child.once('exit', resolve); });+62
clearTimeout(timeout);+63
if (failure) throw failure;+64
assert.equal(code, 0, 'Sigil tests passed');+65
assert.equal(requests, 8, 'no redirects followed and no automatic retries');+66
console.log('R2 fake-service checks passed: byte-exact upload/download, signatures, metadata, deletion and failures.');+67
} finally { server.closeAllConnections(); server.close(); }test/test-network.sgladded
@@ -0,0 +1,23 @@
+1
(import (sigil core) (sigil test) (sigil process) (sigil crypto) (cloudflare r2))+2
;; test/http.mjs supplies a loopback-only fake service and independently checks+3
;; signatures, raw bodies and methods. No real credentials or Cloudflare calls.+4
(when (getenv "R2_TEST_PORT")+5
(test-group "R2 HTTP boundary"+6
(test "binary PUT/GET/HEAD/DELETE and provider failures"+7
(let* ((client (r2-client "0123456789abcdef0123456789abcdef" "TESTACCESS" "test-secret"+8
"test-assets" test-port: (string->number (getenv "R2_TEST_PORT")) timeout: 2))+9
(key "logos/é +%雪.png")+10
(bytes (make-bytevector 65536)))+11
(let loop ((i 0)) (when (< i 65536) (bytevector-u8-set! bytes i (modulo i 256)) (loop (+ i 1))))+12
(assert-equal (dict-ref (r2-put-object client key bytes content-type: "image/png" cache-control: "public, max-age=3600") status:) 200)+13
(let ((got (r2-get-object client key)))+14
(assert-equal (dict-ref got status:) 200)+15
(assert-equal (sha256 (dict-ref got body:)) (sha256 bytes)))+16
(let ((head (r2-head-object client key)))+17
(assert-equal (dict-ref head status:) 200)+18
(assert-equal (bytevector-length (dict-ref head body:)) 0))+19
(assert-equal (dict-ref (r2-delete-object client key) status:) 204)+20
(assert-equal (dict-ref (r2-get-object client key) status:) 404)+21
(assert-equal (dict-ref (r2-get-object client "redirect") status:) 307)+22
(assert-equal (dict-ref (r2-get-object client "denied") status:) 403)+23
(assert-false (r2-get-object client "truncated"))))))test/test-signing.sgladded
@@ -0,0 +1,36 @@
+1
(import (sigil core) (sigil test) (sigil crypto) (cloudflare r2) (cloudflare r2 signing))+2
(define access "AKIAIOSFODNN7EXAMPLE")+3
(define secret "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")+4
(test-group "R2 SigV4"+5
(test "official AWS S3 GET range signature"+6
(let ((r (r2-sign-request 'GET "/test.txt" '()+7
'(("Host" . "examplebucket.s3.amazonaws.com") ("Range" . "bytes=0-9"))+8
"" access secret "20130524T000000Z" region: "us-east-1")))+9
(assert-equal (sha256 (dict-ref r canonical-request:)) "7344ae5b7ee6c3e7e6b0fe0640412a37625d1fbfff95c48bbb2dc43964946972")+10
(assert-equal (dict-ref r signature:) "f0e8bdb87c964420e857bd35b5d6ed310bd44f0170aba48dd91039c6036bdb41")))+11
(test "official AWS S3 lifecycle query signature"+12
(let ((r (r2-sign-request 'GET "/" '(("lifecycle" . ""))+13
'(("host" . "examplebucket.s3.amazonaws.com"))+14
"" access secret "20130524T000000Z" region: "us-east-1")))+15
(assert-equal (dict-ref r signature:) "fea454ca298b7da1c68078a5d1bdbfbbe0d65c699e0f91ac7a200a0136783543")))+16
(test "UTF-8 path encoding preserves slashes and dot segments"+17
(assert-equal (r2-uri-encode "/logos//../é +%?雪.png" preserve-slashes?: #t)+18
"/logos//../%C3%A9%20%2B%25%3F%E9%9B%AA.png"))+19
(test "query sorting occurs after encoding and preserves duplicate keys"+20
(assert-equal (r2-canonical-query '(("z" . "") ("a" . "z") ("a" . "+") ("é" . "x")))+21
"%C3%A9=x&a=%2B&a=z&z="))+22
(test "maximum-length key does not exceed variadic call limits"+23
(assert-equal (string-length (r2-uri-encode (make-string 1024 #\space))) 3072))+24
(test "header spaces collapse and names lowercase"+25
(let ((a (r2-sign-request 'GET "/" '() '(("Host" . "example.com") ("X-Test" . " a \t b ")) "" access secret "20130524T000000Z"))+26
(b (r2-sign-request 'GET "/" '() '(("host" . "example.com") ("x-test" . "a b")) "" access secret "20130524T000000Z")))+27
(assert-equal (dict-ref a signature:) (dict-ref b signature:))))+28
(test "header injection and duplicate headers fail before network"+29
(assert-error (r2-sign-request 'GET "/" '() '(("host" . "x\r\ny")) "" access secret "20130524T000000Z"))+30
(assert-error (r2-sign-request 'GET "/" '() '(("host" . "x") ("Host" . "x")) "" access secret "20130524T000000Z")))+31
(test "public custom domain is separate from API bucket path"+32
(let ((c (r2-client "0123456789abcdef0123456789abcdef" access secret "rezvibe-assets" public-base-url: "https://assets.rezvibe.com")))+33
(assert-equal (r2-public-url c "logos/é.png") "https://assets.rezvibe.com/logos/%C3%A9.png")))+34
(test "invalid client configuration fails locally"+35
(assert-error (r2-client "bad" access secret "rezvibe-assets"))+36
(assert-error (r2-client "0123456789abcdef0123456789abcdef" access secret "../wrong"))))