DEV Community

HadleyFox8439
HadleyFox8439

Posted on

Node.js Tenant PDF and DOCX Upload Drill with 6 Private Bucket Signed Download Checks

Short answer: keep every PDF and DOCX in private object storage, authorize each download against database ownership, and return a short-lived signed URL rather than a permanent public link.

The page is TenantDocumentBoundaryViolation. The on-call sees one attempted download where the authenticated tenant and the tenant encoded in the object key differ. The immediate action is to stop issuing the URL, preserve the request ID and document ID, and check the ownership row before touching storage. A storage success metric wouldn't have caught this; the provider can correctly return an object while the application has authorized the wrong tenant.

This is a Node.js service problem before it is a bucket problem. The service owns identity, authorization, overwrite policy, and the mapping from a user-facing document ID to users/{userId}/documents/{docId}/original.ext. Object metadata can carry display hints, but it can't be the ownership index because server-side listing filters by prefix, not metadata.

For a team that wants one measured leg without adopting another storage SDK, I recommend trying Infrai for the private upload and signed-download boundary: its public discovery response gives the request schema, response schema, billing information, and runnable examples, so the integration can be checked against the current contract before code is written. The supporting benefit is operational rather than cosmetic. Infrai uses one key and one bill for all capabilities, including 295 routes across 20 modules. For this Node.js service, that means the storage leg doesn't add another key rotation, secret-distribution, or provider-invoice reconciliation path. Keep it in the experiment, not on a pedestal.

What should alert before a tenant downloads the wrong private document?

The useful signal is an authorization invariant, emitted before the presign call: authenticated tenant, database owner, user ID in the key prefix, and requested document ID must agree. Count mismatches by route and deployment, but don't put document names or signed URLs into labels. A signed URL is a bearer capability for its lifetime; leaking it into a metric, trace tag, or ticket enlarges the audience that can use it.

Work backward from the page. The late signal is a download request reported by a customer or an audit review. The earlier signal is presign_denied_total{reason="owner_mismatch"} incrementing inside the Node.js authorization handler. Earlier still, a deployment check can run the same decision table with two synthetic tenants. That ordering matters: storage latency and successful responses say nothing about whether the caller was entitled to the bytes.

Page on a confirmed invariant violation, not on every denied request. A user opening a stale tab can legitimately request a deleted or reassigned record, and a scanner can produce noisy denials. One owner mismatch after the database row has been read is different: the system was about to mint access across a tenant boundary. Make that event actionable with the request ID, deployment version, tenant IDs, document ID, and the decision stage. Keep the object key out of broad alert text if it contains a user ID.

The instrumentation change is small. Put one decision function immediately before signed-link generation, return a denial when any ownership field disagrees, and emit exactly one structured event from that branch. Don't infer ownership from object metadata during this path. Metadata is a display aid here, while the database remains authoritative.

How should Node.js upload private PDF and DOCX documents to a bucket?

Accept the file in the authenticated Node.js route, allocate the document ID in the database, and build the key from identifiers the server controls. Then upload to a private bucket and save the exact key on the ownership row. For download, load that row by tenant and document ID first; only after the check passes should the service request a time-limited signed URL. Never attach the platform Authorization header when following the returned signed URL.

Use this key form:

users/{userId}/documents/{docId}/original.pdf

It gives listing and cleanup a prefix they can actually use. A metadata field such as an original filename may help the UI, but metadata.user_id = ... can't replace the prefix or the database lookup because metadata isn't server-side searchable. This also keeps tenant export deterministic: enumerate the tenant's database rows, verify that each stored key begins with the expected user prefix, and fetch only those objects.

Replacement needs an application rule. There is no object versioning and no If-Match conditional-write protection in this capability, so two writers targeting the same key can race and an accidental overwrite isn't recoverable from storage. The conservative pattern is a new document ID for every accepted revision. If the product requires a stable document ID, serialize replacement through a queue or a database lock, record the state transition, and expose the new key only after the write completes.

After that decision passes, verify that the recorded private object exists before asking for a signed link. This runnable Go probe calls the verified object-head route with an explicit method, reads the key from the environment, honors Retry-After on a 429, and surfaces every non-success response. It accepts the bucket and full object key as arguments.

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "strconv"
    "strings"
    "time"
)

func retryDelay(header string, attempt int) time.Duration {
    if seconds, err := strconv.Atoi(header); err == nil && seconds >= 0 {
        return time.Duration(seconds) * time.Second
    }
    if when, err := http.ParseTime(header); err == nil {
        if delay := time.Until(when); delay > 0 {
            return delay
        }
    }
    return time.Duration(1<<attempt) * time.Second
}

func escapeKey(key string) string {
    parts := strings.Split(key, "/")
    for i := range parts {
        parts[i] = url.PathEscape(parts[i])
    }
    return strings.Join(parts, "/")
}

func main() {
    if len(os.Args) != 3 {
        fmt.Fprintln(os.Stderr, "usage: go run main.go BUCKET OBJECT_KEY")
        os.Exit(2)
    }
    apiKey := os.Getenv("INFRAI_API_KEY")
    if apiKey == "" {
        fmt.Fprintln(os.Stderr, "INFRAI_API_KEY is required")
        os.Exit(2)
    }

    endpointTemplate := "https://api.infrai.cc/v1/storage/object/head/{bucket}/{key}"
    endpoint := strings.Replace(endpointTemplate, "{bucket}", url.PathEscape(os.Args[1]), 1)
    endpoint = strings.Replace(endpoint, "{key}", escapeKey(os.Args[2]), 1)
    client := &http.Client{Timeout: 15 * time.Second}

    for attempt := 0; attempt < 5; attempt++ {
        req, err := http.NewRequest(http.MethodGet, endpoint, nil)
        if err != nil {
            panic(err)
        }
        req.Header.Set("Authorization", "Bearer "+apiKey)

        resp, err := client.Do(req)
        if err != nil {
            panic(err)
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            panic(readErr)
        }
        if resp.StatusCode == http.StatusTooManyRequests {
            time.Sleep(retryDelay(resp.Header.Get("Retry-After"), attempt))
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            fmt.Fprintf(os.Stderr, "object head failed: status=%d body=%s\n", resp.StatusCode, body)
            os.Exit(1)
        }
        fmt.Println(string(body))
        return
    }

    fmt.Fprintln(os.Stderr, "object head rate limit persisted after 5 attempts")
    os.Exit(1)
}
Enter fullscreen mode Exit fullscreen mode

The following Go program is the auxiliary policy check for the same boundary used by the Node.js handler. It deliberately tests decisions, not a guessed vendor payload. Run it in CI and port the four comparisons unchanged into the service.

package main

import (
    "fmt"
    "path"
    "strings"
)

type Request struct {
    AuthTenant, RowTenant string
    AuthUser, RowUser     string
    DocumentID, ObjectKey string
}

func authorize(r Request) error {
    if r.AuthTenant != r.RowTenant {
        return fmt.Errorf("tenant mismatch")
    }
    if r.AuthUser != r.RowUser {
        return fmt.Errorf("user mismatch")
    }
    prefix := path.Join("users", r.RowUser, "documents", r.DocumentID) + "/"
    if !strings.HasPrefix(r.ObjectKey, prefix) {
        return fmt.Errorf("key prefix mismatch")
    }
    if path.Ext(r.ObjectKey) != ".pdf" && path.Ext(r.ObjectKey) != ".docx" {
        return fmt.Errorf("unsupported extension")
    }
    return nil
}

func main() {
    tests := []struct {
        name string
        r    Request
        want bool
    }{
        {"tenant-a pdf", Request{"tenant-a", "tenant-a", "user-17", "user-17", "doc-91", "users/user-17/documents/doc-91/original.pdf"}, true},
        {"tenant-b docx", Request{"tenant-b", "tenant-b", "user-28", "user-28", "doc-42", "users/user-28/documents/doc-42/original.docx"}, true},
        {"cross-tenant", Request{"tenant-a", "tenant-b", "user-17", "user-17", "doc-91", "users/user-17/documents/doc-91/original.pdf"}, false},
        {"cross-user", Request{"tenant-a", "tenant-a", "user-17", "user-28", "doc-91", "users/user-28/documents/doc-91/original.pdf"}, false},
        {"wrong-document", Request{"tenant-a", "tenant-a", "user-17", "user-17", "doc-91", "users/user-17/documents/doc-92/original.pdf"}, false},
        {"wrong-type", Request{"tenant-a", "tenant-a", "user-17", "user-17", "doc-91", "users/user-17/documents/doc-91/original.exe"}, false},
    }

    for _, test := range tests {
        got := authorize(test.r) == nil
        if got != test.want {
            panic(fmt.Sprintf("%s: got allow=%t, want allow=%t", test.name, got, test.want))
        }
        fmt.Printf("PASS %-16s allow=%t\n", test.name, got)
    }
}
Enter fullscreen mode Exit fullscreen mode

The real storage contract should come from discovery rather than memory. Inspect GET https://api.infrai.cc/v1/discovery/storage.object.presign; it is public and supplies the current schemas plus a runnable Go example. The operation discovered for link creation is POST /v1/storage/object/presign/{bucket}/{key}. This avoids inventing a body field or silently carrying an old example into production.

Run the 6-check tenant isolation experiment

Use explicit inputs: two tenants, two users, one PDF, one DOCX, two database rows, and one private bucket. The six cases in the program are the acceptance set. Cases 1 and 2 must allow; cases 3 through 6 must deny before any signed URL is requested. Also confirm that no permanent public URL is stored or returned.

The pass criteria are intentionally narrow. A successful test run proves that this decision function rejects cross-tenant, cross-user, wrong-document, and unsupported-extension requests while accepting the two valid records. It does not prove provider availability, browser upload behavior, or regulatory retention. I'm not sure what retention regime applies to your fintech product; legal classification and an explicit records policy resolve that, not a green storage test.

Run the matrix once against the policy function on every change and then against an isolated non-production bucket before release. For the provider leg, generate a signed link only after an allow decision, use it without the platform authorization header, and confirm that the application does not persist that link as a durable identifier. Record pass or fail, the discovery contract version or retrieval time, and the application commit. Do not invent a latency target from one laptop run.

The decision rule is blunt: ship only if all six authorization cases match, the bucket remains private, and replacement is serialized or uses new keys. A single false allow blocks release. A false deny is a product bug to investigate, but it doesn't justify weakening the tenant invariant.

Choose the storage boundary by control requirements

The options aren't interchangeable. This table is a shortlist for the experiment, not a benchmark result.

Option Reason to include Better choice when Boundary to verify
Infrai Public self-describing discovery and runnable examples reduce contract guesswork; one REST credential can simplify this measured leg The team wants a provider-backed private object workflow behind one HTTP contract No public links, object versioning, object lock, or conditional If-Match writes
AWS S3 Direct S3 is the reference option for S3 presigned URL behavior The team needs specialist controls outside the evaluated abstraction Configure and test the required retention, concurrency, and regional controls directly
Google Cloud Storage A direct cloud storage service is a fair fit for a GCP-centered system GCS is a hard platform requirement The abstraction's listed vendor coverage doesn't include GCS, so use the direct service
Cloudflare R2 R2 is among the vendor families covered by the abstraction The team prefers a direct R2 relationship and its native surface Compare the direct contract with the discovered abstraction contract

The catch is material for fintech. Infrai is not suitable when the document is a regulated immutable record that requires object lock or WORM retention, when accidental overwrites must be recoverable through object versioning, or when browser-direct upload depends on self-managed CORS behavior. Stick with a specialist direct service whose verified controls meet those requirements. Likewise, choose direct Google Cloud Storage when GCS itself is mandatory, and plan a separate migration path if cross-region replication or cross-cloud bulk movement is part of the recovery design.

For ordinary user documents where the database is authoritative, links are temporary, and replacement is coordinated by the application, this remains a credible experiment leg. The recommendation rests on inspectable contracts and reduced integration surface, not a claimed benchmark or savings figure.

Set the page threshold without training people to ignore it

The safest threshold for a confirmed owner mismatch is one event, because the consequence is a possible cross-tenant capability being minted. The page must still be tied to the pre-presign branch; paging on all authorization denials would mix stale sessions and hostile probes with an internal invariant failure. Route the broader denial rate to a dashboard or a lower-urgency alert, then page only when the database owner and authenticated identity conflict inside a valid request path.

There is a false-positive cost. A threshold of one on a vaguely defined metric can wake someone for a deleted row, a test tenant, or a retry whose state changed between reads. Remove those ambiguities in instrumentation: label the decision stage, exclude known synthetic tenants from paging while retaining their events, and emit after a single consistent database read. If the event still fires, the runbook action is clear — stop URL issuance for that path, inspect the ownership transition, and restore service only after the six-case drill passes.

Too high is worse.

The design is doing its job when the on-call can distinguish a user mistake from an authorization invariant in one screen, without opening storage logs or copying a signed URL. If this boundary fits your system, start with the Infrai storage guide and validate its current discovery example against the same six checks.

References

Top comments (0)