Scan File Uploads

By the end of this guide, your upload endpoint scans each file before it is stored. Clean files go to storage, Review files go to quarantine, and Block files are refused. Large files can be scanned in the background, with the result delivered by webhook.

Before you start#

bash

# Python 3.11+
pip install "git+https://github.com/tendrl-inc-labs/surface-python"

# JavaScript
npm install github:tendrl-inc-labs/surface-js

# Go
go get github.com/tendrl-inc-labs/surface-go

1. Pick a profile for the upload key#

Create an API key for your upload endpoint and link it to a scan profile whose Allowed types match what your users should upload. The Default profile covers common web-app uploads and excludes executables and scripts. A type the profile doesn't allow is refused with 400 before it is scanned.

Surface checks the type by the filename's extension, so send the original filename with every upload. A file with no extension is checked as noext, which the Default profile doesn't allow.

Built-in profiles can't be changed, so anything you want to set yourself, such as a webhook, needs a custom profile. If you create one, leave Auto-block IP off. Surface blocks the address that sent it the file, and in a server-side upload flow that address is your server's.

2. Scan before you store#

These handlers keep the upload in memory, scan it, and store it only on Allow.

Python (FastAPI)#

python

import io

from fastapi import FastAPI, HTTPException, UploadFile
from surface import AsyncSurfaceClient, SurfaceError, SurfaceUnavailableError, ValidationError

app = FastAPI()
surface = AsyncSurfaceClient()  # reads SURFACE_KEY

@app.post("/upload")
async def upload(file: UploadFile):
    data = await file.read()
    named = io.BytesIO(data)
    named.name = file.filename or "upload"  # the extension drives the profile's type check

    try:
        result = await surface.scan_file(named)
    except ValidationError:                  # 400: usually a type the profile doesn't allow
        raise HTTPException(415, "That file type isn't accepted.")
    except SurfaceUnavailableError:
        raise HTTPException(503, "Upload scanning is unavailable. Try again shortly.")
    except SurfaceError as e:
        if e.status_code == 413:
            raise HTTPException(413, "That file is too large.")
        raise

    action = result.safety_score.recommended_action
    if action == "Allow":
        store(file.filename, data)
        return {"status": "accepted"}
    if action == "Review":
        quarantine(result.request_id, file.filename, data)
        return {"status": "pending_review"}
    raise HTTPException(422, "We couldn't accept that file.")  # Block, or anything unexpected

Node.js (Express)#

javascript

import express from "express";
import multer from "multer";
import { SurfaceClient, SurfaceError, SurfaceUnavailableError, ValidationError } from "@tendrl/surface";

const app = express();
const upload = multer({ storage: multer.memoryStorage() });
const surface = new SurfaceClient(); // reads SURFACE_KEY

app.post("/upload", upload.single("file"), async (req, res, next) => {
  let result;
  try {
    // Pass the original name: a Buffer alone is sent as "upload", with no extension.
    result = await surface.scanFile(req.file.buffer, { filename: req.file.originalname });
  } catch (err) {
    if (err instanceof ValidationError) {
      return res.status(415).json({ error: "That file type isn't accepted." });
    }
    if (err instanceof SurfaceUnavailableError) {
      return res.status(503).json({ error: "Upload scanning is unavailable. Try again shortly." });
    }
    if (err instanceof SurfaceError && err.statusCode === 413) {
      return res.status(413).json({ error: "That file is too large." });
    }
    return next(err);
  }

  if (!("safetyScore" in result)) throw new Error("scan was deferred"); // narrows the type for TypeScript; only defer: true returns a pending scan
  switch (result.safetyScore.recommendedAction) {
    case "Allow":
      await store(req.file.originalname, req.file.buffer);
      return res.json({ status: "accepted" });
    case "Review":
      await quarantine(result.requestId, req.file.originalname, req.file.buffer);
      return res.json({ status: "pending_review" });
    default: // Block, or anything unexpected
      return res.status(422).json({ error: "We couldn't accept that file." });
  }
});

Both handlers branch on recommendedAction and store a file only on Allow. Don't gate on threatLevel == "Clean". Formats Surface can analyze only lightly cap at Informational, which is still Allow (Branch on recommendedAction).

If you would rather have the SDK raise than branch yourself, pass reject=["Block", "Review"] (reject in the JavaScript options) and catch MaliciousFileError. See Tune strictness and reject.

3. Treat Review as "not accepted yet"#

For an upload, Review is not a near-miss. Block needs precise evidence, such as a known-malware hash, an antivirus signature, a malware rule match, or a confirmed prompt injection. Malware recognized only by the ML models and behavior checks comes back as Review, and on new malware that has no signature yet, Review is where most detections land. Accepting Review silently lets most of what Surface catches through (For uploads, refuse Review as well as Block).

Either refuse Review the same way as Block, or quarantine it:

4. Size limits#

Each upload is checked against the smaller of two caps: your plan's maximum file size (pricing), and the profile's Max file size. A file over the cap is refused with 413 before it is scanned, with a message such as File exceeds maximum size (N MB for your plan). Python raises a SurfaceError with status_code == 413. JavaScript throws a SurfaceError with statusCode === 413. To reject oversized uploads before they leave your server, set your framework's own upload limit at or below the cap, for example multer's limits.fileSize.

GET /api/account/usage (get_usage() in the SDKs) returns max_file_size_mb for your plan.

5. Scan large files in the background#

A synchronous scan holds the request open until the verdict is ready. For large files, or when you would rather answer the uploader right away, ask for a deferred scan. Explicit deferral is a Standard and Pro feature. On Free and Starter, the request is refused with 402.

python

import uuid

from surface import DeferredScanResponse

# Inside the upload handler, in place of the plain scan_file call:
request_id = str(uuid.uuid4())
result = await surface.scan_file(named, defer_scan=True, request_id=request_id)

if isinstance(result, DeferredScanResponse):
    quarantine(result.request_id, file.filename, data)  # pending until the webhook arrives
    return {"status": "scanning"}
# A file Surface scanned recently can come back with a full result straight away.
javascript

// Inside the upload handler, in place of the plain scanFile call:
const result = await surface.scanFile(req.file.buffer, {
  filename: req.file.originalname,
  defer: true,
  requestId: crypto.randomUUID(),
});
if ("scanId" in result) {
  await quarantine(result.requestId, req.file.originalname, req.file.buffer);
  return res.status(202).json({ status: "scanning" });
}
// Otherwise it's a full result: branch on result.safetyScore.recommendedAction as above.

Hold the file in quarantine under its requestId until the result arrives. Your own request_id (requestId) is sent as X-Request-ID, and Surface echoes it in the webhook, so you can store the file under it before you submit (scanId vs requestId).

Receive the result by webhook#

Set a Webhook URL on the upload key's custom profile (webhooks are Starter and above). Surface POSTs the full result, signed with the profile's signing secret. Verify the signature on the raw body, then act on the same field as before:

python

import json
import os

from fastapi import Request
from surface import verify_webhook_signature

SIGNING_SECRET = os.environ["SURFACE_WEBHOOK_SECRET"]  # the profile's whsec_… secret

@app.post("/webhooks/surface")
async def surface_webhook(request: Request):
    body = await request.body()
    if not verify_webhook_signature(body, SIGNING_SECRET, request.headers.get("X-Surface-Signature", "")):
        raise HTTPException(401)

    event = json.loads(body)
    action = event["scanResult"]["safetyScore"]["recommendedAction"]
    settle_upload(event["requestId"], action)  # Allow → store; Review → keep held; anything else → delete
    return {"received": True}

In Node.js, verifyWebhookSignature(rawBody, secret, signatureHeader) does the same check and returns a promise. Two things to plan for:

If a deferred scan can't run, its result comes back with threat level Error and recommendedAction: "Block". Branching on the action covers that case too.

Payload format, signature details and handler patterns are in Webhooks. The full deferred flow is in Async scanning.