> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hiddenlayer.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Scan models for security risks

> Use the HiddenLayer SDKs to scan model files and folders from local disk, Hugging Face, AWS S3, and Azure Blob Storage, and read the scan report.

Model scanning is part of HiddenLayer [AI Supply Chain Security](https://docs.hiddenlayer.ai/docs/products/supply-chain/overview.md). A scan inspects model files for security risks, such as malicious code embedded in a serialized model, before you load or deploy them. The SDK uploads your model to HiddenLayer (or asks HiddenLayer to fetch it), waits for the scan to finish, and returns a scan report.

Use model scanning when you:

* Download a third-party model and want to check it before loading it.
* Want to block risky models in a CI/CD pipeline.
* Need a record of scan results for models stored in Hugging Face, AWS S3, or Azure Blob Storage.

## Before you begin

* Install the SDK and configure credentials. See [Installation](https://docs.hiddenlayer.ai/docs/integrations/sdk/installation.md) and [Authentication and configuration](https://docs.hiddenlayer.ai/docs/integrations/sdk/authentication.md).
* Set `HIDDENLAYER_CLIENT_ID` and `HIDDENLAYER_CLIENT_SECRET` in your environment. Alternatively, set `HIDDENLAYER_TOKEN` to a bearer token. Every example on this page reads credentials from these variables. None of them hard-code secrets.
* Your tenant must have AI Supply Chain Security enabled, and your client credential needs permission to use it.

The Python and TypeScript SDKs include helpers that download a model from Hugging Face, S3, or Azure Blob Storage before they scan it. Those helpers need storage packages that the SDK does not install. Install them only if you use the matching helper. The Java SDK has no download helpers: download the model with your cloud provider's SDK and scan the downloaded file, or let HiddenLayer fetch it with the [community scanner](#scan-a-remote-model-with-the-community-scanner).

| Model location | Python packages | TypeScript packages | Java |
| - | - | - | - |
| Hugging Face | `huggingface_hub` | `@huggingface/hub` | Use the community scanner |
| AWS S3 | `boto3` | `@aws-sdk/client-s3` | Download with the AWS SDK for Java, then scan the file |
| Azure Blob Storage | `azure-identity` and `azure-storage-blob` | `@azure/storage-blob`, plus `@azure/identity` if you sign in with `DefaultAzureCredential` | Download with the Azure SDK for Java, then scan the file |

## Understand the scan report

Every scan method returns a scan report, typed as `ScanReportOfRecordV3`:

* **Python:** `hiddenlayer.ScanReportOfRecordV3`, a Pydantic model. Read fields as attributes, such as `report.status`. Don't use `hiddenlayer.ScanReport` for type hints: since version 4 it is a different type.
* **TypeScript:** `HiddenLayerApi.ScanReportOfRecordV3`, also exported as `ScanReport`. Fields keep the API's names, such as `report.summary.highest_severity`.
* **Java:** `com.hiddenlayer.api.types.ScanReportOfRecordV3`. Read fields with getters, such as `report.getSummary().getHighestSeverity()`. Optional fields return an `Optional`.

The fields you use most often are listed below by their API names:

| Field | Description |
| - | - |
| `scan_id` | Unique ID of the scan. Use it to fetch results later. |
| `status` | `pending`, `running`, `done`, `failed`, or `canceled`. |
| `summary.highest_severity` | Highest threat level across all detections: `critical`, `high`, `medium`, `low`, `none`, or `unknown`. |
| `summary.detection_count` | Total number of detections. |
| `summary.file_count` | Number of files scanned, including the files inside an archive. |
| `summary.files_with_detections_count` | Number of files that have at least one detection. |
| `summary.files_failed_to_scan` | Number of files that could not be scanned. |
| `summary.detection_categories` | List of detection categories found. |
| `inventory` | Model details, such as `model_name`, `model_version`, `model_id`, and `origin`. |
| `file_results` | One entry per file, with `file_location`, `status`, `details` (for example `details.file_type` and `details.sha256`), `detections`, `compliance`, and `file_error`. |
| `compliance.status` | `COMPLIANT` or `NONCOMPLIANT`, when compliance rules apply. |

A file in an archive format also has one entry for each file inside it. For example, a PyTorch checkpoint such as `pytorch_model.bin` is a zip archive, so `file_results` lists `pytorch_model.bin` and entries such as `pytorch_model.bin/archive/data.pkl`.

Each item in `file_results[].detections` includes `severity` (`critical`, `high`, `medium`, or `low`), `category`, `description`, `rule_id`, and `mitre_atlas`. It can also include `evidence` (for example, the function calls found in a pickle) and the mapping fields `cve`, `cwe`, `cwe_href`, and `owasp`. The API leaves a mapping field out when it doesn't apply, so check that it is set before you read it. The `risk`, `likelihood`, and `impact` fields are optional too, and are usually absent.

> [!WARNING]
>
> The report also has top-level `detection_count`, `file_count`, `files_with_detections_count`, `severity`, and `detection_categories` fields. These are deprecated. Read the same values from `summary` instead, and use `summary.highest_severity` rather than `summary.severity`. Some older examples, including `examples/demo.py` in the Python SDK repository, still read the deprecated fields.

> [!NOTE]
>
> A scan that fails is returned, not raised as an exception. Always check the report's `status` before you trust the summary. A `failed` scan may have zero detections only because the scan did not complete.

## Choose a scan method

The Python and TypeScript scanners are `client.model_scanner` and `client.modelScanner`. In Java they are `client.modelScanner()` and `client.communityScanner()`.

| Your model is | Python | TypeScript | Java | How the model reaches HiddenLayer |
| - | - | - | - | - |
| A single file on local disk | `scan_file` | `scanFile` | `scanFile` | The SDK uploads the file |
| A folder of files on local disk | `scan_folder` | `scanFolder` | `scanFolder` | The SDK uploads each file |
| A Hugging Face repository | `scan_huggingface_model` | `scanHuggingFaceModel` | Community scanner | Python and TypeScript download it locally, then upload it |
| A single file in AWS S3 | `scan_s3_model` | `scanS3Model` | Download, then `scanFile` | Downloaded locally, then uploaded |
| A single blob in Azure Blob Storage | `scan_azure_blob_model` | `scanAzureBlobModel` | Download, then `scanFile` | Downloaded locally, then uploaded |
| At a remote location HiddenLayer can access | `community_scanner.community_scan` | `communityScanner.communityScan` | `communityScanner().communityScan` | HiddenLayer fetches it. Nothing is downloaded to your machine |

Every scan method waits until the scan finishes unless you turn that off: `wait_for_results=False` in Python, `waitForResults: false` in TypeScript, or `.waitForResults(false)` on the Java options builder. See [Start a scan without waiting](#start-a-scan-without-waiting).

## Scan a local file

Use the file scan to scan one model file, such as a `.pkl`, `.pt`, `.h5`, or `.safetensors` file. The SDK uploads the file in parts, tells HiddenLayer the upload is complete, and then polls until the scan finishes.

The following program scans a file, prints the results, and exits with a non-zero code if the scan fails, a file can't be scanned, or the scan finds a `critical` or `high` detection. You can run it as a CI gate: most CI systems fail the job when a step exits with a non-zero code. The SDK waits for the scan with no time limit, so set a timeout on the CI job, or use the polling loop in [Wait with a time limit](#wait-with-a-time-limit).

```python Python theme={null}
import sys

import httpx
from hiddenlayer import HiddenLayer
from hiddenlayer.core import ApiError

MODEL_PATH = "models/resnet50.pkl"
BLOCKING_SEVERITIES = {"critical", "high"}


def main() -> int:
    # Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET (or HIDDENLAYER_TOKEN) from the environment.
    client = HiddenLayer()
    try:
        report = client.model_scanner.scan_file(
            model_name="resnet50",
            model_version="1",
            model_path=MODEL_PATH,
        )
    except FileNotFoundError:
        print(f"Model file not found: {MODEL_PATH}", file=sys.stderr)
        return 2
    except ApiError as e:
        print(f"HiddenLayer API error {e.status_code}: {e.body}", file=sys.stderr)
        return 2
    except httpx.TransportError as e:
        print(f"Could not reach HiddenLayer: {e!r}", file=sys.stderr)
        return 2

    print(f"Scan ID:          {report.scan_id}")
    print(f"Status:           {report.status}")
    print(f"Highest severity: {report.summary.highest_severity}")
    print(f"Detections:       {report.summary.detection_count}")

    for file_result in report.file_results or []:
        print(f"\nFile: {file_result.file_location} ({file_result.status})")
        for detection in file_result.detections:
            print(f"  [{detection.severity}] {detection.category}: {detection.description}")

    if report.status != "done":
        print(f"Scan did not complete (status: {report.status}).", file=sys.stderr)
        return 2
    if report.summary.files_failed_to_scan:
        print(f"{report.summary.files_failed_to_scan} file(s) could not be scanned.", file=sys.stderr)
        return 2
    if report.summary.highest_severity in BLOCKING_SEVERITIES:
        print("Blocking: model has critical or high severity detections.", file=sys.stderr)
        return 1
    return 0


if __name__ == "__main__":
    sys.exit(main())
```

```typescript TypeScript theme={null}
import { HiddenLayer, HiddenLayerError } from "@hiddenlayerai/hiddenlayer-sdk";

const MODEL_PATH = "models/resnet50.pkl";
const BLOCKING_SEVERITIES = new Set(["critical", "high"]);

async function main(): Promise<number> {
    // Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET (or HIDDENLAYER_TOKEN) from the environment.
    const client = new HiddenLayer();
    try {
        const report = await client.modelScanner.scanFile({
            modelName: "resnet50",
            modelVersion: "1",
            modelPath: MODEL_PATH,
        });

        console.log(`Scan ID:          ${report.scan_id}`);
        console.log(`Status:           ${report.status}`);
        console.log(`Highest severity: ${report.summary.highest_severity}`);
        console.log(`Detections:       ${report.summary.detection_count}`);

        for (const fileResult of report.file_results ?? []) {
            console.log(`\nFile: ${fileResult.file_location} (${fileResult.status})`);
            for (const detection of fileResult.detections) {
                console.log(`  [${detection.severity}] ${detection.category}: ${detection.description}`);
            }
        }

        if (report.status !== "done") {
            console.error(`Scan did not complete (status: ${report.status}).`);
            return 2;
        }
        if (report.summary.files_failed_to_scan) {
            console.error(`${report.summary.files_failed_to_scan} file(s) could not be scanned.`);
            return 2;
        }
        if (BLOCKING_SEVERITIES.has(report.summary.highest_severity ?? "")) {
            console.error("Blocking: model has critical or high severity detections.");
            return 1;
        }
        return 0;
    } catch (err) {
        if (err instanceof HiddenLayerError) {
            // statusCode is undefined when HiddenLayer couldn't be reached.
            console.error(`HiddenLayer error ${err.statusCode ?? "(no response)"}: ${err.message}`);
            return 2;
        }
        if (err instanceof Error && "code" in err && err.code === "ENOENT") {
            console.error(`Model file not found: ${MODEL_PATH}`);
            return 2;
        }
        throw err;
    }
}

process.exitCode = await main();
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.core.HiddenLayerApiException;
import com.hiddenlayer.api.core.HiddenLayerException;
import com.hiddenlayer.api.lib.ScanFileOptions;
import com.hiddenlayer.api.types.ScanDetectionV3;
import com.hiddenlayer.api.types.ScanFileResultV3;
import com.hiddenlayer.api.types.ScanHighestDetectionSeverity;
import com.hiddenlayer.api.types.ScanReportOfRecordV3;
import com.hiddenlayer.api.types.Status;
import java.util.Collections;
import java.util.Optional;

public class ScanModelFile {
    private static final String MODEL_PATH = "models/resnet50.pkl";

    public static void main(String[] args) {
        System.exit(run());
    }

    static int run() {
        // Reads HIDDENLAYER_CLIENT_ID and HIDDENLAYER_CLIENT_SECRET (or HIDDENLAYER_TOKEN) from the environment.
        HiddenLayerClient client = new HiddenLayerClientBuilder().build();
        ScanReportOfRecordV3 report;
        try {
            report = client.modelScanner().scanFile(ScanFileOptions.builder()
                    .modelName("resnet50")
                    .modelVersion("1")
                    .modelPath(MODEL_PATH)
                    .build());
        } catch (IllegalArgumentException e) {
            System.err.println(e.getMessage());
            return 2;
        } catch (HiddenLayerException e) {
            // The cause is what failed: a HiddenLayerApiException for an API error, an IOException for the network.
            Throwable cause = e.getCause() != null ? e.getCause() : e;
            if (cause instanceof HiddenLayerApiException) {
                HiddenLayerApiException apiError = (HiddenLayerApiException) cause;
                System.err.println("HiddenLayer API error " + apiError.statusCode() + ": " + apiError.body());
            } else {
                System.err.println("Scan failed: " + cause);
            }
            return 2;
        } finally {
            client.close();
        }

        Optional<ScanHighestDetectionSeverity> highest = report.getSummary().getHighestSeverity();
        System.out.println("Scan ID:          " + report.getScanId());
        System.out.println("Status:           " + report.getStatus());
        System.out.println("Highest severity: " + highest.map(Object::toString).orElse("unknown"));
        System.out.println("Detections:       " + report.getSummary().getDetectionCount().orElse(0L));

        for (ScanFileResultV3 fileResult : report.getFileResults().orElse(Collections.emptyList())) {
            System.out.println("\nFile: " + fileResult.getFileLocation() + " (" + fileResult.getStatus() + ")");
            for (ScanDetectionV3 detection : fileResult.getDetections()) {
                System.out.println("  [" + detection.getSeverity() + "] " + detection.getCategory() + ": "
                        + detection.getDescription());
            }
        }

        if (!Status.DONE.equals(report.getStatus())) {
            System.err.println("Scan did not complete (status: " + report.getStatus() + ").");
            return 2;
        }
        long filesFailed = report.getSummary().getFilesFailedToScan().orElse(0L);
        if (filesFailed > 0) {
            System.err.println(filesFailed + " file(s) could not be scanned.");
            return 2;
        }
        if (highest.filter(s -> s.equals(ScanHighestDetectionSeverity.CRITICAL)
                        || s.equals(ScanHighestDetectionSeverity.HIGH))
                .isPresent()) {
            System.err.println("Blocking: model has critical or high severity detections.");
            return 1;
        }
        return 0;
    }
}
```

**Expected result:** the program prints the scan ID, status, highest threat level, and detection count. For each file it prints any detections. For a model with no detections, the status is `done`, the highest threat level is typically `none`, and the program exits with code `0`.

The model name and model version identify the model in the HiddenLayer Console. The version defaults to `"1"`.

## Scan a folder

Use the folder scan when a model consists of several files, such as a weights file plus configuration and tokenizer files. The SDK walks the folder recursively and uploads every file that passes the filters, as one model.

You can filter files with shell-style wildcard patterns, such as `*.bin`:

* **Allow patterns:** if set, only files that match at least one pattern are scanned.
* **Ignore patterns:** files that match any pattern are skipped.

How patterns are matched differs by language:

> [tab] Python
>
> `allow_file_patterns` and `ignore_file_patterns` use [fnmatch](https://docs.python.org/3/library/fnmatch.html) against each file's path, and `*` also matches `/`. The SDK always adds these ignore patterns to yours: `*.txt`, `*.md`, `*.lock`, `.gitattributes`, and anything under `.git`. If HiddenLayer rejects a file as a duplicate within the same scan, the SDK logs a warning and skips that file instead of failing the whole scan.

> [tab] TypeScript
>
> `allowFilePatterns` and `ignoreFilePatterns` are matched against each file's name, not its full path. The SDK always adds these ignore patterns to yours: `*.txt`, `*.md`, `*.lock`, `.gitattributes`, and anything under `.git`.

> [tab] Java
>
> `allowFilePatterns` and `ignoreFilePatterns` match a pattern without a `/`, such as `*.safetensors`, against each file's name. A pattern with a `/`, such as `onnx/*.bin`, is matched against the file's path inside the folder, where `*` stops at `/` and `**` crosses directories. The SDK always adds these ignore patterns to yours: `*.txt`, `*.md`, `*.lock`, `.gitattributes`, and anything under `.git` (`ScanFolderOptions.DEFAULT_IGNORE_FILE_PATTERNS`). A folder that has no file left to scan throws an `IllegalArgumentException`.

```python Python theme={null}
from hiddenlayer import HiddenLayer

client = HiddenLayer()

report = client.model_scanner.scan_folder(
    model_name="distilbert-sentiment",
    model_version="2",
    path="models/distilbert-sentiment",
    allow_file_patterns=["*.safetensors", "*.bin", "*.json"],
    ignore_file_patterns=["*.png"],
)

print(
    f"{report.status}: {report.summary.file_count} files, "
    f"{report.summary.detection_count} detections, "
    f"highest severity {report.summary.highest_severity}"
)
```

```typescript TypeScript theme={null}
import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer();

const report = await client.modelScanner.scanFolder({
    modelName: "distilbert-sentiment",
    modelVersion: "2",
    path: "models/distilbert-sentiment",
    allowFilePatterns: ["*.safetensors", "*.bin", "*.json"],
    ignoreFilePatterns: ["*.png"],
});

console.log(
    `${report.status}: ${report.summary.file_count} files, ` +
        `${report.summary.detection_count} detections, ` +
        `highest severity ${report.summary.highest_severity}`,
);
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.lib.ScanFolderOptions;
import com.hiddenlayer.api.types.ScanReportOfRecordV3;
import java.util.Arrays;

public class ScanModelFolder {
    public static void main(String[] args) {
        HiddenLayerClient client = new HiddenLayerClientBuilder().build();

        ScanReportOfRecordV3 report = client.modelScanner().scanFolder(ScanFolderOptions.builder()
                .modelName("distilbert-sentiment")
                .modelVersion("2")
                .path("models/distilbert-sentiment")
                .allowFilePatterns(Arrays.asList("*.safetensors", "*.bin", "*.json"))
                .ignoreFilePatterns(Arrays.asList("*.png"))
                .build());

        System.out.println(report.getStatus() + ": "
                + report.getSummary().getFileCount().orElse(0L) + " files, "
                + report.getSummary().getDetectionCount().orElse(0L) + " detections, highest severity "
                + report.getSummary().getHighestSeverity().map(Object::toString).orElse("unknown"));
        client.close();
    }
}
```

**Expected result:** one report that covers every uploaded file, with an entry for each file in `file_results`.

## Scan a Hugging Face model

Scan a model repository on Hugging Face. The examples scan `prajjwal1/bert-tiny`, a small public BERT model. For a private or gated repository, provide a Hugging Face access token.

> [tab] Python
>
> `scan_huggingface_model` downloads the repository with `huggingface_hub`, then scans the downloaded folder.
>
> **Extra prerequisite:** `pip install huggingface_hub`.
>
> A public repository needs no token. For a private or gated one, pass `hf_token` a token string, or `True` to read the token saved in your local Hugging Face configuration (for example, after you log in with `hf auth login`). With `True` and no saved token, `huggingface_hub` raises `LocalTokenNotFoundError`. The example reads the token from an `HF_TOKEN` environment variable that you set yourself, and sends none when it isn't set.
>
> ```python Python theme={null}
> import os
>
> from hiddenlayer import HiddenLayer
>
> client = HiddenLayer()
>
> report = client.model_scanner.scan_huggingface_model(
>     repo_id="prajjwal1/bert-tiny",
>     revision="main",
>     allow_file_patterns=["*.safetensors", "*.bin", "*.json"],
>     # Needed only for private or gated repositories.
>     hf_token=os.environ.get("HF_TOKEN"),
> )
>
> print(f"{report.inventory.model_name}: {report.status}, highest severity {report.summary.highest_severity}")
> ```
>
> If you omit `model_name`, the SDK uses `repo_id` as the model name. The `revision` (a branch, tag, or commit hash) is also used as the model version, which is `"1"` when you omit it. Other options are `local_dir` (download location), `ignore_file_patterns`, and `force_download`.

> [tab] TypeScript
>
> `scanHuggingFaceModel` downloads the repository's files with `@huggingface/hub`, then scans the downloaded folder.
>
> **Extra prerequisite:** `npm install @huggingface/hub`.
>
> A public repository needs no token. For a private or gated one, pass `hfToken` a token string, or `true` to send the token configured on your machine. With `true`, the SDK reads the `HF_TOKEN` environment variable, then `HUGGING_FACE_HUB_TOKEN`, then the token file that `hf auth login` saves. With `true` and no token configured, the scan fails before it downloads anything, with an error that names where the SDK looked. The example reads the token from an `HF_TOKEN` environment variable that you set yourself, and sends none when it isn't set.
>
> ```typescript TypeScript theme={null}
> import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
>
> const client = new HiddenLayer();
>
> const report = await client.modelScanner.scanHuggingFaceModel({
>     repoId: "prajjwal1/bert-tiny",
>     revision: "main",
>     allowFilePatterns: ["*.safetensors", "*.bin", "*.json"],
>     // Needed only for private or gated repositories.
>     hfToken: process.env.HF_TOKEN,
> });
>
> console.log(
>     `${report.inventory.model_name}: ${report.status}, highest severity ${report.summary.highest_severity}`,
> );
> ```
>
> If you omit `modelName`, the SDK uses `repoId` as the model name. The `revision` is also used as the model version, which is `"1"` when you omit it. Other options are `localDir` (download location) and `ignoreFilePatterns`.

> [tab] Java
>
> The Java SDK has no Hugging Face download helper. Ask HiddenLayer to fetch the repository with the community scanner and `CommunityScanSource.HUGGING_FACE`, as shown in [Scan a remote model with the community scanner](#scan-a-remote-model-with-the-community-scanner).

**Expected result:** a report for the downloaded repository with `inventory.origin` set to `Hugging Face`.

## Scan a model in AWS S3

Scan a single model file stored in S3.

> [tab] Python
>
> `scan_s3_model` downloads the file with `boto3`, then scans it.
>
> **Extra prerequisite:** `pip install boto3`.
>
> By default the SDK creates `boto3.client("s3")`, which uses the standard AWS credential chain. That chain checks sources such as the `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` environment variables, your AWS config files, and attached IAM roles. Pass your own client with `s3_client` if you need a specific profile or region.
>
> ```python Python theme={null}
> from hiddenlayer import HiddenLayer
>
> client = HiddenLayer()
>
> report = client.model_scanner.scan_s3_model(
>     model_name="fraud-detector",
>     model_version="2026-11-01",
>     bucket="ml-model-registry",
>     key="fraud-detector/2026-11-01/model.pkl",
> )
>
> print(f"{report.status}: highest severity {report.summary.highest_severity}")
> ```

> [tab] TypeScript
>
> `scanS3Model` downloads the file with `@aws-sdk/client-s3`, then scans it.
>
> **Extra prerequisite:** `npm install @aws-sdk/client-s3`.
>
> By default the SDK creates `new S3Client()`, which uses the standard AWS credential chain. Pass your own client with `s3Client` if you need a specific profile or region.
>
> ```typescript TypeScript theme={null}
> import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
>
> const client = new HiddenLayer();
>
> const report = await client.modelScanner.scanS3Model({
>     modelName: "fraud-detector",
>     modelVersion: "2026-11-01",
>     bucket: "ml-model-registry",
>     key: "fraud-detector/2026-11-01/model.pkl",
> });
>
> console.log(`${report.status}: highest severity ${report.summary.highest_severity}`);
> ```

> [tab] Java
>
> The Java SDK has no S3 download helper. Download the file with the [AWS SDK for Java 2.x](https://docs.aws.amazon.com/sdk-for-java/latest/developer-guide/home.html) (`software.amazon.awssdk:s3`), then scan it with `scanFile`. `S3Client.create()` uses the standard AWS credential chain. Setting `origin("S3")` records where the model came from, as the Python and TypeScript helpers do.
>
> ```java Java theme={null}
> import com.hiddenlayer.api.HiddenLayerClient;
> import com.hiddenlayer.api.HiddenLayerClientBuilder;
> import com.hiddenlayer.api.lib.ScanFileOptions;
> import com.hiddenlayer.api.types.ScanReportOfRecordV3;
> import java.io.IOException;
> import java.nio.file.Files;
> import java.nio.file.Path;
> import software.amazon.awssdk.services.s3.S3Client;
> import software.amazon.awssdk.services.s3.model.GetObjectRequest;
>
> public class ScanS3Download {
>     public static void main(String[] args) throws IOException {
>         Path dir = Files.createTempDirectory("hiddenlayer-scan");
>         Path modelFile = dir.resolve("model.pkl");
>         try {
>             try (S3Client s3 = S3Client.create()) {
>                 s3.getObject(
>                         GetObjectRequest.builder()
>                                 .bucket("ml-model-registry")
>                                 .key("fraud-detector/2026-11-01/model.pkl")
>                                 .build(),
>                         modelFile);
>             }
>
>             try (HiddenLayerClient client = new HiddenLayerClientBuilder().build()) {
>                 ScanReportOfRecordV3 report = client.modelScanner().scanFile(ScanFileOptions.builder()
>                         .modelName("fraud-detector")
>                         .modelVersion("2026-11-01")
>                         .modelPath(modelFile.toString())
>                         .origin("S3")
>                         .build());
>                 System.out.println(report.getStatus() + ": highest severity "
>                         + report.getSummary().getHighestSeverity().map(Object::toString).orElse("unknown"));
>             }
>         } finally {
>             // Runs even if the download or the scan fails.
>             Files.deleteIfExists(modelFile);
>             Files.deleteIfExists(dir);
>         }
>     }
> }
> ```

**Expected result:** a report with `inventory.origin` set to `S3`.

## Scan a model in Azure Blob Storage

Scan a single blob in Azure Blob Storage.

> [tab] Python
>
> `scan_azure_blob_model` downloads the blob with the Azure Storage SDK, then scans it.
>
> **Extra prerequisite:** `pip install azure-identity azure-storage-blob`.
>
> By default the SDK authenticates with `DefaultAzureCredential`, which tries several Azure sign-in methods, such as environment variables, managed identity, and the Azure CLI. To use a shared access signature (SAS) token instead, pass it as `credential`. Read it from an environment variable rather than writing it in your code.
>
> ```python DefaultAzureCredential theme={null}
> from hiddenlayer import HiddenLayer
>
> client = HiddenLayer()
>
> report = client.model_scanner.scan_azure_blob_model(
>     model_name="fraud-detector",
>     model_version="2026-11-01",
>     account_url="https://mlmodelstore.blob.core.windows.net",
>     container="models",
>     blob="fraud-detector/2026-11-01/model.pkl",
> )
>
> print(f"{report.status}: highest severity {report.summary.highest_severity}")
> ```
>
> ```python SAS token theme={null}
> import os
>
> from hiddenlayer import HiddenLayer
>
> client = HiddenLayer()
>
> report = client.model_scanner.scan_azure_blob_model(
>     model_name="fraud-detector",
>     model_version="2026-11-01",
>     account_url="https://mlmodelstore.blob.core.windows.net",
>     container="models",
>     blob="fraud-detector/2026-11-01/model.pkl",
>     # AZURE_STORAGE_SAS_TOKEN is a variable you define; the SDK doesn't read it.
>     credential=os.environ["AZURE_STORAGE_SAS_TOKEN"],
> )
>
> print(f"{report.status}: highest severity {report.summary.highest_severity}")
> ```

> [tab] TypeScript
>
> `scanAzureBlobModel` downloads the blob with `@azure/storage-blob`, then scans it.
>
> **Extra prerequisite:** `npm install @azure/storage-blob`, plus `@azure/identity` to sign in with `DefaultAzureCredential`.
>
> The TypeScript helper has no default credential. Pass one as `credential`, such as `new DefaultAzureCredential()`, or put a SAS token in `accountUrl` and omit `credential`. Read the SAS token from an environment variable rather than writing it in your code.
>
> ```typescript DefaultAzureCredential theme={null}
> import { DefaultAzureCredential } from "@azure/identity";
> import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
>
> const client = new HiddenLayer();
>
> const report = await client.modelScanner.scanAzureBlobModel({
>     modelName: "fraud-detector",
>     modelVersion: "2026-11-01",
>     accountUrl: "https://mlmodelstore.blob.core.windows.net",
>     container: "models",
>     blob: "fraud-detector/2026-11-01/model.pkl",
>     credential: new DefaultAzureCredential(),
> });
>
> console.log(`${report.status}: highest severity ${report.summary.highest_severity}`);
> ```
>
> ```typescript SAS token theme={null}
> import { HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
>
> const client = new HiddenLayer();
>
> // AZURE_STORAGE_SAS_TOKEN is a variable you define; the SDK doesn't read it.
> const sasToken = process.env.AZURE_STORAGE_SAS_TOKEN;
> if (!sasToken) {
>     throw new Error("Set the AZURE_STORAGE_SAS_TOKEN environment variable.");
> }
>
> const report = await client.modelScanner.scanAzureBlobModel({
>     modelName: "fraud-detector",
>     modelVersion: "2026-11-01",
>     accountUrl: `https://mlmodelstore.blob.core.windows.net?${sasToken}`,
>     container: "models",
>     blob: "fraud-detector/2026-11-01/model.pkl",
> });
>
> console.log(`${report.status}: highest severity ${report.summary.highest_severity}`);
> ```

> [tab] Java
>
> The Java SDK has no Azure Blob Storage download helper. Download the blob with the [Azure Storage Blob client library for Java](https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-java) (`com.azure:azure-storage-blob`, with `com.azure:azure-identity` for `DefaultAzureCredential`), then scan it with `scanFile`.
>
> ```java Java theme={null}
> import com.azure.identity.DefaultAzureCredentialBuilder;
> import com.azure.storage.blob.BlobClient;
> import com.azure.storage.blob.BlobClientBuilder;
> import com.hiddenlayer.api.HiddenLayerClient;
> import com.hiddenlayer.api.HiddenLayerClientBuilder;
> import com.hiddenlayer.api.lib.ScanFileOptions;
> import com.hiddenlayer.api.types.ScanReportOfRecordV3;
> import java.io.IOException;
> import java.nio.file.Files;
> import java.nio.file.Path;
>
> public class ScanAzureDownload {
>     public static void main(String[] args) throws IOException {
>         Path dir = Files.createTempDirectory("hiddenlayer-scan");
>         Path modelFile = dir.resolve("model.pkl");
>         try {
>             BlobClient blob = new BlobClientBuilder()
>                     .endpoint("https://mlmodelstore.blob.core.windows.net")
>                     .containerName("models")
>                     .blobName("fraud-detector/2026-11-01/model.pkl")
>                     .credential(new DefaultAzureCredentialBuilder().build())
>                     .buildClient();
>             blob.downloadToFile(modelFile.toString());
>
>             try (HiddenLayerClient client = new HiddenLayerClientBuilder().build()) {
>                 ScanReportOfRecordV3 report = client.modelScanner().scanFile(ScanFileOptions.builder()
>                         .modelName("fraud-detector")
>                         .modelVersion("2026-11-01")
>                         .modelPath(modelFile.toString())
>                         .origin("Azure Blob Storage")
>                         .build());
>                 System.out.println(report.getStatus() + ": highest severity "
>                         + report.getSummary().getHighestSeverity().map(Object::toString).orElse("unknown"));
>             }
>         } finally {
>             // Runs even if the download or the scan fails.
>             Files.deleteIfExists(modelFile);
>             Files.deleteIfExists(dir);
>         }
>     }
> }
> ```

**Expected result:** a report with `inventory.origin` set to `Azure Blob Storage`.

### Temporary files for downloaded models

> [tab] Python
>
> > [!WARNING]
> >
> > The S3 and Azure helpers always download to `/tmp/<file name>`. The Hugging Face helper downloads to `/tmp/<repo_id>` unless you set `local_dir`. Keep these points in mind:
> >
> > * The SDK does not delete downloaded files after the scan. Remove them yourself if disk space or data retention matters.
> > * Because the paths are fixed under `/tmp`, the S3 and Azure helpers may not work on Windows. On Windows, download the file yourself and call `scan_file`, or set `local_dir` for Hugging Face.

> [tab] TypeScript
>
> The helpers download into a uniquely named file or folder in the operating system's temporary directory (`os.tmpdir()`) and delete it when the scan finishes or fails. If you set `localDir` for a Hugging Face scan, the files stay there after the scan.

> [tab] Java
>
> You choose where the model is downloaded. The examples above download into a new temporary directory and delete it after the scan.

## Scan a remote model with the community scanner

Use the community scanner when HiddenLayer can reach the model directly, for example through a presigned URL or a public Hugging Face repository. HiddenLayer fetches the model itself, so nothing is downloaded to or uploaded from your machine.

Set the model source to one of the `CommunityScanSource` constants. They have the same names in every SDK: import `CommunityScanSource` from `hiddenlayer.lib` in Python, from `@hiddenlayerai/hiddenlayer-sdk` in TypeScript, and from `com.hiddenlayer.api.lib` in Java.

| Constant | Source type |
| - | - |
| `HUGGING_FACE` | Hugging Face repository. Set the model path to the repository ID. |
| `AWS_PRESIGNED` | AWS S3 presigned URL |
| `AWS_IAM_ROLE` | AWS S3 through an IAM role |
| `AZURE_BLOB_SAS` | Azure Blob Storage with a SAS URL |
| `AZURE_BLOB_AD` | Azure Blob Storage with Microsoft Entra ID (Azure AD) |
| `GOOGLE_SIGNED` | Google Cloud Storage signed URL |
| `GOOGLE_OAUTH` | Google Cloud Storage with OAuth |
| `LOCAL` | Local source |

> [!NOTE]
>
> This page does not cover the access setup each source type requires on the HiddenLayer side (for example, which IAM role HiddenLayer assumes). The `HUGGING_FACE` example below follows the SDKs' own usage.

```python Python theme={null}
from hiddenlayer import HiddenLayer
from hiddenlayer.lib import CommunityScanSource

client = HiddenLayer()

report = client.community_scanner.community_scan(
    model_name="bert-tiny-torch-vuln",
    model_path="drhyrum/bert-tiny-torch-vuln",
    model_source=CommunityScanSource.HUGGING_FACE,
    model_version="main",
)

print(
    f"{report.scan_id}: {report.status}, "
    f"{report.summary.detection_count} detections, "
    f"highest severity {report.summary.highest_severity}"
)
```

```typescript TypeScript theme={null}
import { CommunityScanSource, HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer();

const report = await client.communityScanner.communityScan({
    modelName: "bert-tiny-torch-vuln",
    modelPath: "drhyrum/bert-tiny-torch-vuln",
    modelSource: CommunityScanSource.HUGGING_FACE,
    modelVersion: "main",
});

console.log(
    `${report.scan_id}: ${report.status}, ` +
        `${report.summary.detection_count} detections, ` +
        `highest severity ${report.summary.highest_severity}`,
);
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.lib.CommunityScanOptions;
import com.hiddenlayer.api.lib.CommunityScanSource;
import com.hiddenlayer.api.types.ScanReportOfRecordV3;

public class CommunityScan {
    public static void main(String[] args) {
        HiddenLayerClient client = new HiddenLayerClientBuilder().build();

        ScanReportOfRecordV3 report = client.communityScanner().communityScan(CommunityScanOptions.builder()
                .modelName("bert-tiny-torch-vuln")
                .modelPath("drhyrum/bert-tiny-torch-vuln")
                .modelSource(CommunityScanSource.HUGGING_FACE)
                .modelVersion("main")
                .build());

        System.out.println(report.getScanId() + ": " + report.getStatus() + ", "
                + report.getSummary().getDetectionCount().orElse(0L) + " detections, highest severity "
                + report.getSummary().getHighestSeverity().map(Object::toString).orElse("unknown"));
        client.close();
    }
}
```

The model version defaults to `"main"`. **Expected result:** a report for the remote model. The repository in this example is intentionally vulnerable, so expect detections.

## Start a scan without waiting

By default, scan methods block until the scan finishes. Turn off waiting to return as soon as the scan starts. This is useful in web services or pipelines where you do not want to hold a process open.

When you don't wait:

* For upload-based scans, the upload itself still finishes before the method returns. Only the wait for the analysis is skipped.
* The returned report is a point-in-time snapshot. Its `status` is often `pending` or `running`, and `file_results` may be incomplete.
* Save the report's scan ID, then fetch an updated report later: `scan_result(scan_id=...)` on `client.model_scanner` or `client.community_scanner` in Python, `getScanResults(client, scanId)` in TypeScript, or `ScanUtils.getScanResults(client, scanId)` in Java.

```python Python theme={null}
from hiddenlayer import HiddenLayer

client = HiddenLayer()

started = client.model_scanner.scan_file(
    model_name="resnet50",
    model_path="models/resnet50.pkl",
    wait_for_results=False,
)
print(f"Started scan {started.scan_id} (status: {started.status})")

# Later, possibly in another process:
report = client.model_scanner.scan_result(scan_id=started.scan_id)
print(f"Status now: {report.status}")
```

```typescript TypeScript theme={null}
import { getScanResults, HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";

const client = new HiddenLayer();

const started = await client.modelScanner.scanFile({
    modelName: "resnet50",
    modelPath: "models/resnet50.pkl",
    waitForResults: false,
});
console.log(`Started scan ${started.scan_id} (status: ${started.status})`);

// Later, possibly in another process:
const report = await getScanResults(client, started.scan_id);
console.log(`Status now: ${report.status}`);
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.lib.ScanFileOptions;
import com.hiddenlayer.api.lib.ScanUtils;
import com.hiddenlayer.api.types.ScanReportOfRecordV3;

public class StartThenFetch {
    public static void main(String[] args) {
        HiddenLayerClient client = new HiddenLayerClientBuilder().build();

        ScanReportOfRecordV3 started = client.modelScanner().scanFile(ScanFileOptions.builder()
                .modelName("resnet50")
                .modelPath("models/resnet50.pkl")
                .waitForResults(false)
                .build());
        System.out.println("Started scan " + started.getScanId() + " (status: " + started.getStatus() + ")");

        // Later, possibly in another process:
        ScanReportOfRecordV3 report = ScanUtils.getScanResults(client, started.getScanId());
        System.out.println("Status now: " + report.getStatus());
        client.close();
    }
}
```

If the new scan is not visible yet, the SDK retries up to five times. If the scan still cannot be found, Python raises `hiddenlayer.NotFoundError`, TypeScript throws a `HiddenLayerError` with `statusCode` 404, and Java throws a `HiddenLayerApiException` with `statusCode()` 404.

## Wait with a time limit

When the SDK waits for results, it polls the scan status with exponential backoff (up to 30 seconds between checks) until the scan is `done`, `failed`, or `canceled`. **There is no overall timeout.** If a scan stays in `pending` or `running`, your program waits indefinitely.

In CI/CD or other unattended environments, start the scan without waiting and poll yourself with a deadline. The scan summary endpoint (`scans.results.retrieve_summary` in Python, `scans.results.retrieveSummary` in TypeScript, `scans().results().retrieveSummary` in Java) is a lightweight call that returns the status and summary without the per-file results.

```python Python theme={null}
import sys
import time

from hiddenlayer import HiddenLayer

TIMEOUT_SECONDS = 15 * 60
POLL_INTERVAL_SECONDS = 10
TERMINAL_STATUSES = {"done", "failed", "canceled"}

client = HiddenLayer()

started = client.model_scanner.scan_file(
    model_name="resnet50",
    model_path="models/resnet50.pkl",
    wait_for_results=False,
)
scan_id = started.scan_id
deadline = time.monotonic() + TIMEOUT_SECONDS

while True:
    summary = client.scans.results.retrieve_summary(scan_id)
    if summary.status in TERMINAL_STATUSES:
        break
    if time.monotonic() > deadline:
        sys.exit(f"Scan {scan_id} did not finish within {TIMEOUT_SECONDS} seconds (last status: {summary.status}).")
    time.sleep(POLL_INTERVAL_SECONDS)

report = client.model_scanner.scan_result(scan_id=scan_id)
print(f"{report.status}: highest severity {report.summary.highest_severity}")
```

```typescript TypeScript theme={null}
import { getScanResults, HiddenLayer } from "@hiddenlayerai/hiddenlayer-sdk";
import { setTimeout as sleep } from "node:timers/promises";

const TIMEOUT_MS = 15 * 60 * 1000;
const POLL_INTERVAL_MS = 10_000;
const TERMINAL_STATUSES = new Set(["done", "failed", "canceled"]);

const client = new HiddenLayer();

const started = await client.modelScanner.scanFile({
    modelName: "resnet50",
    modelPath: "models/resnet50.pkl",
    waitForResults: false,
});
const scanId = started.scan_id;
const deadline = Date.now() + TIMEOUT_MS;

while (true) {
    const summary = await client.scans.results.retrieveSummary({ scan_id: scanId });
    if (TERMINAL_STATUSES.has(summary.status)) {
        break;
    }
    if (Date.now() > deadline) {
        console.error(`Scan ${scanId} did not finish within ${TIMEOUT_MS / 1000} seconds (last status: ${summary.status}).`);
        process.exit(1);
    }
    await sleep(POLL_INTERVAL_MS);
}

const report = await getScanResults(client, scanId);
console.log(`${report.status}: highest severity ${report.summary.highest_severity}`);
```

```java Java theme={null}
import com.hiddenlayer.api.HiddenLayerClient;
import com.hiddenlayer.api.HiddenLayerClientBuilder;
import com.hiddenlayer.api.lib.ScanFileOptions;
import com.hiddenlayer.api.lib.ScanUtils;
import com.hiddenlayer.api.types.ScanReportOfRecordV3;
import com.hiddenlayer.api.types.ScanReportSummaryResponseV3;
import com.hiddenlayer.api.types.Status;
import java.util.concurrent.TimeUnit;

public class ScanWithTimeout {
    public static void main(String[] args) throws InterruptedException {
        long timeoutMillis = TimeUnit.MINUTES.toMillis(15);
        long pollIntervalMillis = TimeUnit.SECONDS.toMillis(10);

        HiddenLayerClient client = new HiddenLayerClientBuilder().build();
        String scanId = client.modelScanner()
                .scanFile(ScanFileOptions.builder()
                        .modelName("resnet50")
                        .modelPath("models/resnet50.pkl")
                        .waitForResults(false)
                        .build())
                .getScanId();
        long deadline = System.currentTimeMillis() + timeoutMillis;

        while (true) {
            ScanReportSummaryResponseV3 summary = client.scans().results().retrieveSummary(scanId);
            Status status = summary.getStatus();
            if (status.equals(Status.DONE) || status.equals(Status.FAILED) || status.equals(Status.CANCELED)) {
                break;
            }
            if (System.currentTimeMillis() > deadline) {
                System.err.println("Scan " + scanId + " did not finish within 15 minutes (last status: " + status + ").");
                System.exit(1);
            }
            Thread.sleep(pollIntervalMillis);
        }

        ScanReportOfRecordV3 report = ScanUtils.getScanResults(client, scanId);
        System.out.println(report.getStatus() + ": highest severity "
                + report.getSummary().getHighestSeverity().map(Object::toString).orElse("unknown"));
        client.close();
    }
}
```

**Expected result:** the program either prints the final status and highest threat level, or exits with a timeout message that includes the scan ID so you can check it later.

For lower-level scan APIs, such as listing scan jobs, paging through file results, and downloading results in SARIF format (Static Analysis Results Interchange Format, a JSON format that many code-scanning tools accept), see [API usage examples](https://docs.hiddenlayer.ai/docs/integrations/sdk/api_examples.md).

## Common errors and fixes

> [accordion] A storage package is missing
>
> The download helper you called needs a package that the SDK does not install. In Python the error is an `ImportError` such as `Python package boto3 is not installed.` In TypeScript it is an `Error` such as `This scan needs @aws-sdk/client-s3: install it beside @hiddenlayerai/hiddenlayer-sdk.` Install the package listed in [Before you begin](#before-you-begin).

> [accordion] 401 Unauthorized
>
> HiddenLayer rejected your credentials. Check that `HIDDENLAYER_CLIENT_ID` and `HIDDENLAYER_CLIENT_SECRET` are set in the same shell or process that runs your program. Also check that the client's environment matches your account's region (`prod-us` or `prod-eu`). See [Authentication and configuration](https://docs.hiddenlayer.ai/docs/integrations/sdk/authentication.md).

> [accordion] 403 Forbidden
>
> Your credentials are valid but lack access to model scanning. Ask a Console administrator to check the client credential's permissions.

> [accordion] Couldn't download model ...
>
> In Python (`RuntimeError`) and TypeScript (`Error`), the S3 or Azure download failed before the scan started. The message includes the underlying error. Check the bucket, key, container, and blob names, and confirm that your AWS or Azure credentials can read the object.

> [accordion] The program cannot find the model
>
> Paths are resolved relative to the current working directory. Use an absolute path, or run the program from the expected directory. Python raises `FileNotFoundError`, TypeScript throws an error with code `ENOENT`, and Java throws an `IllegalArgumentException` such as `File does not exist: ...`.

> [accordion] The scan returns with status failed
>
> Failed scans are returned, not raised. Inspect `file_error` on each entry in `file_results` for scanner error messages, and check `summary.files_failed_to_scan`.

> [accordion] The program hangs while waiting for results
>
> Waiting for results has no overall timeout. Use the pattern in [Wait with a time limit](#wait-with-a-time-limit).

> [accordion] 404 Not Found right after starting a scan
>
> Without waiting, the SDK retries a few times while a new scan becomes available. If it still fails with a 404, wait briefly and fetch the results again. Also confirm you are using the same environment (region) that started the scan.

For more on exceptions and retries, see [Error handling](https://docs.hiddenlayer.ai/docs/integrations/sdk/error_handling.md) and [Troubleshooting](https://docs.hiddenlayer.ai/docs/integrations/sdk/troubleshooting.md).
