Dev › Gnuboard

Storing Gnuboard5 board attachments in S3 with presigned URLs

Store Gnuboard5 v5.6.58 attachments in private S3 with headObject checks, 5-minute presigned 302 downloads, image proxying, and GET_LOCK reference counting.

Storing Gnuboard5 board attachments in S3 with presigned URLs

Moving Gnuboard5 (v5.6.58) board attachments into a private S3 bucket shouldn’t break secret-post permissions, download point deductions, legacy local files, or post copy/delete synchronization. Here is how commit dc228c8f8 wires those constraints together, verified locally on PHP 8.5.13, MariaDB 11.8, and SeaweedFS 4.56.

Every code excerpt and test output in this post comes from Gnuboard5 v5.6.58 (public commit dc228c8f8) running in Docker Compose with php:8.5-apache-trixie, mariadb:11.8, and chrislusf/seaweedfs:4.56.

Why moving board attachments to private S3 breaks common assumptions

In running Gnuboard5 locally with Docker Compose and Dev Containers, a named gnuboard-data volume isolated data/ permissions on a single host. Once you run multiple web instances or stateless containers, though, board attachments under data/file/<bo_table>/ have to move to shared object storage.

Most quick S3 guides open the bucket publicly and serve direct URLs. That bypasses core Gnuboard5 rules: anyone with the link can download files from secret posts or member-only boards without triggering permission checks, point deductions, or bf_download counters. Locking the bucket down fixes access control, but introduces four new design problems: Docker internal vs. browser endpoint signing mismatches (SignatureDoesNotMatch), private image previews, concurrent copy/delete object cleanup, and coexistence with existing local files.

ApproachPrivate board ACL & pointsMulti-instance scalingMain trade-off
Local data/file/PHP checks and streams directlyNeeds shared disk (NFS/EFS)Disk coupling and backup overhead
Public S3 bucketBypassed once URL leaksHighCannot protect secret or restricted boards
Private S3 + presigned URL + image proxyPHP checks every download and imageHighRequires split endpoints, reference counting, and proxying

Schema-free hook integration and fail-closed uploads

Commit dc228c8f8 avoids database migrations by storing 'gnuboard_s3' in the existing g5_board_file.bf_storage (VARCHAR(50)) column. extend/board_s3.extend.php registers seven hooks across upload, download, image rendering, sharing, copying, and deletion:

1
2
3
4
5
6
7
8
9
10
// extend/board_s3.extend.php
include_once G5_PLUGIN_PATH.'/board-s3/storage.php';

add_replace('store_board_attachment', 'g5_board_s3_upload', G5_HOOK_DEFAULT_PRIORITY, 4);
add_replace('board_attachment_download_url', 'g5_board_s3_download_url', G5_HOOK_DEFAULT_PRIORITY, 2);
add_replace('board_attachment_image_url', 'g5_board_s3_image_url', G5_HOOK_DEFAULT_PRIORITY, 3);
add_event('board_attachment_send_image', 'g5_board_s3_send_image', G5_HOOK_DEFAULT_PRIORITY, 1);
add_replace('board_attachment_shared', 'g5_board_s3_is_shared', G5_HOOK_DEFAULT_PRIORITY, 2);
add_replace('board_attachment_copy_record', 'g5_board_s3_copy_record', G5_HOOK_DEFAULT_PRIORITY, 3);
add_event('board_attachment_unlinked', 'g5_board_s3_remove', G5_HOOK_DEFAULT_PRIORITY, 1);

On upload, g5_board_s3_upload() generates a 128-bit CSPRNG key (<bo_table>/<32hex>[.<ext>]) and writes it under <G5_TABLE_PREFIX>attachments/<relative_key>. It passes IfNoneMatch: '*' so S3 rejects accidental overwrites instead of clobbering an existing object:

1
2
3
4
5
6
7
8
9
10
11
// plugin/board-s3/storage.php (excerpt)
$relative_key = $board['bo_table'].'/'.bin2hex($bytes);
$extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
if (preg_match('/\A[a-z0-9]{1,12}\z/D', $extension)) $relative_key .= '.'.$extension;

g5_board_s3_client()->putObject(g5_board_s3_object($relative_key) + array(
    'SourceFile' => $tmp_file,
    'ContentType' => 'application/octet-stream',
    'IfNoneMatch' => '*',
));
return array('file' => $relative_key, 'storage' => 'gnuboard_s3');

bbs/write_update.php enforces a fail-closed policy: if the hook doesn’t return 'storage' => 'gnuboard_s3' or S3 fails, it rejects the upload instead of falling back to local disk. When replacing an attachment during post edits, the UPDATE uses optimistic concurrency control (WHERE ... AND bf_file = '$old_file' AND bf_storage = '$old_storage') and only unlinks the old object when get_sql_affected_rows() > 0. If the DB write fails, it cleans up the newly uploaded S3 object right away.

In local SeaweedFS 4.56 testing, uploading a Korean-named text file and a PNG wrote bf_storage='gnuboard_s3' and bf_file='free/<32hex>.<ext>' while leaving data/file/free/ empty. Re-uploading the same key with IfNoneMatch: '*' returned HTTP 412 PreconditionFailed. Stopping the s3 container blocked uploads with a storage error (저장소 설정을 확인해 주십시오.), leaving zero local files and zero DB rows.

SeaweedFS Admin UI showing 32-character hex attachment objects stored under gnuboard-dev/g5_attachments/free Figure 1. SeaweedFS Admin UI (v4.56, read-only viewer account) in local Docker Compose showing 32-hex attachment objects stored under gnuboard-dev/g5_attachments/free.

Permission checks, headObject validation, and split-endpoint 302 downloads

bbs/download.php runs every standard Gnuboard5 check—board read access, view session (ss_view_*), download nonce, and member level—before issuing a 5-minute presigned URL via HTTP 302:

sequenceDiagram
    participant Browser
    participant PHP as bbs/download.php
    participant S3 as S3 / SeaweedFS
    Browser->>PHP: GET download.php (session, nonce)
    PHP->>PHP: Check read ACL, level, nonce
    PHP->>S3: headObject (internal endpoint)
    S3-->>PHP: 200 OK (object exists)
    PHP->>PHP: Sign public URL, then deduct points & count
    PHP-->>Browser: 302 Found (no-store, no-referrer)
    Browser->>S3: GET presigned URL (public endpoint)
    S3-->>Browser: 200 OK (attachment, octet-stream)

Two details prevent real production bugs here:

  1. headObject before point deduction. bbs/download.php calls board_attachment_download_url before insert_point() and bf_download + 1. Inside g5_board_s3_download_url(), the internal client runs headObject first. When I deleted an object directly in SeaweedFS and triggered a download, PHP aborted before touching the user’s points (1080 -> 1080) or download counter (0 -> 0).
  2. Split internal and public endpoints. Inside Docker Compose, PHP reaches SeaweedFS at http://s3:8333, while the browser reaches http://127.0.0.1:8333. Because AWS SigV4 signs the Host header, a URL signed against s3:8333 fails in the browser with SignatureDoesNotMatch. g5_board_s3_client($public) keeps two cached clients: false uses G5_ATTACHMENT_S3_ENDPOINT, and true uses G5_ATTACHMENT_S3_PUBLIC_ENDPOINT.
1
2
3
4
5
6
7
8
9
10
11
// plugin/board-s3/storage.php (excerpt)
$object = g5_board_s3_object($file['bf_file']);
g5_board_s3_client()->headObject($object);
$client = g5_board_s3_client(true);
$filename = preg_replace('/[\x00-\x1f\x7f]/', '', $file['bf_source']);
$command = $client->getCommand('GetObject', $object + array(
    'ResponseContentDisposition' => "attachment; filename*=UTF-8''".rawurlencode($filename),
    'ResponseContentType' => 'application/octet-stream',
    'ResponseCacheControl' => 'private, no-store',
));
return (string)$client->createPresignedRequest($command, '+5 minutes')->getUri();

Local testing turned up a useful quirk in SeaweedFS 4.56 mini: even though putObject sent 'ContentType' => 'application/octet-stream', headObject returned extension-inferred MIME types (text/plain; charset=utf-8 for .txt and image/png for .png). Because the presigned URL explicitly passes ResponseContentType: application/octet-stream and ResponseContentDisposition, the actual browser response still arrived as a forced download. Setting ResponseContentType on the presigned request is mandatory when targeting S3-compatible backends.

When bbs/download.php receives the signed URL, it responds with Cache-Control: private, no-store, Referrer-Policy: no-referrer, and HTTP 302. Here are the captured headers from an isolated local run (port 18333, with signature and timestamps masked):

1
2
3
4
HTTP/1.1 302 Found
Cache-Control: private, no-store
Referrer-Policy: no-referrer
Location: http://127.0.0.1:18333/gnuboard-dev/g5_attachments/free/6ccfdce180939cd7f6fec944d33c9c4c.txt?response-content-disposition=attachment%3B%20filename%2A%3DUTF-8%27%27%25ED%2585%258C%25EC%258A%25A4%25ED%258A%25B8_%25EC%25B2%25A8%25EB%25B6%2580%25ED%258C%258C%25EC%259D%25BC.txt&response-content-type=application%2Foctet-stream&response-cache-control=private%2C%20no-store&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=gnuboard-dev%2F<date>%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=<timestamp>&X-Amz-SignedHeaders=host&X-Amz-Expires=300&X-Amz-Signature=<redacted>
1
2
3
4
5
HTTP/1.1 200 OK
Content-Type: application/octet-stream
Content-Disposition: attachment; filename*=UTF-8''%ED%85%8C%EC%8A%A4%ED%8A%B8_%EC%B2%A8%EB%B6%80%ED%8C%8C%EC%9D%BC.txt
Cache-Control: private, no-store
Content-Length: 78

Guest requests against a secret post were blocked without issuing a 302 URL. Meanwhile, legacy local rows (bf_storage = '') return false from g5_board_s3_is_shared(), so they coexist in the same board: bbs/download.php streams them directly with 200 OK, and post deletion removes only their local file under data/file/<bo_table>/.

Private image previews and on-demand thumbnail proxying

Inline post previews and gallery thumbnails can’t expose raw bucket URLs either. lib/common.lib.php and lib/thumbnail.lib.php route S3-backed images through bbs/attachment_image.php?bo_table=...&wr_id=...&no=...:

1
2
3
4
5
6
7
8
9
10
11
12
13
// bbs/attachment_image.php
http_response_code(404);
header('Cache-Control: private, no-store');
if (!g5_board_visible($board, true) || !g5_can_read_secret($board, $write)) exit;

$no = filter_input(INPUT_GET, 'no', FILTER_VALIDATE_INT, array('options' => array('min_range' => 0)));
if ($no === null || $no === false) exit;

$file = sql_fetch("SELECT * FROM {$g5['board_file_table']}
    WHERE bo_table = '$bo_table' AND wr_id = '".(int)$write['wr_id']."' AND bf_no = $no");
if (empty($file['bf_file'])) exit;

run_event('board_attachment_send_image', $file);

The script starts with 404 and Cache-Control: private, no-store, switching to 200 OK only after g5_board_visible() and g5_can_read_secret() pass. Unauthorized requests and missing files return the same empty 404 response.

Inside g5_board_s3_send_image(), three guardrails keep the proxy safe:

  • Strict response headers: Every image response sends Cache-Control: private, no-store, X-Content-Type-Options: nosniff, and Content-Security-Policy: default-src 'none'; sandbox to block MIME sniffing and script execution.
  • Bounded GD resizing: When width is requested, the image isn’t BMP, bf_width * bf_height <= 16,000,000 (16 MP), and bf_filesize <= 16,000,000 (16 MB), PHP downloads it into a 0700 temp directory, resizes up to 1600px, and deletes the directory in a finally block.
  • 64 KB chunked streaming fallback: Original requests and oversized images stream via getObject(['@http' => ['stream' => true]]) in 64 KB chunks to avoid buffering large files in PHP memory.

Local verification against a 640x480 PNG, a width=300&height=200&crop=1 thumbnail request, and a guest request on a secret post produced these results, with zero /tmp/g5-attachment-* directories left behind:

1
2
3
4
5
6
7
8
9
10
11
12
13
Original image status=200, dims=640x480, bytes=5078
  Content-Type: image/png
  Cache-Control: private, no-store
  X-Content-Type-Options: nosniff
  Content-Security-Policy: default-src 'none'; sandbox

Thumbnail image status=200, dims=300x200, bytes=10960
  Content-Type: image/png
  Cache-Control: private, no-store
  X-Content-Type-Options: nosniff
  Content-Security-Policy: default-src 'none'; sandbox

Secret image (guest) status=404, Cache-Control=private, no-store, body_len=0

Gnuboard5 post view rendering a 640x480 PNG preview via bbs/attachment_image.php alongside two downloadable attachment entries below Figure 2. Gnuboard5 board post view (Korean UI) in local Docker Compose rendering the private SeaweedFS PNG preview through bbs/attachment_image.php above the two attachment download links.

Shared object reference counting with MariaDB GET_LOCK

Gnuboard5 supports copying and moving posts (bbs/move_update.php) as well as duplicating entire boards (adm/board_copy_update.php). Rather than duplicating objects in S3, the plugin shares the same bf_file and bf_storage = 'gnuboard_s3' across copied rows.

Sharing keys means deletion can’t blindly call deleteObject: deleting the original post would break every copy, and a concurrent copy/delete could leave a DB row pointing at a deleted object. g5_board_s3_with_lock() serializes both operations using MariaDB GET_LOCK(..., 5) keyed on g5s3: plus the first 56 hex chars of sha256(G5_TABLE_PREFIX . ':' . bf_file).

flowchart TD
    Del["DB row DELETE fires unlinked event"] --> Lock["Acquire GET_LOCK (5s timeout)"]
    Lock --> Check{"0 rows left in g5_board_file?"}
    Check -->|"Yes (last ref)"| S3Del["Run S3 deleteObject"]
    Check -->|"No (copies remain)"| Keep["Keep S3 object"]
    S3Del --> Unlock["Run RELEASE_LOCK"]
    Keep --> Unlock
1
2
3
4
5
6
7
8
9
10
11
12
// plugin/board-s3/storage.php (excerpt)
function g5_board_s3_with_lock($file, $operation)
{
    $name = 'g5s3:'.substr(hash('sha256', G5_TABLE_PREFIX.':'.$file['bf_file']), 0, 56);
    $result = sql_fetch("SELECT GET_LOCK('$name', 5) AS acquired", false);
    if (empty($result['acquired'])) return false;
    try {
        return $operation();
    } finally {
        sql_query("DO RELEASE_LOCK('$name')", false);
    }
}

g5_board_s3_copy_record() re-checks inside the lock that the source row still exists before inserting the copy. On delete, core deletes the DB row first and fires board_attachment_unlinked; g5_board_s3_remove() acquires the lock and calls deleteObject only when no remaining g5_board_file rows reference that key. If the lock times out or S3 deletion fails, it logs [g5 board-s3] 객체 정리 필요: <bf_file> so an operator or batch job can clean up the orphan object.

In local E2E runs, copying a post from free to notice (sw=copy) created two rows sharing one key. Deleting the original kept the SeaweedFS object intact and the copy downloaded cleanly (302 -> 200 OK). Deleting the final copy removed the object (headObject returned 404 NotFound). Moving a post (sw=move) removed the source row while keeping the target row and S3 object alive.

Local verification with SeaweedFS 4.56 and production caveats

To test the full stack without an AWS account, compose.yaml adds a chrislusf/seaweedfs:4.56 mini service and wires web to wait for its /readyz health check:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# compose.yaml (S3 excerpt)
services:
  web:
    environment:
      G5_ATTACHMENT_S3_BUCKET: "${GNUBOARD_S3_BUCKET:-gnuboard-dev}"
      G5_ATTACHMENT_S3_ENDPOINT: "http://s3:8333"
      G5_ATTACHMENT_S3_PUBLIC_ENDPOINT: "http://127.0.0.1:${GNUBOARD_S3_PORT:-8333}"
      G5_ATTACHMENT_S3_ACCESS_KEY: "${GNUBOARD_S3_ACCESS_KEY:-gnuboard-dev}"
      G5_ATTACHMENT_S3_SECRET_KEY: "${GNUBOARD_S3_SECRET_KEY:-gnuboard-dev-secret}"
    depends_on:
      s3:
        condition: service_healthy

  s3:
    image: chrislusf/seaweedfs:4.56
    command:
      - mini
      - -dir=/data
      - -admin.allowInsecureBind=false
      - "-s3.allowedOrigins=http://127.0.0.1:${GNUBOARD_WEB_PORT:-8080}"
    ports:
      - "127.0.0.1:${GNUBOARD_S3_PORT:-8333}:8333"
      - "127.0.0.1:${GNUBOARD_S3_ADMIN_PORT:-12535}:12535"
    # environment (AWS_ACCESS_KEY_ID, S3_BUCKET, etc.) and volumes (s3-data:/data) omitted
    healthcheck:
      test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:8333/readyz"]
      interval: 5s
      timeout: 5s
      retries: 12
      start_period: 15s

.devcontainer/Dockerfile installs aws/aws-sdk-php 3.411.1 into /opt/gnuboard/board-s3/ via composer:2 and points G5_ATTACHMENT_S3_AUTOLOAD there, keeping vendor/ out of the bind-mounted source tree. .devcontainer/uploads.ini raises limits (upload_max_filesize = 100M, post_max_size = 210M, memory_limit = 256M), and plugin/board-s3/.htaccess (Require all denied) returned HTTP 403 Forbidden for both /plugin/board-s3/storage.php and /plugin/board-s3/composer.json.

For fast regression checks without a database or S3 container, tests/attachment.php exercises random-byte failures, key collisions, missing storage providers, and DB-failure rollbacks deterministically:

1
docker compose exec -T web php tests/attachment.php
1
PASS: 난수 소스, 파일명, 충돌, 저장 실패 및 두 업로드 경로의 교체·삭제

Scope and verification limits: This plugin covers board attachments only. Editor inline images (data/editor/), 1:1 Q&A attachments (bbs/qawrite_update.php), and bulk migration of legacy data/file/ files aren’t included. Because local runs used SeaweedFS 4.56 and PHP 8.5.13, four areas weren’t executed directly and need staging checks before production: AWS IAM Instance Profile/IRSA default credentials, the PHP 8.3 minimum runtime (composer.json platform 8.3.0), the >16 MP/>16 MB streaming fallback, and concurrent multi-client GET_LOCK load tests.

Before enabling this plugin in production, run through five checks:

  • Private bucket and prefix-scoped IAM: Block all public access on the bucket and restrict IAM permissions to PutObject, GetObject, and DeleteObject under <G5_TABLE_PREFIX>attachments/*. On EC2 or EKS, omit G5_ATTACHMENT_S3_ACCESS_KEY and G5_ATTACHMENT_S3_SECRET_KEY so the SDK uses the default credential chain.
  • Block /plugin/board-s3/ on non-Apache servers: .htaccess only protects Apache. On Nginx, add an explicit deny all; location rule for /plugin/board-s3/.
  • Verify PHP 8.3+ and SimpleXML: storage.php refuses to run below PHP_VERSION_ID 80300, and AWS SDK for PHP v3 requires SimpleXML for S3 XML responses.
  • Alert on orphan cleanup logs: Monitor PHP error logs for [g5 board-s3] 객체 정리 필요: to sweep objects left behind after lock timeouts or transient S3 outages.
  • Watch proxy load on high-traffic public galleries: bbs/attachment_image.php routes every image view through PHP and S3. If your site serves heavy public image galleries, place a caching layer or signed-cookie CDN in front instead of proxying every request through PHP.

References

그누보드5 (영카트 포함) 공개형 Git. Contribute to gnuboard/gnuboard5 development by creating an account on GitHub.
Learn how to create pre-signed URLs for Amazon S3 using the AWS SDK for PHP. Enable secure, time-limited access to S3 objects for HTTP GET and PUT requests without sharing AWS credentials.
conditional requests are included in header fields and test a precondition before doing some S3 operations.
SeaweedFS is a distributed storage system for object storage (S3), file systems, Iceberg table buckets, and Lance vector buckets, designed to handle billions of files with O(1) disk access and effo...
This post is licensed under CC BY 4.0 by the author.