From 9f3f37c9e34510da65ad37d043ac8403488fbb16 Mon Sep 17 00:00:00 2001 From: O M Date: Wed, 2 Dec 2026 18:24:01 -0500 Subject: [PATCH 1/2] Inventory packages in container layers and function bundles. A library inside an image or a function never became a CVE finding, because those bytes were not walked. Co-authored-by: Cursor --- README.md | 12 +- docs/ARCHITECTURE.md | 6 +- docs/ROADMAP.md | 6 +- docs/adr/011-container-function-packages.md | 45 ++ go.mod | 2 + go.sum | 4 + internal/cmd/scan_workload.go | 2 +- internal/cmd/scan_workload_aws.go | 2 +- internal/cmd/scan_workload_container.go | 124 ++++++ internal/cmd/scan_workload_function.go | 213 +++++++++ internal/cmd/scan_workload_test.go | 23 + internal/collectors/aws/collector.go | 5 + internal/collectors/aws/collector_test.go | 3 + internal/collectors/azure/collector.go | 5 + internal/collectors/gcp/collector.go | 5 + internal/graph/store.go | 48 +- internal/graph/store_test.go | 69 +++ internal/graph/types.go | 7 + internal/workload/archive.go | 315 ++++++++++++++ internal/workload/archive_test.go | 154 +++++++ internal/workload/aws/function.go | 93 ++++ internal/workload/aws/function_test.go | 48 ++ internal/workload/azure/function.go | 230 ++++++++++ internal/workload/azure/function_test.go | 100 +++++ internal/workload/azure/scan.go | 5 + internal/workload/fetch.go | 92 ++++ internal/workload/function.go | 171 ++++++++ internal/workload/function_test.go | 110 +++++ internal/workload/gcp/function.go | 254 +++++++++++ internal/workload/gcp/function_test.go | 43 ++ internal/workload/images.go | 41 ++ internal/workload/lang.go | 182 ++++++++ internal/workload/registry.go | 458 ++++++++++++++++++++ internal/workload/registry_auth.go | 113 +++++ internal/workload/registry_ecr.go | 37 ++ internal/workload/registry_test.go | 126 ++++++ 36 files changed, 3144 insertions(+), 9 deletions(-) create mode 100644 docs/adr/011-container-function-packages.md create mode 100644 internal/cmd/scan_workload_container.go create mode 100644 internal/cmd/scan_workload_function.go create mode 100644 internal/workload/archive.go create mode 100644 internal/workload/archive_test.go create mode 100644 internal/workload/aws/function.go create mode 100644 internal/workload/aws/function_test.go create mode 100644 internal/workload/azure/function.go create mode 100644 internal/workload/azure/function_test.go create mode 100644 internal/workload/fetch.go create mode 100644 internal/workload/function.go create mode 100644 internal/workload/function_test.go create mode 100644 internal/workload/gcp/function.go create mode 100644 internal/workload/gcp/function_test.go create mode 100644 internal/workload/images.go create mode 100644 internal/workload/lang.go create mode 100644 internal/workload/registry.go create mode 100644 internal/workload/registry_auth.go create mode 100644 internal/workload/registry_ecr.go create mode 100644 internal/workload/registry_test.go diff --git a/README.md b/README.md index b8c0058..6d60686 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ OpenSourceOM Core is the platform behind [opensourceom.org](https://opensourceom Traditional scanners flood you with CVEs and misconfigurations. OpenSourceOM connects the dots — showing which findings sit on paths from the internet to your sensitive data and privileged identities. -> **Status:** Phase 3 has shipped. Phase 4 is open: `om scan workload` inventories Linux root volumes and boot images. Phase 5 (secret and malware findings on that storage) is open. Further rule packs stay open for contributors ([#10](https://github.com/OpenSourceOM/core/issues/10)). See the [roadmap](./docs/ROADMAP.md). +> **Status:** Phase 3 has shipped. Phase 4 is open: `om scan workload` inventories Linux root volumes, boot images, container layers, and function bundles. Shared filesystems are still open. Phase 5 (secret and malware findings on that storage) is open. Further rule packs stay open for contributors ([#10](https://github.com/OpenSourceOM/core/issues/10)). See the [roadmap](./docs/ROADMAP.md). ## Why this exists @@ -105,6 +105,10 @@ export AWS_REGION=us-east-1 # sudo -E ./om scan workload gcp # sudo -E ./om scan workload image gcp ./om scan k8s # requires kubeconfig +# ./om scan workload container +# ./om scan workload function aws +# ./om scan workload function azure +# ./om scan workload function gcp # Or ingest a custom collector (stdout is a graph batch) go build -o example-collector ./examples/collector @@ -163,6 +167,10 @@ An API token is created only when an admin asks for one, from the console or wit ./om scan workload gcp # scanner VM; snapshots the production project ./om scan workload image gcp # scanner VM; image packages, applied to instances ./om scan k8s # requires kubeconfig or in-cluster credentials +./om scan workload container # image layers on pods from om scan k8s +./om scan workload function aws +./om scan workload function azure +./om scan workload function gcp ./om scan plugin -- ./my-collector ``` @@ -189,7 +197,7 @@ Full documentation: [opensourceom.org](https://opensourceom.org) (docs at [opens | **1** | Attack path queries, CVE enrichment, web UI, Azure/GCP collectors | | **2** | CSPM rules, blast radius, K8s connector, exports | | **3** | Plugin SDK, Helm, embedded rule pack, demo graph, inventory-backed CVEs, crown-jewel datastores, attack-path findings, and cloud audit context (CloudTrail, Activity Log, Admin Activity). Shipped. | -| **4** | Package inventory from persistent workload storage. Linux root volumes and boot images ship with `om scan workload`. Container layers, function bundles, and shared filesystems are open. | +| **4** | Package inventory from persistent workload storage. Linux root volumes, boot images, container layers, and function bundles ship with `om scan workload`. Shared filesystems are open. | | **5** | Secret and malware findings on storage Phase 4 already opens. Kind and path only. Open. | Details: [docs/ROADMAP.md](./docs/ROADMAP.md) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index b62305c..46b630e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -53,7 +53,7 @@ SPDX-License-Identifier: Apache-2.0 Findings link to affected resources via `VIOLATES` edges. CSPM and CVE findings share the same `Finding` node type but use `finding_type` and `rule_id` / `cve_id` properties for provenance. -See [ADR 001](./adr/001-graph-schema-v0.md), [ADR 002](./adr/002-phase1-findings-ui.md), [ADR 003](./adr/003-phase2-cspm-rbac.md), [ADR 004](./adr/004-collector-plugin-sdk.md), [ADR 005](./adr/005-console-admins.md), [ADR 006](./adr/006-aws-root-volume-packages.md), [ADR 007](./adr/007-azure-gce-root-volume-packages.md), and [ADR 008](./adr/008-boot-image-packages.md). +See [ADR 001](./adr/001-graph-schema-v0.md), [ADR 002](./adr/002-phase1-findings-ui.md), [ADR 003](./adr/003-phase2-cspm-rbac.md), [ADR 004](./adr/004-collector-plugin-sdk.md), [ADR 005](./adr/005-console-admins.md), [ADR 006](./adr/006-aws-root-volume-packages.md), [ADR 007](./adr/007-azure-gce-root-volume-packages.md), [ADR 008](./adr/008-boot-image-packages.md), [ADR 009](./adr/009-scanner-account.md), [ADR 010](./adr/010-console-cloud-connect.md), and [ADR 011](./adr/011-container-function-packages.md). ## Technology choices @@ -88,7 +88,9 @@ Further community rule packs (PCI and additional CIS mappings) stay open for con Phase 4 writes `packages` (CPE 2.3 names and package URLs) from persistent workload storage onto the workload node that enrichment already matches. The sources, in order, are AWS Linux root volumes, Azure VM and GCE root volumes, boot images, container image layers and function bundles, and shared filesystems (EFS, Azure Files, Filestore). The scan is opt-in. `om scan aws`, `om scan azure`, and `om scan gcp` stay read-only API collectors. -`om scan workload aws` is the AWS root-volume scan. `om scan workload azure` and `om scan workload gcp` are the same walk for Azure OS disks and GCE boot disks. `om scan workload image aws`, `om scan workload image azure`, and `om scan workload image gcp` read each boot image once and add those package identifiers to instances launched from it. A package that exists only on an instance disk stays on that instance. Each command runs as root on a worker in a scanner account, subscription, or project. The production account grants snapshot and share. The worker mounts the copy and stores package identifiers only. A later API scan keeps `packages`. Windows, LVM, and non-root disks are skipped. Container layers, function bundles, and shared filesystems are still open. See [ADR 006](./adr/006-aws-root-volume-packages.md), [ADR 007](./adr/007-azure-gce-root-volume-packages.md), [ADR 008](./adr/008-boot-image-packages.md), and [ADR 009](./adr/009-scanner-account.md). The grants are in [deploy/connect](../deploy/connect/README.md). +`om scan workload aws` is the AWS root-volume scan. `om scan workload azure` and `om scan workload gcp` are the same walk for Azure OS disks and GCE boot disks. `om scan workload image aws`, `om scan workload image azure`, and `om scan workload image gcp` read each boot image once and add those package identifiers to instances launched from it. A package that exists only on an instance disk stays on that instance. Each of those commands runs as root on a worker in a scanner account, subscription, or project. The production account grants snapshot and share. The worker mounts the copy and stores package identifiers only. A later API scan keeps `packages`. Windows, LVM, and non-root disks are skipped. See [ADR 006](./adr/006-aws-root-volume-packages.md), [ADR 007](./adr/007-azure-gce-root-volume-packages.md), [ADR 008](./adr/008-boot-image-packages.md), and [ADR 009](./adr/009-scanner-account.md). The grants are in [deploy/connect](../deploy/connect/README.md). + +`om scan workload container` reads container image layers already stored on Kubernetes workloads. `om scan workload function aws`, `om scan workload function azure`, and `om scan workload function gcp` read Lambda deployment packages, Azure Functions bundles, and Cloud Functions source. Those commands do not attach a volume. The graph stores package identifiers on the workload, beside an existing `images` list for a pod. A repository source, a zstd layer, and a foreign layer are skipped. Shared filesystems are still open. See [ADR 011](./adr/011-container-function-packages.md). Phase 5 adds a finding for a secret pattern or a malware signature on storage that Phase 4 reader already opened. The finding stores the kind and the path. Object bodies and database rows are in neither phase. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 8f54353..7abc63e 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -64,20 +64,22 @@ Phase 4 is open. Cloud collectors record the VM, its exposure, and its identity. The phase ends when a package found in that storage is a CVE finding on the workload the graph already stores. A block volume is the first source. Boot images, container image layers, function bundles, and shared filesystems are the rest. -The scan is opt-in and separate from `om scan aws`, `om scan azure`, and `om scan gcp`. Those commands stay read-only. The workload scan runs a worker in a scanner account, subscription, or project, reads package metadata, and writes CPE 2.3 names and package URLs onto the existing workload. Snapshots and mounts are removed when the scan finishes, including when it fails. File contents stay off the graph. +The scan is opt-in and separate from `om scan aws`, `om scan azure`, and `om scan gcp`. Those commands stay read-only. Root-volume and boot-image scans run a worker in a scanner account, subscription, or project. Snapshots and mounts are removed when the scan finishes, including when it fails. Container layers and function bundles are read without a volume attach. Each scan writes CPE 2.3 names and package URLs onto the workload. File contents stay off the graph. The path, in order: - [x] **AWS Linux root volumes** — [#102](https://github.com/OpenSourceOM/core/issues/102) - [x] **Azure VM and GCE root volumes** — the same walker, those snapshot APIs — [#103](https://github.com/OpenSourceOM/core/issues/103) - [x] **Boot images** — an AMI and the Azure and GCE equivalents, scanned once and applied to instances launched from that image — [#104](https://github.com/OpenSourceOM/core/issues/104) -- [ ] **Container image layers and function bundles** — layers for images already stored on Kubernetes workloads, plus Lambda deployment packages and the Azure and GCP equivalents. No volume attach — [#105](https://github.com/OpenSourceOM/core/issues/105) +- [x] **Container image layers and function bundles** — layers for images already stored on Kubernetes workloads, plus Lambda deployment packages and the Azure and GCP equivalents. No volume attach — [#105](https://github.com/OpenSourceOM/core/issues/105) - [ ] **Shared filesystems** — EFS, Azure Files, and Filestore, when the application is installed there and a root-volume scan would miss it — [#106](https://github.com/OpenSourceOM/core/issues/106) `om scan workload aws` reads Linux root volumes in a production account from a worker in a scanner account. It assumes a snapshot role, shares the snapshot, copies it into the scanner account, and mounts that copy read-only. `om scan workload azure` and `om scan workload gcp` do the same from a scanner subscription or project. The grants are in `deploy/connect`. A later `om scan aws`, `om scan azure`, or `om scan gcp` leaves `packages` in place. Windows, LVM, and disks other than the root volume are skipped. See [ADR 009](./adr/009-scanner-account.md). `om scan workload image aws` reads each AMI once, including an image no instance is running, and adds those package identifiers to every instance launched from it. `om scan workload image azure` and `om scan workload image gcp` do the same for Azure and GCE images. A package found only on an instance's own disk stays on that instance. Marketplace images the account cannot share are skipped. The volume or disk created for the read is deleted. The image's own snapshot is not. +`om scan workload container` reads each container image stored by `om scan k8s` once and adds those package identifiers to every Kubernetes workload that lists the image. The `images` list stays. Registry credentials stay in the operator environment. `om scan workload function aws`, `om scan workload function azure`, and `om scan workload function gcp` write a workload for each function and store package identifiers from its deployment package or container image. A repository source, a zstd layer, and a foreign layer are skipped. No snapshot or volume is attached. Bundle bytes and layer bytes are deleted after the walk. A later API scan leaves these packages in place. See [ADR 011](./adr/011-container-function-packages.md). + Object bodies and database rows stay out. They are customer data, not the installed software. A public bucket or database is already an exposure finding from the API scan. ## Phase 5 — Findings on inventoried storage diff --git a/docs/adr/011-container-function-packages.md b/docs/adr/011-container-function-packages.md new file mode 100644 index 0000000..c882ba7 --- /dev/null +++ b/docs/adr/011-container-function-packages.md @@ -0,0 +1,45 @@ + + +# ADR 011: Container and function package inventory + +**Status:** Accepted +**Date:** 2026-12-02 +**Phase:** 4 + +## Context + +[ADR 006](./006-aws-root-volume-packages.md), [ADR 007](./007-azure-gce-root-volume-packages.md), and [ADR 008](./008-boot-image-packages.md) read a block volume. A container image and a function bundle are also persistent workload storage, and they do not need a snapshot. `om scan k8s` already stores image references on the pod. `om enrich cve` matches `packages` and does not need a new identifier shape. Lambda, Azure Functions, and Cloud Functions are not in the API inventory at all. + +## Decision + +`om scan workload container`, `om scan workload function aws`, `om scan workload function azure`, and `om scan workload function gcp` are subcommands of the same opt-in scan. `om scan aws`, `om scan azure`, `om scan gcp`, and `om scan k8s` stay read-only. The root-volume and boot-image commands stay as they are. + +The container command fetches each image reference already stored on a Kubernetes workload, walks the layers in order, and adds the resulting CPE 2.3 names and package URLs to `packages` on every workload that lists that image. The `images` list stays. Identifiers already stored stay, including a package this image does not contain. Run `om scan k8s` first. + +Each function command lists functions in the configured region, reads the deployment package or the function's container image, and writes a workload node for that function. A full run removes function workloads in that account and region that no longer exist. `--function` updates the named functions and leaves the others. A skipped function keeps packages already stored. + +No command in this decision attaches a volume or needs to run as root. Layer bytes and bundle bytes are deleted after the walk. The graph, logs, and exports store package identifiers. They do not store file contents, a presigned URL, or function environment variables. + +Registry and function credentials stay in the operator environment. A private registry uses an `auths` entry in the docker config. Credential helpers in that file are not run. An ECR registry uses the AWS credential chain. Public images need no credentials. + +The walker reads dpkg, apk, and rpm databases, plus Maven jars, Python distributions, and npm `package.json` files. A zstd layer, a foreign layer, and a Cloud Functions repository source are skipped. `WEBSITE_RUN_FROM_PACKAGE` is read only when it is an http or https URL. App settings other than that URL are not stored. Listing Azure app settings uses the `config/appsettings/list` POST. + +The new AWS actions are `lambda:ListFunctions` and `lambda:GetFunction`, plus `ecr:GetAuthorizationToken` when the image is in ECR. The new Azure actions are `Microsoft.Web/sites/read` and `Microsoft.Web/sites/config/read`. The new GCP permissions are `cloudfunctions.functions.list` and `storage.objects.get`. The API collectors do not gain these permissions. + +Shared filesystems stay on a later Phase 4 issue. ECS services, Cloud Run services, Container Apps, and functions deployed only from a repository stay out. Secret and malware findings stay on Phase 5. + +## Consequences + +These commands can run from any machine that can reach the registry or the function API. They do not use the scanner-account snapshot role. The Helm chart does not schedule them. + +`om enrich cve` is unchanged. It attaches a CVE only when one of these identifiers matches. A function workload is left in place by a later `om scan aws`, `om scan azure`, or `om scan gcp`. + +## References + +- [docs/ROADMAP.md](../ROADMAP.md) +- [ADR 006](./006-aws-root-volume-packages.md) +- [ADR 008](./008-boot-image-packages.md) +- [Issue #105](https://github.com/OpenSourceOM/core/issues/105) diff --git a/go.mod b/go.mod index 49189d1..826d253 100644 --- a/go.mod +++ b/go.mod @@ -21,7 +21,9 @@ require ( github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.20.7 github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.65.13 github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.2 + github.com/aws/aws-sdk-go-v2/service/ecr v1.67.0 github.com/aws/aws-sdk-go-v2/service/iam v1.64.6 + github.com/aws/aws-sdk-go-v2/service/lambda v1.113.3 github.com/aws/aws-sdk-go-v2/service/rds v1.130.3 github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6 github.com/aws/aws-sdk-go-v2/service/sts v1.51.8 diff --git a/go.sum b/go.sum index 494defc..992d68d 100644 --- a/go.sum +++ b/go.sum @@ -78,6 +78,8 @@ github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.65.13 h1:0Eohou9DEK6s1JjZnhfT github.com/aws/aws-sdk-go-v2/service/cloudtrail v1.65.13/go.mod h1:OqQeF9m+3Z8jvuUXrX1gid/ZHQXCwAxMH7U8eKskr1c= github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.2 h1:JohP9To4S31937ChcN87LOGGHWcv/lQ8B96XKUbmV30= github.com/aws/aws-sdk-go-v2/service/ec2 v1.350.2/go.mod h1:JbB+shRXmk18Y4V+GnOzGWFkIjA8ZfGSgtPUgs4X+7E= +github.com/aws/aws-sdk-go-v2/service/ecr v1.67.0 h1:diXYaM5vgoy4xeHgY4Q0cAwCCwKx+cvFdjR23eKGXJk= +github.com/aws/aws-sdk-go-v2/service/ecr v1.67.0/go.mod h1:hbHHpYZ/29gAnar+fh7C0BpL/ELXMwxh2q7ZqXSZePI= github.com/aws/aws-sdk-go-v2/service/iam v1.64.6 h1:6tqE3gHbHFEvARPvlLHgRK1dXoD96ecolfPEurpYXyc= github.com/aws/aws-sdk-go-v2/service/iam v1.64.6/go.mod h1:lV0r+RVSkXRA6WhiaxW55qn8n60ObMwQShxaqrs9UeY= github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.13.27 h1:2jIfOe8ZuoStxOkRtVU45zxgvt/qeIRChhm2USOS6g8= @@ -88,6 +90,8 @@ github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.14 h1:+uYcwTJB github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.14.14/go.mod h1:POa4UPRV0vUNxPl2brT7/TmPHsFZvKP86DT0eTxV9C4= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8 h1:RS1Wt+K0r4X0ci9Vf4JYTUfHzsQihYA2LgGJeEneKpk= github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.20.8/go.mod h1:adMnTy5kyoUW86jhXnGSVc/mvMQI4GZd1qYWMeaS8M8= +github.com/aws/aws-sdk-go-v2/service/lambda v1.113.3 h1:oSHldse7GDHpdq81XeAJnhIbsdDKP9bMIt00G8W6uXI= +github.com/aws/aws-sdk-go-v2/service/lambda v1.113.3/go.mod h1:Y//K046w4uhiR3o77beo/y52Jv2uEY13iJ+3+jicLO8= github.com/aws/aws-sdk-go-v2/service/rds v1.130.3 h1:/r/iLO6C3fZt8h10+YT4ID2R//JD6q7k9P/7f8AsN+A= github.com/aws/aws-sdk-go-v2/service/rds v1.130.3/go.mod h1:kINuLzcAGKKdpwsN4A24D3y0gAVJDrN4/dGfkJeq9JE= github.com/aws/aws-sdk-go-v2/service/s3 v1.114.6 h1:to7+Vr3rLkpYRwVKJ5QRriI0eE306vrVN/6TnVHgxvY= diff --git a/internal/cmd/scan_workload.go b/internal/cmd/scan_workload.go index a076bac..297fe9b 100644 --- a/internal/cmd/scan_workload.go +++ b/internal/cmd/scan_workload.go @@ -10,7 +10,7 @@ var scanWorkloadCmd = &cobra.Command{ Short: "Inventory packages on workload storage", Long: `Inventory packages on workload storage. -Root volumes are "om scan workload aws", "om scan workload azure", and "om scan workload gcp". Boot images are "om scan workload image aws", "om scan workload image azure", and "om scan workload image gcp". Each runs as root on a worker in a scanner account, subscription, or project. It assumes a role in the account being scanned, shares a snapshot, and mounts the copy on the worker. om scan aws, om scan azure, and om scan gcp stay read-only. The grants are in deploy/connect.`, +Root volumes are "om scan workload aws", "om scan workload azure", and "om scan workload gcp". Boot images are "om scan workload image aws", "om scan workload image azure", and "om scan workload image gcp". Each of those runs as root on a worker in a scanner account, subscription, or project. It assumes a role in the account being scanned, shares a snapshot, and mounts the copy on the worker. Container layers are "om scan workload container". Function bundles are "om scan workload function aws", "om scan workload function azure", and "om scan workload function gcp". Those do not attach a volume. om scan aws, om scan azure, and om scan gcp stay read-only. The grants for the volume scans are in deploy/connect.`, } func init() { diff --git a/internal/cmd/scan_workload_aws.go b/internal/cmd/scan_workload_aws.go index 316692f..60c0bf8 100644 --- a/internal/cmd/scan_workload_aws.go +++ b/internal/cmd/scan_workload_aws.go @@ -34,7 +34,7 @@ Run it as root on an EC2 instance in the scanner account, in the same region. Pa An encrypted volume needs --kms-key, a key in the scanner account. The production key policy has to allow the scanner role to decrypt. om scan aws stays a read-only API scan. A later om scan aws keeps packages already stored on the workload. Snapshots and volumes are tagged opensourceom:scan=workload, which is how to find one left behind by a killed process. -This command reads Linux root volumes. Windows instances are skipped. LVM and disks other than the root volume are skipped. Boot images are "om scan workload image aws". Container layers, function bundles, and shared filesystems are later scans. +This command reads Linux root volumes. Windows instances are skipped. LVM and disks other than the root volume are skipped. Boot images are "om scan workload image aws". Container layers are "om scan workload container". Function bundles are "om scan workload function aws". Shared filesystems are a later scan. ` + granted("Production role", awsv.Permissions) + "\n\n" + granted("Scanner role", awsv.WorkerPermissions) } diff --git a/internal/cmd/scan_workload_container.go b/internal/cmd/scan_workload_container.go new file mode 100644 index 0000000..7613fa9 --- /dev/null +++ b/internal/cmd/scan_workload_container.go @@ -0,0 +1,124 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package cmd + +import ( + "context" + "errors" + "fmt" + "sort" + "time" + + "github.com/OpenSourceOM/core/internal/graph" + "github.com/OpenSourceOM/core/internal/workload" + "github.com/spf13/cobra" +) + +var ( + containerTimeout time.Duration + containerImages []string + containerCluster string +) + +var scanWorkloadContainerCmd = &cobra.Command{ + Use: "container", + Short: "Inventory packages in container image layers", + Long: `Inventory packages in container image layers already stored by om scan k8s. + +The command fetches each image once, walks the layers, and adds those CPE 2.3 names and package URLs to packages on every Kubernetes workload that lists the image. The images list stays. It does not attach a volume and does not need to run as root. Layer bytes are deleted after the walk. The graph stores package identifiers only. + +Registry credentials stay in the operator environment. A private registry uses an auth entry in the docker config (DOCKER_CONFIG, or ~/.docker/config.json). Credential helpers in that file are not run. An ECR registry uses the AWS credential chain, which needs ecr:GetAuthorizationToken. The token is not stored. Public images need no credentials. + +A package already stored on the workload stays, including one this image does not contain. om scan k8s stays a read-only API scan and keeps packages already stored. Run om scan k8s first so the pod nodes and image refs exist. Shared filesystems are a later scan. + +zstd layers and foreign layers are skipped.`, + RunE: runScanWorkloadContainer, +} + +func runScanWorkloadContainer(cmd *cobra.Command, args []string) error { + cfg := loadConfig() + ctx := cmd.Context() + store, err := openGraphStore(ctx, cfg) + if err != nil { + return err + } + defer store.Close() + + type hit struct { + id string + name string + } + byImage := map[string][]hit{} + err = store.ForEachNode(ctx, graph.NodeWorkload, func(node graph.Node) error { + if node.Provider != "kubernetes" { + return nil + } + if containerCluster != "" && node.AccountID != containerCluster { + return nil + } + for _, ref := range workload.ImageRefs(node.Properties) { + byImage[ref] = append(byImage[ref], hit{id: node.ID, name: node.Name}) + } + return nil + }) + if err != nil { + return err + } + if len(containerImages) > 0 { + filtered := map[string][]hit{} + for _, ref := range containerImages { + hits, ok := byImage[ref] + if !ok { + return fmt.Errorf("image %s is not on a kubernetes workload", ref) + } + filtered[ref] = hits + } + byImage = filtered + } + refs := make([]string, 0, len(byImage)) + for ref := range byImage { + refs = append(refs, ref) + } + sort.Strings(refs) + + registry := workload.NewRegistry() + timeout := containerTimeout + if timeout <= 0 { + timeout = 10 * time.Minute + } + var failed []error + wrote := 0 + for _, ref := range refs { + fmt.Printf("%s: reading image layers\n", ref) + ictx, cancel := context.WithTimeout(ctx, timeout) + packages, err := registry.Packages(ictx, ref) + cancel() + if err != nil { + if reason, ok := workload.Reason(err); ok { + fmt.Printf("%s: skipped (%s)\n", ref, reason) + continue + } + failed = append(failed, err) + fmt.Printf("%s: %s\n", ref, err) + continue + } + for _, item := range byImage[ref] { + if err := store.MergeWorkloadPackages(ctx, item.id, packages); err != nil { + failed = append(failed, err) + continue + } + fmt.Printf("%s: %d package identifiers\n", workloadLabel(item.id, item.name), len(packages)) + wrote++ + } + } + fmt.Printf("Stored packages on %d workloads.\n", wrote) + return errors.Join(failed...) +} + +func init() { + scanWorkloadContainerCmd.Flags().DurationVar(&containerTimeout, "timeout", 10*time.Minute, "time limit for each image") + scanWorkloadContainerCmd.Flags().StringArrayVar(&containerImages, "image", nil, "image reference (repeat to scan several; the default is every image on a kubernetes workload)") + scanWorkloadContainerCmd.Flags().StringVar(&containerCluster, "cluster", "", "limit the scan to workloads from this K8S_CLUSTER account id") + scanWorkloadCmd.AddCommand(scanWorkloadContainerCmd) +} diff --git a/internal/cmd/scan_workload_function.go b/internal/cmd/scan_workload_function.go new file mode 100644 index 0000000..04588e2 --- /dev/null +++ b/internal/cmd/scan_workload_function.go @@ -0,0 +1,213 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package cmd + +import ( + "context" + "errors" + "fmt" + "strings" + "time" + + awscol "github.com/OpenSourceOM/core/internal/collectors/aws" + "github.com/OpenSourceOM/core/internal/config" + "github.com/OpenSourceOM/core/internal/graph" + "github.com/OpenSourceOM/core/internal/workload" + awsv "github.com/OpenSourceOM/core/internal/workload/aws" + azurev "github.com/OpenSourceOM/core/internal/workload/azure" + gcpv "github.com/OpenSourceOM/core/internal/workload/gcp" + "github.com/spf13/cobra" +) + +var ( + awsFunctionTimeout time.Duration + awsFunctions []string + azureFunctionTimeout time.Duration + azureFunctions []string + gcpFunctionTimeout time.Duration + gcpFunctions []string +) + +var scanWorkloadFunctionCmd = &cobra.Command{ + Use: "function", + Short: "Inventory packages in function bundles", + Long: `Inventory packages in function bundles. + +Each cloud is its own command: "om scan workload function aws", "om scan workload function azure", and "om scan workload function gcp". Each writes a workload for the function and stores package identifiers from the deployment package or container image. No volume is attached. Bundle bytes are deleted after the walk. om scan aws, om scan azure, and om scan gcp stay read-only and leave these workloads in place.`, +} + +var scanWorkloadFunctionAWSCmd = &cobra.Command{ + Use: "aws", + Short: "Inventory packages in Lambda deployment packages", + Long: workloadFunctionAWSLong(), + RunE: runScanWorkloadFunctionAWS, +} + +var scanWorkloadFunctionAzureCmd = &cobra.Command{ + Use: "azure", + Short: "Inventory packages in Azure Functions bundles", + Long: workloadFunctionAzureLong(), + RunE: runScanWorkloadFunctionAzure, +} + +var scanWorkloadFunctionGCPCmd = &cobra.Command{ + Use: "gcp", + Short: "Inventory packages in Cloud Functions source bundles", + Long: workloadFunctionGCPLong(), + RunE: runScanWorkloadFunctionGCP, +} + +func workloadFunctionAWSLong() string { + return `Inventory packages on Lambda functions in the current AWS account and region. + +The command lists functions in AWS_REGION, downloads each zip deployment package or reads the function's container image, and writes CPE 2.3 names and package URLs onto a workload for that function. It does not attach a volume and does not need to run as root. The package bytes are deleted after the walk. The presigned URL and the function's environment variables are not stored. + +A later om scan aws leaves the function workload and its packages in place. A full run of this command removes function workloads in this region that no longer exist. --function updates the named functions and leaves the others. + +The graph id is aws::AWS_REGION:workload:function/. + +IAM actions: + ` + strings.Join(awsv.FunctionPermissions, "\n ") +} + +func workloadFunctionAzureLong() string { + return `Inventory packages on function apps in the current Azure subscription. + +The command lists function apps in AZURE_LOCATION. A WEBSITE_RUN_FROM_PACKAGE URL is downloaded. A function that runs from a container image is read as an image. Other app settings are not stored. It does not attach a volume and does not need to run as root. Package bytes are deleted after the walk. + +A later om scan azure leaves the function workload and its packages in place. A full run of this command removes function workloads in this region that no longer exist. --function updates the named functions and leaves the others. + +The graph id is azure:::workload:function//. + +Azure RBAC actions: + ` + strings.Join(azurev.FunctionPermissions, "\n ") +} + +func workloadFunctionGCPLong() string { + return `Inventory packages on Cloud Functions in the current GCP project. + +The command lists functions in GCP_REGION. A source object in Cloud Storage is downloaded. A repository source is skipped. It does not attach a volume and does not need to run as root. Source bytes are deleted after the walk. + +A later om scan gcp leaves the function workload and its packages in place. A full run of this command removes function workloads in this region that no longer exist. --function updates the named functions and leaves the others. + +The graph id is gcp::GCP_REGION:workload:function/. + +IAM permissions: + ` + strings.Join(gcpv.FunctionPermissions, "\n ") +} + +func runScanWorkloadFunctionAWS(cmd *cobra.Command, args []string) error { + cfg := loadConfig() + ctx := cmd.Context() + collector, err := awscol.NewCollector(ctx, cfg.AWSRegion) + if err != nil { + return err + } + source, err := awsv.NewFunctions(ctx, cfg.AWSRegion, collector.AccountID) + if err != nil { + return err + } + return runFunctionScan(ctx, cfg, collector.AccountID, cfg.AWSRegion, source, functionReaders(awsFunctionTimeout, false), awsFunctions) +} + +func runScanWorkloadFunctionAzure(cmd *cobra.Command, args []string) error { + cfg := loadConfig() + if cfg.AzureSubscriptionID == "" { + return fmt.Errorf("AZURE_SUBSCRIPTION_ID is required") + } + source, err := azurev.NewFunctions(cfg.AzureSubscriptionID, cfg.AzureLocation) + if err != nil { + return err + } + return runFunctionScan(cmd.Context(), cfg, cfg.AzureSubscriptionID, azurev.ScanLocation(cfg.AzureLocation), source, functionReaders(azureFunctionTimeout, false), azureFunctions) +} + +func runScanWorkloadFunctionGCP(cmd *cobra.Command, args []string) error { + cfg := loadConfig() + if cfg.GCPProjectID == "" { + return fmt.Errorf("GCP_PROJECT_ID is required") + } + source, err := gcpv.NewFunctions(cmd.Context(), cfg.GCPProjectID, cfg.GCPRegion) + if err != nil { + return err + } + return runFunctionScan(cmd.Context(), cfg, cfg.GCPProjectID, cfg.GCPRegion, source, functionReaders(gcpFunctionTimeout, true), gcpFunctions) +} + +func functionReaders(timeout time.Duration, gcs bool) workload.FunctionReaders { + if timeout <= 0 { + timeout = 10 * time.Minute + } + readers := workload.FunctionReaders{ + Zip: func(ctx context.Context, rawURL string) ([]string, error) { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + return workload.ReadBundle(ctx, nil, rawURL) + }, + Image: func(ctx context.Context, ref string) ([]string, error) { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + return workload.ReadImage(ctx, ref) + }, + } + if gcs { + readers.Object = func(ctx context.Context, bucket, object string) ([]string, error) { + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + return gcpv.ReadObject(ctx, bucket, object) + } + } + return readers +} + +func runFunctionScan(ctx context.Context, cfg config.Config, account, region string, source workload.FunctionSource, readers workload.FunctionReaders, only []string) error { + store, err := openGraphStore(ctx, cfg) + if err != nil { + return err + } + defer store.Close() + + results, scanErr := workload.ScanFunctions(ctx, source, readers, only) + if scanErr != nil && len(results) == 0 { + return scanErr + } + nodes := make([]graph.Node, 0, len(results)) + wrote := 0 + for _, result := range results { + nodes = append(nodes, result.Node) + if result.Skipped != "" { + fmt.Printf("%s: skipped (%s)\n", result.Label, result.Skipped) + continue + } + fmt.Printf("%s: %d package identifiers\n", result.Label, packageCount(result.Node)) + wrote++ + } + if len(only) == 0 { + err = store.ReplaceFunctionWorkloads(ctx, account, region, nodes) + } else if len(nodes) > 0 { + err = store.UpsertBatch(ctx, graph.Batch{Nodes: nodes}) + } + fmt.Printf("Stored packages on %d workloads.\n", wrote) + return errors.Join(scanErr, err) +} + +func packageCount(node graph.Node) int { + switch items := node.Properties["packages"].(type) { + case []string: + return len(items) + default: + return 0 + } +} + +func init() { + scanWorkloadFunctionAWSCmd.Flags().DurationVar(&awsFunctionTimeout, "timeout", 10*time.Minute, "time limit for each function") + scanWorkloadFunctionAWSCmd.Flags().StringArrayVar(&awsFunctions, "function", nil, "function name (repeat to scan several; the default is every function in this region)") + scanWorkloadFunctionAzureCmd.Flags().DurationVar(&azureFunctionTimeout, "timeout", 10*time.Minute, "time limit for each function") + scanWorkloadFunctionAzureCmd.Flags().StringArrayVar(&azureFunctions, "function", nil, "function app name (repeat to scan several; the default is every function app in this region)") + scanWorkloadFunctionGCPCmd.Flags().DurationVar(&gcpFunctionTimeout, "timeout", 10*time.Minute, "time limit for each function") + scanWorkloadFunctionGCPCmd.Flags().StringArrayVar(&gcpFunctions, "function", nil, "function name (repeat to scan several; the default is every function in this region)") + scanWorkloadFunctionCmd.AddCommand(scanWorkloadFunctionAWSCmd, scanWorkloadFunctionAzureCmd, scanWorkloadFunctionGCPCmd) + scanWorkloadCmd.AddCommand(scanWorkloadFunctionCmd) +} diff --git a/internal/cmd/scan_workload_test.go b/internal/cmd/scan_workload_test.go index 5dd56bf..66d6dd8 100644 --- a/internal/cmd/scan_workload_test.go +++ b/internal/cmd/scan_workload_test.go @@ -67,6 +67,29 @@ func TestScanWorkloadRegistered(t *testing.T) { t.Errorf("image gcp help missing %s", action) } } + commandByName(t, workloadCmd, "container") + function := commandByName(t, workloadCmd, "function") + if function.Runnable() { + t.Fatal("om scan workload function runs a scan; name the cloud") + } + awsFunction := commandByName(t, function, "aws") + for _, action := range awsv.FunctionPermissions { + if !strings.Contains(awsFunction.Long, action) { + t.Errorf("function aws help missing %s", action) + } + } + azureFunction := commandByName(t, function, "azure") + for _, action := range azurev.FunctionPermissions { + if !strings.Contains(azureFunction.Long, action) { + t.Errorf("function azure help missing %s", action) + } + } + gcpFunction := commandByName(t, function, "gcp") + for _, action := range gcpv.FunctionPermissions { + if !strings.Contains(gcpFunction.Long, action) { + t.Errorf("function gcp help missing %s", action) + } + } } func commandByName(t *testing.T, parent *cobra.Command, name string) *cobra.Command { diff --git a/internal/collectors/aws/collector.go b/internal/collectors/aws/collector.go index 66d1dd3..1cc7942 100644 --- a/internal/collectors/aws/collector.go +++ b/internal/collectors/aws/collector.go @@ -441,6 +441,11 @@ func WorkloadNodeID(accountID, region, instanceID string) string { return fmt.Sprintf("aws:%s:%s:workload:%s", accountID, region, instanceID) } +// FunctionWorkloadNodeID is the graph id om scan workload function aws stores. +func FunctionWorkloadNodeID(accountID, region, name string) string { + return fmt.Sprintf("aws:%s:%s:workload:function/%s", accountID, region, name) +} + func (c *Collector) nodeID(kind, resource string) string { if kind == "workload" { return WorkloadNodeID(c.AccountID, c.Region, resource) diff --git a/internal/collectors/aws/collector_test.go b/internal/collectors/aws/collector_test.go index 558f130..1638c69 100644 --- a/internal/collectors/aws/collector_test.go +++ b/internal/collectors/aws/collector_test.go @@ -684,6 +684,9 @@ func TestWorkloadNodeID(t *testing.T) { if c.nodeID("workload", "i-1") != WorkloadNodeID("111122223333", "us-east-1", "i-1") { t.Fatalf("id = %s", c.nodeID("workload", "i-1")) } + if FunctionWorkloadNodeID("111122223333", "us-east-1", "pay") != "aws:111122223333:us-east-1:workload:function/pay" { + t.Fatalf("function id = %s", FunctionWorkloadNodeID("111122223333", "us-east-1", "pay")) + } } func testSecurityGroup(id string, open bool) ec2types.SecurityGroup { diff --git a/internal/collectors/azure/collector.go b/internal/collectors/azure/collector.go index 09f9da9..8a02ee1 100644 --- a/internal/collectors/azure/collector.go +++ b/internal/collectors/azure/collector.go @@ -382,6 +382,11 @@ func WorkloadNodeID(subscriptionID, location, name string) string { return fmt.Sprintf("azure:%s:%s:workload:%s", subscriptionID, location, name) } +// FunctionWorkloadNodeID is the graph id om scan workload function azure stores. +func FunctionWorkloadNodeID(subscriptionID, location, group, name string) string { + return fmt.Sprintf("azure:%s:%s:workload:function/%s/%s", subscriptionID, location, group, name) +} + func (c *Collector) nodeID(kind, resource string) string { if kind == "workload" { return WorkloadNodeID(c.SubscriptionID, c.Location, resource) diff --git a/internal/collectors/gcp/collector.go b/internal/collectors/gcp/collector.go index bf7e162..e239ac6 100644 --- a/internal/collectors/gcp/collector.go +++ b/internal/collectors/gcp/collector.go @@ -406,6 +406,11 @@ func WorkloadNodeID(projectID, zone, name string) string { return fmt.Sprintf("gcp:%s:%s:workload:%s", projectID, zone, name) } +// FunctionWorkloadNodeID is the graph id om scan workload function gcp stores. +func FunctionWorkloadNodeID(projectID, region, name string) string { + return fmt.Sprintf("gcp:%s:%s:workload:function/%s", projectID, region, name) +} + func (c *Collector) nodeID(region, kind, resource string) string { if kind == "workload" { return WorkloadNodeID(c.ProjectID, region, resource) diff --git a/internal/graph/store.go b/internal/graph/store.go index 0c4a7d2..9754be3 100644 --- a/internal/graph/store.go +++ b/internal/graph/store.go @@ -210,11 +210,12 @@ func deleteAbsentInventory(ctx context.Context, tx pgx.Tx, scopes []Scope, batch DELETE FROM nodes n WHERE n.type <> $2 AND NOT (n.id = ANY($3::text[])) + AND COALESCE(n.properties->>'workload_kind', '') <> $4 AND EXISTS ( SELECT 1 FROM `+scopeRows+` WHERE `+scopeMatch+` ) - `, string(scopeJSON), NodeFinding, keepNodes); err != nil { + `, string(scopeJSON), NodeFinding, keepNodes, WorkloadKindFunction); err != nil { return fmt.Errorf("delete absent inventory: %w", err) } @@ -436,6 +437,51 @@ func (s *Store) SetWorkloadPackages(ctx context.Context, id string, packages []s return nil } +// ReplaceFunctionWorkloads upserts function workloads and deletes other function +// workloads in the same account and region. An API inventory scan does not +// delete these nodes. Findings whose workload was removed are deleted with it. +func (s *Store) ReplaceFunctionWorkloads(ctx context.Context, accountID, region string, nodes []Node) error { + if accountID == "" || region == "" { + return fmt.Errorf("function workloads need an account and a region") + } + tx, err := s.pool.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + + if err := upsertBatch(ctx, tx, Batch{Nodes: nodes}); err != nil { + return err + } + keep := make([]string, len(nodes)) + for i, node := range nodes { + keep[i] = node.ID + } + if _, err := tx.Exec(ctx, ` + DELETE FROM nodes n + WHERE n.account_id = $1 + AND n.region = $2 + AND n.type = $3 + AND COALESCE(n.properties->>'workload_kind', '') = $4 + AND NOT (n.id = ANY($5::text[])) + `, accountID, region, NodeWorkload, WorkloadKindFunction, keep); err != nil { + return fmt.Errorf("delete absent function workloads: %w", err) + } + if _, err := tx.Exec(ctx, ` + DELETE FROM nodes f + WHERE f.type = $2 + AND f.account_id = $1 + AND COALESCE(f.properties->>'affected_resource', '') <> '' + AND NOT EXISTS ( + SELECT 1 FROM nodes t + WHERE t.id = f.properties->>'affected_resource' + ) + `, accountID, NodeFinding); err != nil { + return fmt.Errorf("delete orphan findings: %w", err) + } + return tx.Commit(ctx) +} + func (s *Store) GetNode(ctx context.Context, id string) (Node, error) { var node Node var props []byte diff --git a/internal/graph/store_test.go b/internal/graph/store_test.go index 3801f93..9a879c4 100644 --- a/internal/graph/store_test.go +++ b/internal/graph/store_test.go @@ -88,6 +88,75 @@ func TestReplaceInventoryDropsAbsentNodes(t *testing.T) { requireEdge(t, ctx, store, "finding:cve-kept:"+kept, kept, graph.EdgeViolates, true) } +func TestReplaceInventoryKeepsFunctionWorkloads(t *testing.T) { + ctx := context.Background() + store := openQueryFixture(t) + + const ( + account = "111122223333" + function = "aws:111122223333:us-east-1:workload:function/payments" + kept = "aws:111122223333:us-east-1:workload:i-web" + finding = "finding:cve-fn:" + function + ) + seed := graph.Batch{ + Nodes: []graph.Node{ + { + ID: function, Type: graph.NodeWorkload, Name: "payments", Provider: "aws", + Region: "us-east-1", AccountID: account, + Properties: map[string]any{ + graph.PropWorkloadKind: graph.WorkloadKindFunction, + "packages": []any{"pkg:npm/lodash@4.17.21"}, + }, + }, + {ID: kept, Type: graph.NodeWorkload, Name: "web", Provider: "aws", Region: "us-east-1", AccountID: account}, + findingNode("cve-fn", function, account, "cve"), + }, + } + if err := store.UpsertBatch(ctx, seed); err != nil { + t.Fatalf("seed: %v", err) + } + err := store.ReplaceInventory(ctx, []graph.Scope{{ + AccountID: account, + Regions: []string{"us-east-1", ""}, + }}, graph.Batch{Nodes: []graph.Node{ + {ID: kept, Type: graph.NodeWorkload, Name: "web", Provider: "aws", Region: "us-east-1", AccountID: account}, + }}) + if err != nil { + t.Fatalf("replace: %v", err) + } + requireNode(t, ctx, store, function, true) + requireNode(t, ctx, store, finding, true) + requireNode(t, ctx, store, kept, true) + + gone := "aws:111122223333:us-east-1:workload:function/old" + if err := store.ReplaceFunctionWorkloads(ctx, account, "us-east-1", []graph.Node{{ + ID: function, Type: graph.NodeWorkload, Name: "payments", Provider: "aws", + Region: "us-east-1", AccountID: account, + Properties: map[string]any{ + graph.PropWorkloadKind: graph.WorkloadKindFunction, + "packages": []string{"pkg:npm/lodash@4.17.21"}, + }, + }}); err != nil { + t.Fatalf("functions: %v", err) + } + if err := store.UpsertBatch(ctx, graph.Batch{Nodes: []graph.Node{{ + ID: gone, Type: graph.NodeWorkload, Name: "old", Provider: "aws", + Region: "us-east-1", AccountID: account, + Properties: map[string]any{graph.PropWorkloadKind: graph.WorkloadKindFunction}, + }}}); err != nil { + t.Fatal(err) + } + if err := store.ReplaceFunctionWorkloads(ctx, account, "us-east-1", []graph.Node{{ + ID: function, Type: graph.NodeWorkload, Name: "payments", Provider: "aws", + Region: "us-east-1", AccountID: account, + Properties: map[string]any{graph.PropWorkloadKind: graph.WorkloadKindFunction}, + }}); err != nil { + t.Fatal(err) + } + requireNode(t, ctx, store, function, true) + requireNode(t, ctx, store, gone, false) +} + func TestReplaceInventoryKeepsOtherNamespaces(t *testing.T) { ctx := context.Background() store := openQueryFixture(t) diff --git a/internal/graph/types.go b/internal/graph/types.go index c0b91f6..86c1894 100644 --- a/internal/graph/types.go +++ b/internal/graph/types.go @@ -31,6 +31,13 @@ const ( // InternetNodeID is the stable id of the synthetic internet node. const InternetNodeID = collector.InternetNodeID +const ( + // PropWorkloadKind marks a workload an API inventory scan must leave in place. + PropWorkloadKind = "workload_kind" + // WorkloadKindFunction is the value om scan workload function writes. + WorkloadKindFunction = "function" +) + type Node struct { ID string `json:"id"` Type string `json:"type"` diff --git a/internal/workload/archive.go b/internal/workload/archive.go new file mode 100644 index 0000000..8284173 --- /dev/null +++ b/internal/workload/archive.go @@ -0,0 +1,315 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "archive/tar" + "archive/zip" + "fmt" + "io" + "os" + "path" + "path/filepath" + "sort" + "strings" +) + +// WalkLayerTars applies image layers in order and returns CPE 2.3 names and +// package URLs. It reads package databases, Maven jars, Python distributions, +// and npm package.json files. Other file bytes are discarded. +func WalkLayerTars(layers []io.Reader) ([]string, error) { + tree := newLayerTree() + for _, layer := range layers { + if err := tree.addTar(layer); err != nil { + return nil, err + } + } + return tree.packages() +} + +// WalkZip reads a function bundle the same way WalkLayerTars reads one layer. +func WalkZip(path string) ([]string, error) { + zr, err := zip.OpenReader(path) + if err != nil { + return nil, fmt.Errorf("read deployment package: %w", err) + } + defer zr.Close() + + tree := newLayerTree() + for _, file := range zr.File { + if file.FileInfo().IsDir() { + continue + } + if file.UncompressedSize64 > maxBundleBytes && !isJar(file.Name) { + continue + } + rc, err := file.Open() + if err != nil { + return nil, fmt.Errorf("read deployment package: %w", err) + } + err = tree.add(file.Name, rc, int64(file.UncompressedSize64)) + rc.Close() + if err != nil { + return nil, err + } + } + return tree.packages() +} + +type layerTree struct { + files map[string][]byte + langs map[string][]string + count int +} + +func newLayerTree() *layerTree { + return &layerTree{ + files: map[string][]byte{}, + langs: map[string][]string{}, + } +} + +func (t *layerTree) addTar(r io.Reader) error { + tr := tar.NewReader(r) + for { + hdr, err := tr.Next() + if err == io.EOF { + return nil + } + if err != nil { + return fmt.Errorf("read layer: %w", err) + } + switch hdr.Typeflag { + case tar.TypeReg, tar.TypeRegA: + if err := t.add(hdr.Name, tr, hdr.Size); err != nil { + return err + } + case tar.TypeLink: + t.copyLink(hdr.Name, hdr.Linkname) + default: + } + } +} + +func (t *layerTree) add(name string, r io.Reader, size int64) error { + rel, ok := cleanRel(name) + if !ok { + return nil + } + if isWhiteout(rel) { + t.applyWhiteout(rel) + return nil + } + if !interesting(rel) { + return nil + } + if t.count >= maxInterestingFile { + return fmt.Errorf("more than %d package files", maxInterestingFile) + } + if isJar(rel) { + ids, err := mavenIDsFromJar(r, size) + if err != nil { + return err + } + if len(ids) == 0 { + delete(t.langs, rel) + return nil + } + t.langs[rel] = ids + t.count++ + return nil + } + limit := int64(maxMetaBytes) + if isPackageDB(rel) { + limit = maxPackageDBBytes + } + if size > limit { + if isPackageDB(rel) { + return fmt.Errorf("%s is %d bytes", path.Base(rel), size) + } + return nil + } + body, err := io.ReadAll(io.LimitReader(r, limit+1)) + if err != nil { + return err + } + if int64(len(body)) > limit { + if isPackageDB(rel) { + return fmt.Errorf("%s is larger than %d bytes", path.Base(rel), limit) + } + return nil + } + if isPackageDB(rel) || isOSRelease(rel) { + t.files[rel] = body + t.count++ + return nil + } + ids := languageIDsFromMeta(rel, body) + if len(ids) == 0 { + delete(t.langs, rel) + return nil + } + t.langs[rel] = ids + t.count++ + return nil +} + +func (t *layerTree) copyLink(name, link string) { + rel, ok := cleanRel(name) + target, tok := cleanRel(link) + if !ok || !tok { + return + } + if body, ok := t.files[target]; ok && (isPackageDB(rel) || isOSRelease(rel)) { + t.files[rel] = body + } + if ids, ok := t.langs[target]; ok { + t.langs[rel] = ids + } +} + +func (t *layerTree) applyWhiteout(rel string) { + dir := path.Dir(rel) + base := path.Base(rel) + if dir == "." { + dir = "" + } + if base == ".wh..wh..opq" { + prefix := dir + if prefix != "" { + prefix += "/" + } + t.deletePrefix(prefix) + return + } + name := strings.TrimPrefix(base, ".wh.") + target := name + if dir != "" { + target = dir + "/" + name + } + delete(t.files, target) + delete(t.langs, target) +} + +func (t *layerTree) deletePrefix(prefix string) { + if prefix == "" { + t.files = map[string][]byte{} + t.langs = map[string][]string{} + return + } + for key := range t.files { + if strings.HasPrefix(key, prefix) { + delete(t.files, key) + } + } + for key := range t.langs { + if strings.HasPrefix(key, prefix) { + delete(t.langs, key) + } + } +} + +func (t *layerTree) packages() ([]string, error) { + root, err := os.MkdirTemp("", "om-packages-") + if err != nil { + return nil, err + } + defer os.RemoveAll(root) + + for rel, body := range t.files { + if !isPackageDB(rel) && !isOSRelease(rel) { + continue + } + dest := filepath.Join(root, filepath.FromSlash(rel)) + if !strings.HasPrefix(dest, root+string(os.PathSeparator)) && dest != root { + continue + } + if err := os.MkdirAll(filepath.Dir(dest), 0o700); err != nil { + return nil, err + } + if err := os.WriteFile(dest, body, 0o600); err != nil { + return nil, err + } + } + + var ids []string + if HasPackageDB(root) { + got, err := Walk(root) + if err != nil { + return nil, err + } + ids = append(ids, got...) + } + for _, list := range t.langs { + ids = append(ids, list...) + } + ids = uniqueSorted(ids) + if len(ids) == 0 { + return nil, ErrNoPackages + } + return ids, nil +} + +func interesting(rel string) bool { + if isPackageDB(rel) || isOSRelease(rel) || isJar(rel) { + return true + } + base := path.Base(rel) + if base == "package.json" { + return true + } + if strings.HasSuffix(rel, ".dist-info/METADATA") { + return true + } + return strings.Contains(rel, "META-INF/maven/") && base == "pom.properties" +} + +func isJar(rel string) bool { + return strings.HasSuffix(strings.ToLower(rel), ".jar") +} + +func isPackageDB(rel string) bool { + for _, candidate := range packageDBPaths { + if rel == candidate { + return true + } + } + return false +} + +func isOSRelease(rel string) bool { + return rel == "etc/os-release" || rel == "usr/lib/os-release" +} + +func isWhiteout(rel string) bool { + return strings.HasPrefix(path.Base(rel), ".wh.") +} + +func cleanRel(name string) (string, bool) { + name = strings.TrimPrefix(name, "./") + name = strings.TrimPrefix(name, "/") + name = path.Clean(name) + if name == "." || name == "" || strings.HasPrefix(name, "../") || name == ".." { + return "", false + } + return name, true +} + +func uniqueSorted(ids []string) []string { + seen := map[string]struct{}{} + var out []string + for _, id := range ids { + id = strings.TrimSpace(id) + if id == "" { + continue + } + if _, ok := seen[id]; ok { + continue + } + seen[id] = struct{}{} + out = append(out, id) + } + sort.Strings(out) + return out +} diff --git a/internal/workload/archive_test.go b/internal/workload/archive_test.go new file mode 100644 index 0000000..42bf98d --- /dev/null +++ b/internal/workload/archive_test.go @@ -0,0 +1,154 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "archive/tar" + "archive/zip" + "bytes" + "compress/gzip" + "io" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestWalkLayerTarsReadsPackagesAndDropsWhiteouts(t *testing.T) { + first := tarLayer(t, map[string][]byte{ + "etc/os-release": []byte("ID=ubuntu\nVERSION_ID=\"22.04\"\n"), + "var/lib/dpkg/status": []byte("Package: openssl\nStatus: install ok installed\nArchitecture: amd64\nVersion: 1.1.1n-0ubuntu1\n\n"), + "app/log4j-core.jar": jarWithPOM(t, "org.apache.logging.log4j", "log4j-core", "2.14.1"), + "../escape/status": []byte("Package: stolen\nStatus: install ok installed\nVersion: 1\n\n"), + }) + second := tarLayer(t, map[string][]byte{ + "app/.wh.log4j-core.jar": {}, + "node_modules/lodash/package.json": []byte(`{"name":"lodash","version":"4.17.21"}`), + "lib/python3.11/site-packages/requests-2.28.1.dist-info/METADATA": []byte("Name: Requests\nVersion: 2.28.1\n\n"), + }) + ids, err := WalkLayerTars([]io.Reader{bytes.NewReader(first), bytes.NewReader(second)}) + if err != nil { + t.Fatal(err) + } + joined := strings.Join(ids, "\n") + for _, want := range []string{ + "cpe:2.3:a:openssl:openssl:1.1.1n:*:*:*:*:*:*:*", + "pkg:deb/ubuntu/openssl@1.1.1n-0ubuntu1?arch=amd64&distro=ubuntu-22.04", + "pkg:npm/lodash@4.17.21", + "pkg:pypi/requests@2.28.1", + } { + if !strings.Contains(joined, want) { + t.Errorf("missing %s\n%s", want, joined) + } + } + if strings.Contains(joined, "log4j") || strings.Contains(joined, "stolen") { + t.Fatalf("removed or escaped bytes were stored\n%s", joined) + } +} + +func TestWalkZipReadsMavenAndSkipsFileURLs(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "bundle.zip") + writeZip(t, path, map[string]string{ + "node_modules/left-pad/package.json": `{"name":"left-pad","version":"1.3.0"}`, + "package.json": `{"name":"app","version":"file:../app"}`, + "META-INF/maven/org.apache.logging.log4j/log4j-core/pom.properties": "groupId=org.apache.logging.log4j\nartifactId=log4j-core\nversion=2.14.1\n", + }) + ids, err := WalkZip(path) + if err != nil { + t.Fatal(err) + } + joined := strings.Join(ids, "\n") + if !strings.Contains(joined, "pkg:npm/left-pad@1.3.0") { + t.Fatalf("packages =\n%s", joined) + } + if !strings.Contains(joined, "pkg:maven/org.apache.logging.log4j/log4j-core@2.14.1") { + t.Fatalf("packages =\n%s", joined) + } + if strings.Contains(joined, "file:") { + t.Fatalf("file version was stored\n%s", joined) + } +} + +func TestWalkLayerTarsEmpty(t *testing.T) { + _, err := WalkLayerTars([]io.Reader{bytes.NewReader(tarLayer(t, map[string][]byte{ + "readme.txt": []byte("hello"), + }))}) + if err != ErrNoPackages { + t.Fatalf("err = %v", err) + } +} + +func tarLayer(t *testing.T, files map[string][]byte) []byte { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + for name, body := range files { + hdr := &tar.Header{Name: name, Mode: 0o644, Size: int64(len(body))} + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if _, err := tw.Write(body); err != nil { + t.Fatal(err) + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func jarWithPOM(t *testing.T, group, artifact, version string) []byte { + t.Helper() + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + w, err := zw.Create("META-INF/maven/" + group + "/" + artifact + "/pom.properties") + if err != nil { + t.Fatal(err) + } + if _, err := w.Write([]byte("groupId=" + group + "\nartifactId=" + artifact + "\nversion=" + version + "\n")); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} + +func writeZip(t *testing.T, path string, files map[string]string) { + t.Helper() + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + zw := zip.NewWriter(f) + for name, body := range files { + w, err := zw.Create(name) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write([]byte(body)); err != nil { + t.Fatal(err) + } + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } +} + +func gzipBytes(t *testing.T, body []byte) []byte { + t.Helper() + var buf bytes.Buffer + zw := gzip.NewWriter(&buf) + if _, err := zw.Write(body); err != nil { + t.Fatal(err) + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } + return buf.Bytes() +} diff --git a/internal/workload/aws/function.go b/internal/workload/aws/function.go new file mode 100644 index 0000000..dfda3b9 --- /dev/null +++ b/internal/workload/aws/function.go @@ -0,0 +1,93 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package aws + +import ( + "context" + "fmt" + "sort" + + awscol "github.com/OpenSourceOM/core/internal/collectors/aws" + "github.com/OpenSourceOM/core/internal/workload" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/lambda" + lambdatypes "github.com/aws/aws-sdk-go-v2/service/lambda/types" +) + +// FunctionPermissions are the IAM actions om scan workload function aws adds. +// GetFunction returns environment variables. This scan does not read them. +var FunctionPermissions = []string{ + "lambda:ListFunctions", + "lambda:GetFunction", +} + +// Functions lists Lambda functions in one region. The presigned package URL +// is returned to the caller and is not stored. +type Functions struct { + api *lambda.Client + region string + account string +} + +// NewFunctions uses the default AWS credential chain. +func NewFunctions(ctx context.Context, region, accountID string) (*Functions, error) { + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region)) + if err != nil { + return nil, fmt.Errorf("load aws config: %w", err) + } + return &Functions{api: lambda.NewFromConfig(cfg), region: region, account: accountID}, nil +} + +func (f *Functions) List(ctx context.Context) ([]workload.Function, error) { + var out []workload.Function + paginator := lambda.NewListFunctionsPaginator(f.api, &lambda.ListFunctionsInput{}) + for paginator.HasMorePages() { + page, err := paginator.NextPage(ctx) + if err != nil { + return nil, fmt.Errorf("list functions: %w", err) + } + for _, fn := range page.Functions { + name := aws.ToString(fn.FunctionName) + if name == "" { + continue + } + got, err := f.api.GetFunction(ctx, &lambda.GetFunctionInput{FunctionName: aws.String(name)}) + if err != nil { + return nil, fmt.Errorf("get function %s: %w", name, err) + } + out = append(out, functionFrom(f.account, f.region, name, got)) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} + +func functionFrom(account, region, name string, got *lambda.GetFunctionOutput) workload.Function { + item := workload.Function{ + Name: name, + NodeID: awscol.FunctionWorkloadNodeID(account, region, name), + Region: region, + AccountID: account, + Provider: "aws", + } + if got == nil || got.Configuration == nil { + item.Skip = "no deployment package" + return item + } + cfg := got.Configuration + item.ResourceID = aws.ToString(cfg.FunctionArn) + item.Runtime = string(cfg.Runtime) + if got.Code != nil && cfg.PackageType == lambdatypes.PackageTypeImage { + item.Image = aws.ToString(got.Code.ImageUri) + return item + } + if got.Code != nil { + item.URL = aws.ToString(got.Code.Location) + } + if item.URL == "" && item.Image == "" { + item.Skip = "no deployment package" + } + return item +} diff --git a/internal/workload/aws/function_test.go b/internal/workload/aws/function_test.go new file mode 100644 index 0000000..ec86e72 --- /dev/null +++ b/internal/workload/aws/function_test.go @@ -0,0 +1,48 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package aws + +import ( + "testing" + + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/service/lambda" + lambdatypes "github.com/aws/aws-sdk-go-v2/service/lambda/types" +) + +func TestFunctionFromZipKeepsURLOffTheName(t *testing.T) { + got := functionFrom("111122223333", "us-east-1", "payments", &lambda.GetFunctionOutput{ + Configuration: &lambdatypes.FunctionConfiguration{ + FunctionArn: aws.String("arn:aws:lambda:us-east-1:111122223333:function:payments"), + FunctionName: aws.String("payments"), + Runtime: lambdatypes.RuntimeNodejs20x, + PackageType: lambdatypes.PackageTypeZip, + }, + Code: &lambdatypes.FunctionCodeLocation{ + Location: aws.String("https://example.invalid/code.zip?sig=secret-token"), + }, + }) + if got.URL == "" || got.Image != "" || got.Runtime != string(lambdatypes.RuntimeNodejs20x) { + t.Fatalf("function = %+v", got) + } + if got.NodeID != "aws:111122223333:us-east-1:workload:function/payments" { + t.Fatalf("id = %s", got.NodeID) + } +} + +func TestFunctionFromImageDropsZipURL(t *testing.T) { + got := functionFrom("111122223333", "us-east-1", "payments", &lambda.GetFunctionOutput{ + Configuration: &lambdatypes.FunctionConfiguration{ + FunctionArn: aws.String("arn:aws:lambda:us-east-1:111122223333:function:payments"), + PackageType: lambdatypes.PackageTypeImage, + }, + Code: &lambdatypes.FunctionCodeLocation{ + Location: aws.String("https://example.invalid/code.zip?sig=secret-token"), + ImageUri: aws.String("123.dkr.ecr.us-east-1.amazonaws.com/app:v1"), + }, + }) + if got.URL != "" || got.Image == "" { + t.Fatalf("function = %+v", got) + } +} diff --git a/internal/workload/azure/function.go b/internal/workload/azure/function.go new file mode 100644 index 0000000..0fc128e --- /dev/null +++ b/internal/workload/azure/function.go @@ -0,0 +1,230 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package azure + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "sort" + "strings" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" + "github.com/Azure/azure-sdk-for-go/sdk/azidentity" + azurecol "github.com/OpenSourceOM/core/internal/collectors/azure" + "github.com/OpenSourceOM/core/internal/workload" +) + +// FunctionPermissions are the Azure RBAC actions om scan workload function azure adds. +// App settings are read only to find a package URL. The values are not stored. +var FunctionPermissions = []string{ + "Microsoft.Web/sites/read", + "Microsoft.Web/sites/config/read", +} + +const webAPIVersion = "2023-12-01" + +// Functions lists function apps in one subscription. +type Functions struct { + sub string + location string + cred azcore.TokenCredential + http *http.Client + base string +} + +// NewFunctions uses the default Azure credential. +// location limits the scan to function apps in that region. +func NewFunctions(subscriptionID, location string) (*Functions, error) { + cred, err := azidentity.NewDefaultAzureCredential(nil) + if err != nil { + return nil, fmt.Errorf("azure credentials: %w", err) + } + return &Functions{ + sub: subscriptionID, + location: normalizeLocation(location), + cred: cred, + http: http.DefaultClient, + base: "https://management.azure.com", + }, nil +} + +func (f *Functions) List(ctx context.Context) ([]workload.Function, error) { + location := f.location + var out []workload.Function + next := f.base + "/subscriptions/" + f.sub + "/providers/Microsoft.Web/sites?api-version=" + webAPIVersion + for pages := 0; next != "" && pages < 100; pages++ { + body, err := f.get(ctx, next) + if err != nil { + return nil, err + } + sites, link, err := parseSites(body) + if err != nil { + return nil, err + } + for _, site := range sites { + if !strings.Contains(strings.ToLower(site.Kind), "functionapp") { + continue + } + if !sameLocation(site.Location, location) { + continue + } + item, err := f.function(ctx, site, location) + if err != nil { + return nil, err + } + out = append(out, item) + } + next = link + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} + +func (f *Functions) function(ctx context.Context, site rawSite, location string) (workload.Function, error) { + region := normalizeLocation(location) + group := resourceGroup(site.ID) + item := workload.Function{ + Name: site.Name, + NodeID: azurecol.FunctionWorkloadNodeID(f.sub, region, group, site.Name), + ResourceID: site.ID, + Region: region, + AccountID: f.sub, + Provider: "azure", + } + settings, err := f.post(ctx, f.base+site.ID+"/config/appsettings/list?api-version="+webAPIVersion) + if err != nil { + return item, fmt.Errorf("%s: %w", site.Name, err) + } + if raw := packageURL(settings); raw != "" { + item.URL = raw + return item, nil + } + web, err := f.get(ctx, f.base+site.ID+"/config/web?api-version="+webAPIVersion) + if err != nil { + return item, fmt.Errorf("%s: %w", site.Name, err) + } + if image := containerImage(web); image != "" { + item.Image = image + return item, nil + } + item.Skip = "no deployment package" + return item, nil +} + +func (f *Functions) get(ctx context.Context, endpoint string) ([]byte, error) { + return f.request(ctx, http.MethodGet, endpoint, nil) +} + +func (f *Functions) post(ctx context.Context, endpoint string) ([]byte, error) { + return f.request(ctx, http.MethodPost, endpoint, strings.NewReader("{}")) +} + +func (f *Functions) request(ctx context.Context, method, endpoint string, payload io.Reader) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, method, endpoint, payload) + if err != nil { + return nil, err + } + if payload != nil { + req.Header.Set("Content-Type", "application/json") + } + token, err := f.cred.GetToken(ctx, policy.TokenRequestOptions{Scopes: []string{"https://management.azure.com/.default"}}) + if err != nil { + return nil, fmt.Errorf("azure credentials: %w", err) + } + req.Header.Set("Authorization", "Bearer "+token.Token) + resp, err := f.http.Do(req) + if err != nil { + return nil, fmt.Errorf("list function apps: %w", err) + } + defer resp.Body.Close() + raw, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + if err != nil { + return nil, fmt.Errorf("list function apps: %w", err) + } + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("list function apps: status %d", resp.StatusCode) + } + return raw, nil +} + +type rawSite struct { + ID string + Name string + Kind string + Location string +} + +func parseSites(body []byte) ([]rawSite, string, error) { + var page struct { + Value []struct { + ID string `json:"id"` + Name string `json:"name"` + Kind string `json:"kind"` + Location string `json:"location"` + } `json:"value"` + NextLink string `json:"nextLink"` + } + if err := json.Unmarshal(body, &page); err != nil { + return nil, "", fmt.Errorf("list function apps: response is not json") + } + var out []rawSite + for _, site := range page.Value { + if site.Name == "" || site.ID == "" { + continue + } + out = append(out, rawSite{ID: site.ID, Name: site.Name, Kind: site.Kind, Location: site.Location}) + } + return out, page.NextLink, nil +} + +func packageURL(body []byte) string { + var page struct { + Properties map[string]string `json:"properties"` + } + if err := json.Unmarshal(body, &page); err != nil { + return "" + } + raw := strings.TrimSpace(page.Properties["WEBSITE_RUN_FROM_PACKAGE"]) + if strings.HasPrefix(raw, "https://") || strings.HasPrefix(raw, "http://") { + return raw + } + return "" +} + +func containerImage(body []byte) string { + var page struct { + Properties struct { + LinuxFxVersion string `json:"linuxFxVersion"` + WindowsFxVersion string `json:"windowsFxVersion"` + } `json:"properties"` + } + if err := json.Unmarshal(body, &page); err != nil { + return "" + } + for _, raw := range []string{page.Properties.LinuxFxVersion, page.Properties.WindowsFxVersion} { + image, ok := strings.CutPrefix(raw, "DOCKER|") + image = strings.TrimSpace(image) + if ok && image != "" { + if i := strings.Index(image, "|"); i >= 0 { + image = image[:i] + } + return image + } + } + return "" +} + +func resourceGroup(id string) string { + parts := strings.Split(id, "/") + for i, part := range parts { + if strings.EqualFold(part, "resourceGroups") && i+1 < len(parts) { + return parts[i+1] + } + } + return "" +} diff --git a/internal/workload/azure/function_test.go b/internal/workload/azure/function_test.go new file mode 100644 index 0000000..95a1b07 --- /dev/null +++ b/internal/workload/azure/function_test.go @@ -0,0 +1,100 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package azure + +import ( + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/Azure/azure-sdk-for-go/sdk/azcore" + "github.com/Azure/azure-sdk-for-go/sdk/azcore/policy" +) + +func TestPackageURLIgnoresOtherSettings(t *testing.T) { + body := []byte(`{"properties":{"WEBSITE_RUN_FROM_PACKAGE":"https://example.invalid/pkg.zip?sig=secret","AzureWebJobsStorage":"DefaultEndpointsProtocol=https;AccountKey=secret"}}`) + if got := packageURL(body); got != "https://example.invalid/pkg.zip?sig=secret" { + t.Fatalf("url = %s", got) + } + if packageURL([]byte(`{"properties":{"WEBSITE_RUN_FROM_PACKAGE":"1","AzureWebJobsStorage":"keep"}}`)) != "" { + t.Fatal("a local package flag was treated as a URL") + } +} + +func TestContainerImage(t *testing.T) { + body := []byte(`{"properties":{"linuxFxVersion":"DOCKER|mcr.microsoft.com/azure-functions/node:4"}}`) + if got := containerImage(body); got != "mcr.microsoft.com/azure-functions/node:4" { + t.Fatalf("image = %s", got) + } +} + +func TestParseSitesSkipsNonFunctions(t *testing.T) { + body := []byte(`{"value":[ + {"id":"/subscriptions/sub/resourceGroups/apps/providers/Microsoft.Web/sites/pay","name":"pay","kind":"functionapp,linux","location":"East US"}, + {"id":"/subscriptions/sub/resourceGroups/apps/providers/Microsoft.Web/sites/web","name":"web","kind":"app","location":"eastus"} + ]}`) + sites, next, err := parseSites(body) + if err != nil || next != "" || len(sites) != 2 { + t.Fatalf("sites = %+v %q %v", sites, next, err) + } + if resourceGroup(sites[0].ID) != "apps" { + t.Fatalf("group = %s", resourceGroup(sites[0].ID)) + } + if !sameLocation(sites[0].Location, "eastus") { + t.Fatal("location was not normalized") + } +} + +func TestListPostsAppSettings(t *testing.T) { + var sawPost bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch { + case r.Method == http.MethodGet && strings.HasSuffix(r.URL.Path, "/providers/Microsoft.Web/sites"): + _, _ = w.Write([]byte(`{"value":[{"id":"/subscriptions/sub/resourceGroups/apps/providers/Microsoft.Web/sites/pay","name":"pay","kind":"functionapp","location":"eastus"}]}`)) + case r.Method == http.MethodPost && strings.Contains(r.URL.Path, "/config/appsettings/list"): + sawPost = true + if r.Header.Get("Content-Type") != "application/json" { + t.Errorf("content-type = %s", r.Header.Get("Content-Type")) + } + _, _ = w.Write([]byte(`{"properties":{"WEBSITE_RUN_FROM_PACKAGE":"https://example.invalid/pkg.zip","AzureWebJobsStorage":"AccountKey=secret"}}`)) + default: + t.Errorf("unexpected %s %s", r.Method, r.URL.Path) + http.NotFound(w, r) + } + })) + defer srv.Close() + + functions := &Functions{ + sub: "sub", + location: "eastus", + cred: fakeToken{}, + http: srv.Client(), + base: srv.URL, + } + items, err := functions.List(context.Background()) + if err != nil { + t.Fatal(err) + } + if !sawPost { + t.Fatal("app settings were not requested with POST") + } + if len(items) != 1 || items[0].URL != "https://example.invalid/pkg.zip" { + t.Fatalf("items = %+v", items) + } + if items[0].NodeID != "azure:sub:eastus:workload:function/apps/pay" { + t.Fatalf("id = %s", items[0].NodeID) + } + if strings.Contains(items[0].URL, "AccountKey") { + t.Fatal("storage secret was copied onto the function") + } +} + +type fakeToken struct{} + +func (fakeToken) GetToken(context.Context, policy.TokenRequestOptions) (azcore.AccessToken, error) { + return azcore.AccessToken{Token: "token", ExpiresOn: time.Now().Add(time.Hour)}, nil +} diff --git a/internal/workload/azure/scan.go b/internal/workload/azure/scan.go index be1aba0..2259621 100644 --- a/internal/workload/azure/scan.go +++ b/internal/workload/azure/scan.go @@ -357,6 +357,11 @@ func findMachine(machines []Machine, want string) (Machine, error) { return found[0], nil } +// ScanLocation is the region stored on a function workload. +func ScanLocation(location string) string { + return normalizeLocation(location) +} + func normalizeLocation(location string) string { return strings.ToLower(strings.ReplaceAll(location, " ", "")) } diff --git a/internal/workload/fetch.go b/internal/workload/fetch.go new file mode 100644 index 0000000..24ea355 --- /dev/null +++ b/internal/workload/fetch.go @@ -0,0 +1,92 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" +) + +// MaxBundleBytes is the largest deployment package this scan reads. +func MaxBundleBytes() int64 { return maxBundleBytes } + +// Download copies an https or http URL to dest and stops after maxBytes. +// The URL is omitted from errors. Callers use it for a deployment package +// and delete dest after WalkZip. +func Download(ctx context.Context, client *http.Client, rawURL, dest string, maxBytes int64) error { + if client == nil { + client = http.DefaultClient + } + if maxBytes <= 0 { + maxBytes = maxBundleBytes + } + parsed, err := url.Parse(rawURL) + if err != nil || (parsed.Scheme != "https" && parsed.Scheme != "http") || parsed.Host == "" { + return fmt.Errorf("deployment package URL is not https") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, rawURL, nil) + if err != nil { + return fmt.Errorf("deployment package: %w", err) + } + resp, err := client.Do(req) + if err != nil { + return fmt.Errorf("deployment package: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("deployment package: status %d", resp.StatusCode) + } + if resp.ContentLength > maxBytes { + return fmt.Errorf("deployment package is larger than %d bytes", maxBytes) + } + f, err := os.OpenFile(dest, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o600) + if err != nil { + return err + } + defer f.Close() + n, err := io.Copy(f, io.LimitReader(resp.Body, maxBytes+1)) + if err != nil { + return fmt.Errorf("deployment package: %w", err) + } + if n > maxBytes { + return fmt.Errorf("deployment package is larger than %d bytes", maxBytes) + } + return nil +} + +// BundleFile downloads rawURL to a temporary file. The caller removes the path. +func BundleFile(ctx context.Context, client *http.Client, rawURL string) (string, error) { + f, err := os.CreateTemp("", "om-bundle-") + if err != nil { + return "", err + } + name := f.Name() + if err := f.Close(); err != nil { + os.Remove(name) + return "", err + } + if err := Download(ctx, client, rawURL, name, maxBundleBytes); err != nil { + os.Remove(name) + return "", err + } + return name, nil +} + +// ReadBundle downloads a deployment package, walks it, and deletes the file. +func ReadBundle(ctx context.Context, client *http.Client, rawURL string) ([]string, error) { + if strings.TrimSpace(rawURL) == "" { + return nil, fmt.Errorf("deployment package URL is empty") + } + path, err := BundleFile(ctx, client, rawURL) + if err != nil { + return nil, err + } + defer os.Remove(path) + return WalkZip(path) +} diff --git a/internal/workload/function.go b/internal/workload/function.go new file mode 100644 index 0000000..62de324 --- /dev/null +++ b/internal/workload/function.go @@ -0,0 +1,171 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "context" + "errors" + "fmt" + "sort" + + "github.com/OpenSourceOM/core/internal/graph" +) + +// Function is one deployment package or container image. +// URL, Bucket, and Object are read and are not copied onto the graph node. +type Function struct { + Name string + NodeID string + ResourceID string + Runtime string + Image string + URL string + Bucket string + Object string + Region string + AccountID string + Provider string + Skip string +} + +// FunctionSource lists functions in one account and region. +type FunctionSource interface { + List(ctx context.Context) ([]Function, error) +} + +// FunctionReaders open a bundle. Each field is used only for that source. +type FunctionReaders struct { + Zip func(ctx context.Context, rawURL string) ([]string, error) + Image func(ctx context.Context, ref string) ([]string, error) + Object func(ctx context.Context, bucket, object string) ([]string, error) +} + +// FunctionResult is one function after its bundle is deleted. +// A skip leaves packages already stored on the node unchanged. +type FunctionResult struct { + Node graph.Node + Label string + Skipped string +} + +// ScanFunctions reads each function once. only limits the scan to those names. +// A name that is not in the list is an error, and no function is read. +func ScanFunctions(ctx context.Context, source FunctionSource, readers FunctionReaders, only []string) ([]FunctionResult, error) { + if source == nil { + return nil, fmt.Errorf("function scan is missing a client") + } + items, err := source.List(ctx) + if err != nil { + return nil, err + } + items, err = selectFunctions(items, only) + if err != nil { + return nil, err + } + sort.Slice(items, func(i, j int) bool { + return items[i].Name < items[j].Name + }) + var ( + results []FunctionResult + failed []error + ) + for _, item := range items { + result, err := readFunction(ctx, item, readers) + results = append(results, result) + if err != nil { + failed = append(failed, err) + } + } + return results, errors.Join(failed...) +} + +func selectFunctions(items []Function, only []string) ([]Function, error) { + if len(only) == 0 { + return items, nil + } + byName := map[string]Function{} + for _, item := range items { + byName[item.Name] = item + } + var out []Function + for _, name := range only { + item, ok := byName[name] + if !ok { + return nil, fmt.Errorf("function %s is not in this region", name) + } + out = append(out, item) + } + return out, nil +} + +func readFunction(ctx context.Context, item Function, readers FunctionReaders) (FunctionResult, error) { + label := item.Name + if label == "" { + label = item.NodeID + } + result := FunctionResult{Label: label, Node: functionNode(item, nil)} + if item.Skip != "" { + result.Skipped = item.Skip + return result, nil + } + packages, err := readFunctionPackages(ctx, item, readers) + if err != nil { + if reason, ok := Reason(err); ok { + result.Skipped = reason + return result, nil + } + return result, fmt.Errorf("%s: %w", label, err) + } + result.Node = functionNode(item, packages) + return result, nil +} + +func readFunctionPackages(ctx context.Context, item Function, readers FunctionReaders) ([]string, error) { + switch { + case item.Image != "" && item.URL == "" && item.Bucket == "": + if readers.Image == nil { + return nil, fmt.Errorf("function scan cannot read an image") + } + return readers.Image(ctx, item.Image) + case item.URL != "": + if readers.Zip == nil { + return nil, fmt.Errorf("function scan cannot read a deployment package") + } + return readers.Zip(ctx, item.URL) + case item.Bucket != "" && item.Object != "": + if readers.Object == nil { + return nil, fmt.Errorf("function scan cannot read source") + } + return readers.Object(ctx, item.Bucket, item.Object) + default: + return nil, Skip("no deployment package") + } +} + +func functionNode(item Function, packages []string) graph.Node { + props := map[string]any{ + graph.PropWorkloadKind: graph.WorkloadKindFunction, + } + if item.ResourceID != "" { + props["resource_id"] = item.ResourceID + } + if item.Runtime != "" { + props["runtime"] = item.Runtime + } + if item.Image != "" { + props["image"] = item.Image + } + if packages != nil { + props["packages"] = packages + } + return graph.Node{ + ID: item.NodeID, + Type: graph.NodeWorkload, + Name: item.Name, + Provider: item.Provider, + Region: item.Region, + AccountID: item.AccountID, + Properties: props, + } +} diff --git a/internal/workload/function_test.go b/internal/workload/function_test.go new file mode 100644 index 0000000..b25fa7e --- /dev/null +++ b/internal/workload/function_test.go @@ -0,0 +1,110 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "context" + "encoding/json" + "strings" + "testing" + + "github.com/OpenSourceOM/core/internal/graph" +) + +type fakeFunctions struct { + items []Function + err error +} + +func (f fakeFunctions) List(context.Context) ([]Function, error) { + return f.items, f.err +} + +func TestScanFunctionsOmitsPackageURL(t *testing.T) { + const secret = "https://example.invalid/bundle.zip?sig=secret-token" + results, err := ScanFunctions(context.Background(), fakeFunctions{items: []Function{{ + Name: "payments", + NodeID: "aws:1:us-east-1:workload:function/payments", + ResourceID: "arn:aws:lambda:us-east-1:1:function:payments", + Runtime: "nodejs20.x", + URL: secret, + Region: "us-east-1", + AccountID: "1", + Provider: "aws", + }}}, FunctionReaders{ + Zip: func(context.Context, string) ([]string, error) { + return []string{"pkg:npm/lodash@4.17.21", "cpe:2.3:a:lodash:lodash:4.17.21:*:*:*:*:*:*:*"}, nil + }, + }, nil) + if err != nil { + t.Fatal(err) + } + if len(results) != 1 || results[0].Skipped != "" { + t.Fatalf("results = %+v", results) + } + raw, err := json.Marshal(results[0].Node) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(raw), "secret-token") || strings.Contains(string(raw), "bundle.zip") { + t.Fatalf("node stored the package URL: %s", raw) + } + if results[0].Node.Properties[graph.PropWorkloadKind] != graph.WorkloadKindFunction { + t.Fatalf("properties = %#v", results[0].Node.Properties) + } + pkgs, _ := results[0].Node.Properties["packages"].([]string) + if len(pkgs) != 2 { + t.Fatalf("packages = %#v", results[0].Node.Properties["packages"]) + } +} + +func TestScanFunctionsSkipLeavesPackagesUnset(t *testing.T) { + results, err := ScanFunctions(context.Background(), fakeFunctions{items: []Function{{ + Name: "empty", + NodeID: "aws:1:us-east-1:workload:function/empty", + URL: "https://example.invalid/empty.zip", + }}}, FunctionReaders{ + Zip: func(context.Context, string) ([]string, error) { + return nil, ErrNoPackages + }, + }, nil) + if err != nil { + t.Fatal(err) + } + if results[0].Skipped != string(ErrNoPackages) { + t.Fatalf("skipped = %q", results[0].Skipped) + } + if _, ok := results[0].Node.Properties["packages"]; ok { + t.Fatalf("skip wrote packages: %#v", results[0].Node.Properties) + } +} + +func TestScanFunctionsImageDoesNotDownloadZip(t *testing.T) { + results, err := ScanFunctions(context.Background(), fakeFunctions{items: []Function{{ + Name: "img", + Image: "123.dkr.ecr.us-east-1.amazonaws.com/app:v1", + URL: "", + }}}, FunctionReaders{ + Zip: func(context.Context, string) ([]string, error) { + t.Fatal("zip reader was called for an image function") + return nil, nil + }, + Image: func(context.Context, string) ([]string, error) { + return []string{"pkg:deb/debian/bash@5.2"}, nil + }, + }, nil) + if err != nil { + t.Fatal(err) + } + if results[0].Node.Properties["image"] != "123.dkr.ecr.us-east-1.amazonaws.com/app:v1" { + t.Fatalf("properties = %#v", results[0].Node.Properties) + } +} + +func TestScanFunctionsMissingName(t *testing.T) { + _, err := ScanFunctions(context.Background(), fakeFunctions{items: []Function{{Name: "other"}}}, FunctionReaders{}, []string{"payments"}) + if err == nil || !strings.Contains(err.Error(), "payments") { + t.Fatalf("err = %v", err) + } +} diff --git a/internal/workload/gcp/function.go b/internal/workload/gcp/function.go new file mode 100644 index 0000000..13380cf --- /dev/null +++ b/internal/workload/gcp/function.go @@ -0,0 +1,254 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package gcp + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "sort" + "strings" + + "cloud.google.com/go/storage" + gcpcol "github.com/OpenSourceOM/core/internal/collectors/gcp" + "github.com/OpenSourceOM/core/internal/workload" + "golang.org/x/oauth2" + "golang.org/x/oauth2/google" +) + +// FunctionPermissions are the IAM permissions om scan workload function gcp adds. +var FunctionPermissions = []string{ + "cloudfunctions.functions.list", + "storage.objects.get", +} + +// Functions lists Cloud Functions in one region. +type Functions struct { + project string + region string + http *http.Client +} + +// NewFunctions uses application default credentials. +func NewFunctions(ctx context.Context, projectID, region string) (*Functions, error) { + ts, err := google.DefaultTokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform") + if err != nil { + return nil, fmt.Errorf("gcp credentials: %w", err) + } + return &Functions{ + project: projectID, + region: region, + http: oauth2.NewClient(ctx, ts), + }, nil +} + +func (f *Functions) List(ctx context.Context) ([]workload.Function, error) { + byName := map[string]workload.Function{} + if err := f.collect(ctx, f.v2URL(), byName, parseV2); err != nil { + return nil, err + } + if err := f.collect(ctx, f.v1URL(), byName, parseV1); err != nil { + return nil, err + } + var out []workload.Function + for _, item := range byName { + out = append(out, item) + } + sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name }) + return out, nil +} + +func (f *Functions) v2URL() string { + return "https://cloudfunctions.googleapis.com/v2/projects/" + url.PathEscape(f.project) + "/locations/" + url.PathEscape(f.region) + "/functions" +} + +func (f *Functions) v1URL() string { + return "https://cloudfunctions.googleapis.com/v1/projects/" + url.PathEscape(f.project) + "/locations/" + url.PathEscape(f.region) + "/functions" +} + +type functionPage func(body []byte) (items []workload.Function, token string, err error) + +func (f *Functions) collect(ctx context.Context, endpoint string, byName map[string]workload.Function, parse functionPage) error { + token := "" + for pages := 0; pages < 100; pages++ { + pageURL := endpoint + if token != "" { + pageURL += "?pageToken=" + url.QueryEscape(token) + } + body, err := f.get(ctx, pageURL) + if err != nil { + return err + } + items, next, err := parse(body) + if err != nil { + return err + } + for _, item := range items { + item.Region = f.region + item.AccountID = f.project + item.Provider = "gcp" + item.NodeID = gcpcol.FunctionWorkloadNodeID(f.project, f.region, item.Name) + if _, ok := byName[item.Name]; ok { + continue + } + byName[item.Name] = item + } + if next == "" { + return nil + } + token = next + } + return fmt.Errorf("list functions: page limit") +} + +func (f *Functions) get(ctx context.Context, endpoint string) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + resp, err := f.http.Do(req) + if err != nil { + return nil, fmt.Errorf("list functions: %w", err) + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + if err != nil { + return nil, fmt.Errorf("list functions: %w", err) + } + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("list functions: status %d", resp.StatusCode) + } + return body, nil +} + +func parseV2(body []byte) ([]workload.Function, string, error) { + var page struct { + Functions []struct { + Name string `json:"name"` + BuildConfig struct { + Runtime string `json:"runtime"` + Source struct { + StorageSource *struct { + Bucket string `json:"bucket"` + Object string `json:"object"` + } `json:"storageSource"` + RepoSource *struct { + Repo string `json:"repoName"` + } `json:"repoSource"` + } `json:"source"` + } `json:"buildConfig"` + } `json:"functions"` + NextPageToken string `json:"nextPageToken"` + } + if err := json.Unmarshal(body, &page); err != nil { + return nil, "", fmt.Errorf("list functions: response is not json") + } + var out []workload.Function + for _, fn := range page.Functions { + name := lastSegment(fn.Name) + if name == "" { + continue + } + item := workload.Function{ + Name: name, + ResourceID: fn.Name, + Runtime: fn.BuildConfig.Runtime, + } + if src := fn.BuildConfig.Source.StorageSource; src != nil && src.Bucket != "" && src.Object != "" { + item.Bucket = src.Bucket + item.Object = src.Object + } else if fn.BuildConfig.Source.RepoSource != nil { + item.Skip = "source is a repository" + } else { + item.Skip = "no deployment package" + } + out = append(out, item) + } + return out, page.NextPageToken, nil +} + +func parseV1(body []byte) ([]workload.Function, string, error) { + var page struct { + Functions []struct { + Name string `json:"name"` + Runtime string `json:"runtime"` + SourceArchiveURL string `json:"sourceArchiveUrl"` + } `json:"functions"` + NextPageToken string `json:"nextPageToken"` + } + if err := json.Unmarshal(body, &page); err != nil { + return nil, "", fmt.Errorf("list functions: response is not json") + } + var out []workload.Function + for _, fn := range page.Functions { + name := lastSegment(fn.Name) + if name == "" { + continue + } + item := workload.Function{ + Name: name, + ResourceID: fn.Name, + Runtime: fn.Runtime, + } + bucket, object, ok := parseGS(fn.SourceArchiveURL) + if ok { + item.Bucket = bucket + item.Object = object + } else { + item.Skip = "no deployment package" + } + out = append(out, item) + } + return out, page.NextPageToken, nil +} + +func parseGS(raw string) (string, string, bool) { + raw = strings.TrimSpace(raw) + rest, ok := strings.CutPrefix(raw, "gs://") + if !ok { + return "", "", false + } + bucket, object, ok := strings.Cut(rest, "/") + if !ok || bucket == "" || object == "" { + return "", "", false + } + return bucket, object, true +} + +// ReadObject downloads a Cloud Functions source object and walks it. +// The object bytes are deleted after the walk. +func ReadObject(ctx context.Context, bucket, object string) ([]string, error) { + client, err := storage.NewClient(ctx) + if err != nil { + return nil, fmt.Errorf("read function source: %w", err) + } + defer client.Close() + reader, err := client.Bucket(bucket).Object(object).NewReader(ctx) + if err != nil { + return nil, fmt.Errorf("read function source: %w", err) + } + defer reader.Close() + file, err := os.CreateTemp("", "om-bundle-") + if err != nil { + return nil, err + } + name := file.Name() + defer os.Remove(name) + n, err := io.Copy(file, io.LimitReader(reader, workload.MaxBundleBytes()+1)) + closeErr := file.Close() + if err != nil { + return nil, fmt.Errorf("read function source: %w", err) + } + if closeErr != nil { + return nil, closeErr + } + if n > workload.MaxBundleBytes() { + return nil, fmt.Errorf("deployment package is larger than %d bytes", workload.MaxBundleBytes()) + } + return workload.WalkZip(name) +} diff --git a/internal/workload/gcp/function_test.go b/internal/workload/gcp/function_test.go new file mode 100644 index 0000000..1690921 --- /dev/null +++ b/internal/workload/gcp/function_test.go @@ -0,0 +1,43 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package gcp + +import ( + "strings" + "testing" +) + +func TestParseV2StorageAndRepo(t *testing.T) { + body := []byte(`{"functions":[ + {"name":"projects/p/locations/us-central1/functions/pay","buildConfig":{"runtime":"python312","source":{"storageSource":{"bucket":"src","object":"pay.zip"}}}}, + {"name":"projects/p/locations/us-central1/functions/git","buildConfig":{"runtime":"go122","source":{"repoSource":{"repoName":"app"}}}} + ],"nextPageToken":"next"}`) + items, token, err := parseV2(body) + if err != nil || token != "next" || len(items) != 2 { + t.Fatalf("items = %+v %s %v", items, token, err) + } + if items[0].Bucket != "src" || items[0].Object != "pay.zip" || items[0].Skip != "" { + t.Fatalf("storage = %+v", items[0]) + } + if items[1].Skip != "source is a repository" || items[1].Bucket != "" { + t.Fatalf("repo = %+v", items[1]) + } +} + +func TestParseV1Archive(t *testing.T) { + body := []byte(`{"functions":[{"name":"projects/p/locations/us-central1/functions/pay","runtime":"nodejs20","sourceArchiveUrl":"gs://src/pay.zip"}]}`) + items, _, err := parseV1(body) + if err != nil || len(items) != 1 { + t.Fatal(err) + } + if items[0].Bucket != "src" || items[0].Object != "pay.zip" { + t.Fatalf("item = %+v", items[0]) + } + if _, _, ok := parseGS("https://example.invalid/secret"); ok { + t.Fatal("https url parsed as gs") + } + if strings.Contains(items[0].Name, "secret") { + t.Fatal(items[0].Name) + } +} diff --git a/internal/workload/images.go b/internal/workload/images.go new file mode 100644 index 0000000..69278dd --- /dev/null +++ b/internal/workload/images.go @@ -0,0 +1,41 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import "sort" + +// ImageRefs returns the container image references stored on a workload. +// The AMI id in image is not included. That property is a boot image, not a registry ref. +func ImageRefs(props map[string]any) []string { + if props == nil { + return nil + } + seen := map[string]struct{}{} + var out []string + add := func(ref string) { + if ref == "" { + return + } + if _, ok := seen[ref]; ok { + return + } + seen[ref] = struct{}{} + out = append(out, ref) + } + switch items := props["images"].(type) { + case []string: + for _, ref := range items { + add(ref) + } + case []any: + for _, item := range items { + ref, ok := item.(string) + if ok { + add(ref) + } + } + } + sort.Strings(out) + return out +} diff --git a/internal/workload/lang.go b/internal/workload/lang.go new file mode 100644 index 0000000..47e1dbd --- /dev/null +++ b/internal/workload/lang.go @@ -0,0 +1,182 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "archive/zip" + "bytes" + "encoding/json" + "io" + "path" + "strings" +) + +const ( + maxJarBytes = 128 << 20 + maxMetaBytes = 1 << 20 + maxBundleBytes = 256 << 20 + maxInterestingFile = 10000 +) + +func languageIDs(ecosystem, namespace, name, version string) []string { + ecosystem = strings.ToLower(strings.TrimSpace(ecosystem)) + namespace = strings.TrimSpace(namespace) + name = strings.TrimSpace(name) + version = strings.TrimSpace(version) + if ecosystem == "" || name == "" || !concretePackageVersion(version) { + return nil + } + if strings.ContainsAny(name, " \t\r\n") || strings.ContainsAny(namespace, " \t\r\n") { + return nil + } + product := name + if i := strings.LastIndex(product, "/"); i >= 0 { + product = product[i+1:] + } + cpe := "cpe:2.3:a:" + cpeEscape(strings.ToLower(product)) + ":" + cpeEscape(strings.ToLower(product)) + ":" + cpeEscape(version) + ":*:*:*:*:*:*:*" + purl := "pkg:" + ecosystem + "/" + if namespace != "" { + purl += purlEscape(namespace) + "/" + } + purl += purlEscape(name) + "@" + purlEscape(version) + return []string{cpe, purl} +} + +func concretePackageVersion(v string) bool { + switch strings.ToLower(v) { + case "", "*", "latest", "file", "workspace", "link": + return false + } + lower := strings.ToLower(v) + for _, prefix := range []string{"file:", "workspace:", "link:", "git:", "git+", "http:", "https:"} { + if strings.HasPrefix(lower, prefix) { + return false + } + } + return true +} + +func mavenIDsFromProperties(body []byte) []string { + var group, artifact, version string + for _, line := range strings.Split(string(body), "\n") { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + key, value, ok := strings.Cut(line, "=") + if !ok { + continue + } + switch strings.TrimSpace(key) { + case "groupId": + group = strings.TrimSpace(value) + case "artifactId": + artifact = strings.TrimSpace(value) + case "version": + version = strings.TrimSpace(value) + } + } + return languageIDs("maven", group, artifact, version) +} + +func mavenIDsFromJar(r io.Reader, size int64) ([]string, error) { + if size > maxJarBytes { + return nil, nil + } + limit := int64(maxJarBytes) + if size > 0 && size < limit { + limit = size + } + body, err := io.ReadAll(io.LimitReader(r, limit+1)) + if err != nil { + return nil, err + } + if int64(len(body)) > maxJarBytes { + return nil, nil + } + zr, err := zip.NewReader(bytes.NewReader(body), int64(len(body))) + if err != nil { + return nil, nil + } + var ids []string + for _, file := range zr.File { + name := path.Clean(strings.TrimPrefix(file.Name, "/")) + if !strings.Contains(name, "META-INF/maven/") || path.Base(name) != "pom.properties" { + continue + } + if file.UncompressedSize64 > maxMetaBytes { + continue + } + rc, err := file.Open() + if err != nil { + return nil, err + } + props, err := io.ReadAll(io.LimitReader(rc, maxMetaBytes+1)) + rc.Close() + if err != nil { + return nil, err + } + if int64(len(props)) > maxMetaBytes { + continue + } + ids = append(ids, mavenIDsFromProperties(props)...) + } + return ids, nil +} + +func npmIDs(body []byte) []string { + var doc struct { + Name string `json:"name"` + Version string `json:"version"` + } + if err := json.Unmarshal(body, &doc); err != nil { + return nil + } + name := strings.TrimSpace(doc.Name) + if strings.HasPrefix(name, "@") { + scope, pkg, ok := strings.Cut(name, "/") + if !ok || scope == "@" || pkg == "" { + return nil + } + return languageIDs("npm", scope, pkg, doc.Version) + } + return languageIDs("npm", "", name, doc.Version) +} + +func pypiIDs(body []byte) []string { + var name, version string + for _, line := range strings.Split(string(body), "\n") { + if strings.TrimSpace(line) == "" && name != "" && version != "" { + break + } + key, value, ok := strings.Cut(line, ":") + if !ok { + continue + } + switch strings.ToLower(strings.TrimSpace(key)) { + case "name": + if name == "" { + name = strings.ToLower(strings.ReplaceAll(strings.TrimSpace(value), "_", "-")) + } + case "version": + if version == "" { + version = strings.TrimSpace(value) + } + } + } + return languageIDs("pypi", "", name, version) +} + +func languageIDsFromMeta(rel string, body []byte) []string { + switch path.Base(rel) { + case "package.json": + return npmIDs(body) + case "METADATA": + return pypiIDs(body) + case "pom.properties": + return mavenIDsFromProperties(body) + default: + return nil + } +} diff --git a/internal/workload/registry.go b/internal/workload/registry.go new file mode 100644 index 0000000..6e44fbe --- /dev/null +++ b/internal/workload/registry.go @@ -0,0 +1,458 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "bufio" + "compress/gzip" + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strings" +) + +// ImageRef is a container image reference split for a registry pull. +type ImageRef struct { + Host string + Name string + Reference string + Familiar string +} + +// ParseImageRef accepts a reference stored on a Kubernetes workload. +// A short name uses docker.io and the library namespace. A missing tag is latest. +func ParseImageRef(raw string) (ImageRef, error) { + raw = strings.TrimSpace(raw) + if raw == "" || strings.ContainsAny(raw, " \t") { + return ImageRef{}, fmt.Errorf("empty image reference") + } + name := raw + digest := "" + if i := strings.Index(name, "@"); i >= 0 { + digest = name[i+1:] + name = name[:i] + if digest == "" || !strings.Contains(digest, ":") { + return ImageRef{}, fmt.Errorf("image reference %s has no digest", raw) + } + } + host := "" + rest := name + if slash := strings.Index(rest, "/"); slash >= 0 { + first := rest[:slash] + if strings.Contains(first, ".") || strings.Contains(first, ":") || first == "localhost" { + host = first + rest = rest[slash+1:] + } + } + if host == "" { + host = "docker.io" + } + tag := "" + if digest == "" { + if colon := strings.LastIndex(rest, ":"); colon >= 0 && !strings.Contains(rest[colon+1:], "/") { + tag = rest[colon+1:] + rest = rest[:colon] + } + if tag == "" { + tag = "latest" + } + } + if rest == "" || strings.HasPrefix(rest, "/") || strings.HasSuffix(rest, "/") { + return ImageRef{}, fmt.Errorf("image reference %s has no name", raw) + } + if host == "docker.io" && !strings.Contains(rest, "/") { + rest = "library/" + rest + } + ref := tag + if digest != "" { + ref = digest + } + return ImageRef{Host: host, Name: rest, Reference: ref, Familiar: raw}, nil +} + +// Registry pulls image layers. Auth returns registry credentials for host. +// ok is false when the pull should stay anonymous. Credentials are not stored. +type Registry struct { + Client *http.Client + Auth func(ctx context.Context, host string) (user, pass string, ok bool, err error) +} + +// NewRegistry uses the docker config and, for an ECR host, the AWS credential chain. +func NewRegistry() *Registry { + return &Registry{Auth: defaultRegistryAuth} +} + +// Packages fetches ref once and walks its layers. +func (r *Registry) Packages(ctx context.Context, ref string) ([]string, error) { + parsed, err := ParseImageRef(ref) + if err != nil { + return nil, err + } + if r == nil { + r = NewRegistry() + } + client := r.Client + if client == nil { + client = http.DefaultClient + } + user, pass, ok, err := r.credentials(ctx, parsed.Host) + if err != nil { + return nil, err + } + manifest, err := r.fetchManifest(ctx, client, parsed, parsed.Reference, user, pass, ok) + if err != nil { + return nil, err + } + if len(manifest.Manifests) > 0 && len(manifest.Layers) == 0 { + chosen, found := pickLinuxManifest(manifest.Manifests) + if !found { + return nil, fmt.Errorf("%s has no linux manifest", parsed.Familiar) + } + manifest, err = r.fetchManifest(ctx, client, parsed, chosen.Digest, user, pass, ok) + if err != nil { + return nil, err + } + } + if len(manifest.Layers) == 0 { + return nil, ErrNoPackages + } + tree := newLayerTree() + for _, layer := range manifest.Layers { + if err := r.addLayer(ctx, client, parsed, layer, user, pass, ok, tree); err != nil { + return nil, fmt.Errorf("%s: %w", parsed.Familiar, err) + } + } + return tree.packages() +} + +// ReadImage fetches ref with NewRegistry and walks its layers. +func ReadImage(ctx context.Context, ref string) ([]string, error) { + return NewRegistry().Packages(ctx, ref) +} + +func (r *Registry) credentials(ctx context.Context, host string) (string, string, bool, error) { + if r.Auth == nil { + return "", "", false, nil + } + return r.Auth(ctx, host) +} + +type imageManifest struct { + MediaType string `json:"mediaType"` + Layers []imageDescriptor `json:"layers"` + Manifests []imageDescriptor `json:"manifests"` +} + +type imageDescriptor struct { + MediaType string `json:"mediaType"` + Digest string `json:"digest"` + Size int64 `json:"size"` + Platform *imagePlatform `json:"platform"` +} + +type imagePlatform struct { + OS string `json:"os"` + Architecture string `json:"architecture"` +} + +func pickLinuxManifest(list []imageDescriptor) (imageDescriptor, bool) { + var fallback imageDescriptor + found := false + for _, item := range list { + if item.Digest == "" { + continue + } + if item.Platform == nil { + if !found { + fallback = item + found = true + } + continue + } + if item.Platform.OS != "linux" && item.Platform.OS != "" { + continue + } + if item.Platform.Architecture == "amd64" || item.Platform.Architecture == "" { + return item, true + } + if !found { + fallback = item + found = true + } + } + return fallback, found +} + +func (r *Registry) fetchManifest(ctx context.Context, client *http.Client, ref ImageRef, reference, user, pass string, auth bool) (imageManifest, error) { + endpoint := ref.endpoint("/manifests/" + reference) + accept := strings.Join([]string{ + "application/vnd.oci.image.index.v1+json", + "application/vnd.docker.distribution.manifest.list.v2+json", + "application/vnd.oci.image.manifest.v1+json", + "application/vnd.docker.distribution.manifest.v2+json", + }, ", ") + body, err := r.get(ctx, client, endpoint, accept, user, pass, auth) + if err != nil { + return imageManifest{}, fmt.Errorf("%s: %w", ref.Familiar, err) + } + var manifest imageManifest + if err := json.Unmarshal(body, &manifest); err != nil { + return imageManifest{}, fmt.Errorf("%s: image manifest is not json", ref.Familiar) + } + return manifest, nil +} + +func (r *Registry) addLayer(ctx context.Context, client *http.Client, ref ImageRef, layer imageDescriptor, user, pass string, auth bool, tree *layerTree) error { + if layer.Digest == "" { + return fmt.Errorf("layer has no digest") + } + if err := unsupportedLayer(layer.MediaType); err != nil { + return err + } + endpoint := ref.endpoint("/blobs/" + layer.Digest) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return err + } + token := "" + resp, token, err := r.do(ctx, client, req, user, pass, auth, token) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return fmt.Errorf("layer: status %d", resp.StatusCode) + } + reader, err := openLayer(layer.MediaType, resp.Body) + if err != nil { + return err + } + if closer, ok := reader.(io.Closer); ok { + defer closer.Close() + } + return tree.addTar(reader) +} + +func unsupportedLayer(mediaType string) error { + mt := strings.ToLower(mediaType) + switch { + case strings.Contains(mt, "zstd"): + return Skip("zstd layers are not read") + case strings.Contains(mt, "foreign"), strings.Contains(mt, "nondistributable"): + return Skip("foreign layers are not read") + default: + return nil + } +} + +func openLayer(mediaType string, r io.Reader) (io.Reader, error) { + mt := strings.ToLower(mediaType) + if strings.Contains(mt, "gzip") || mt == "" { + return maybeGzip(r) + } + if strings.Contains(mt, "tar") { + return r, nil + } + return nil, fmt.Errorf("layer type %s is not read", mediaType) +} + +func maybeGzip(r io.Reader) (io.Reader, error) { + br := bufio.NewReader(r) + magic, err := br.Peek(2) + if err != nil && err != io.EOF { + return nil, err + } + if len(magic) >= 2 && magic[0] == 0x1f && magic[1] == 0x8b { + return gzip.NewReader(br) + } + return br, nil +} + +func (r *Registry) get(ctx context.Context, client *http.Client, endpoint, accept, user, pass string, auth bool) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, nil) + if err != nil { + return nil, err + } + if accept != "" { + req.Header.Set("Accept", accept) + } + resp, _, err := r.do(ctx, client, req, user, pass, auth, "") + if err != nil { + return nil, err + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return nil, fmt.Errorf("manifest: status %d", resp.StatusCode) + } + body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + if err != nil { + return nil, err + } + return body, nil +} + +func (r *Registry) do(ctx context.Context, client *http.Client, req *http.Request, user, pass string, basic bool, bearer string) (*http.Response, string, error) { + req.Header.Set("User-Agent", "opensourceom") + if bearer != "" { + req.Header.Set("Authorization", "Bearer "+bearer) + } + resp, err := client.Do(req) + if err != nil { + return nil, bearer, fmt.Errorf("registry: %w", err) + } + if resp.StatusCode != http.StatusUnauthorized || bearer != "" { + return resp, bearer, nil + } + challenge := resp.Header.Get("WWW-Authenticate") + resp.Body.Close() + if basic && user != "" && strings.HasPrefix(strings.ToLower(strings.TrimSpace(challenge)), "basic") { + retry := req.Clone(ctx) + retry.SetBasicAuth(user, pass) + retry.Header.Set("User-Agent", "opensourceom") + resp, err = client.Do(retry) + if err != nil { + return nil, "", fmt.Errorf("registry: %w", err) + } + return resp, "", nil + } + token, err := r.bearerToken(ctx, client, challenge, user, pass, basic) + if err != nil { + return nil, "", err + } + retry := req.Clone(ctx) + retry.Header.Set("Authorization", "Bearer "+token) + retry.Header.Set("User-Agent", "opensourceom") + resp, err = client.Do(retry) + if err != nil { + return nil, "", fmt.Errorf("registry: %w", err) + } + return resp, token, nil +} + +func (r *Registry) bearerToken(ctx context.Context, client *http.Client, challenge, user, pass string, basic bool) (string, error) { + realm, service, scope, ok := parseBearer(challenge) + if !ok { + return "", fmt.Errorf("registry denied the image") + } + endpoint, err := url.Parse(realm) + if err != nil || endpoint.Scheme == "" || endpoint.Host == "" { + return "", fmt.Errorf("registry denied the image") + } + query := endpoint.Query() + if service != "" { + query.Set("service", service) + } + if scope != "" { + query.Set("scope", scope) + } + endpoint.RawQuery = query.Encode() + req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint.String(), nil) + if err != nil { + return "", err + } + if basic && user != "" { + req.SetBasicAuth(user, pass) + } + resp, err := client.Do(req) + if err != nil { + return "", fmt.Errorf("registry: %w", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("registry denied the image") + } + var body struct { + Token string `json:"token"` + AccessToken string `json:"access_token"` + } + if err := json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(&body); err != nil { + return "", fmt.Errorf("registry denied the image") + } + if body.Token != "" { + return body.Token, nil + } + if body.AccessToken != "" { + return body.AccessToken, nil + } + return "", fmt.Errorf("registry denied the image") +} + +func parseBearer(header string) (realm, service, scope string, ok bool) { + header = strings.TrimSpace(header) + if len(header) < len("Bearer ") || !strings.EqualFold(header[:len("Bearer ")], "Bearer ") { + return "", "", "", false + } + values := map[string]string{} + rest := strings.TrimSpace(header[len("Bearer "):]) + for rest != "" { + rest = strings.TrimLeft(rest, " ,") + if rest == "" { + break + } + key, value, found := strings.Cut(rest, "=") + if !found { + break + } + key = strings.TrimSpace(key) + value = strings.TrimSpace(value) + if strings.HasPrefix(value, `"`) { + value = value[1:] + end := strings.IndexByte(value, '"') + if end < 0 { + break + } + rest = value[end+1:] + value = value[:end] + } else { + end := strings.IndexAny(value, ", ") + if end < 0 { + rest = "" + } else { + rest = value[end:] + value = value[:end] + } + } + values[strings.ToLower(key)] = value + } + realm = values["realm"] + if realm == "" { + return "", "", "", false + } + return realm, values["service"], values["scope"], true +} + +func (ref ImageRef) endpoint(suffix string) string { + scheme := "https" + host := ref.Host + if host == "docker.io" { + host = "registry-1.docker.io" + } + if localRegistry(host) { + scheme = "http" + } + name := pathEscapeSlashes(ref.Name) + return scheme + "://" + host + "/v2/" + name + suffix +} + +func pathEscapeSlashes(name string) string { + parts := strings.Split(name, "/") + for i, part := range parts { + parts[i] = url.PathEscape(part) + } + return strings.Join(parts, "/") +} + +func localRegistry(host string) bool { + switch { + case host == "localhost" || strings.HasPrefix(host, "localhost:"): + return true + case host == "127.0.0.1" || strings.HasPrefix(host, "127.0.0.1:"): + return true + default: + return false + } +} diff --git a/internal/workload/registry_auth.go b/internal/workload/registry_auth.go new file mode 100644 index 0000000..aff418a --- /dev/null +++ b/internal/workload/registry_auth.go @@ -0,0 +1,113 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "context" + "encoding/base64" + "encoding/json" + "os" + "path/filepath" + "strings" +) + +func defaultRegistryAuth(ctx context.Context, host string) (string, string, bool, error) { + user, pass, ok, err := dockerConfigAuth(host) + if err != nil || ok { + return user, pass, ok, err + } + if region, ok := ecrRegion(host); ok { + return ecrAuth(ctx, region) + } + return "", "", false, nil +} + +func dockerConfigAuth(host string) (string, string, bool, error) { + dir := os.Getenv("DOCKER_CONFIG") + if dir == "" { + home, err := os.UserHomeDir() + if err != nil || home == "" { + return "", "", false, nil + } + dir = filepath.Join(home, ".docker") + } + data, err := os.ReadFile(filepath.Join(dir, "config.json")) + if os.IsNotExist(err) { + return "", "", false, nil + } + if err != nil { + return "", "", false, err + } + var file struct { + Auths map[string]dockerAuthEntry `json:"auths"` + } + if err := json.Unmarshal(data, &file); err != nil { + return "", "", false, err + } + for _, key := range dockerAuthKeys(host) { + entry, ok := file.Auths[key] + if !ok { + continue + } + user, pass, ok := entry.credentials() + if ok { + return user, pass, true, nil + } + } + return "", "", false, nil +} + +type dockerAuthEntry struct { + Auth string `json:"auth"` + Username string `json:"username"` + Password string `json:"password"` +} + +func (e dockerAuthEntry) credentials() (string, string, bool) { + if e.Username != "" { + return e.Username, e.Password, true + } + if e.Auth == "" { + return "", "", false + } + raw, err := base64.StdEncoding.DecodeString(e.Auth) + if err != nil { + raw, err = base64.URLEncoding.DecodeString(e.Auth) + if err != nil { + return "", "", false + } + } + user, pass, ok := strings.Cut(string(raw), ":") + if !ok || user == "" { + return "", "", false + } + return user, pass, true +} + +func dockerAuthKeys(host string) []string { + keys := []string{host, "https://" + host, "https://" + host + "/v1/"} + if host == "docker.io" || host == "registry-1.docker.io" { + keys = append(keys, "https://index.docker.io/v1/") + } + return keys +} + +func ecrRegion(host string) (string, bool) { + const marker = ".dkr.ecr." + i := strings.Index(host, marker) + if i < 0 { + return "", false + } + rest := host[i+len(marker):] + region, suffix, ok := strings.Cut(rest, ".") + if !ok || region == "" { + return "", false + } + switch suffix { + case "amazonaws.com", "amazonaws.com.cn": + return region, true + default: + return "", false + } +} diff --git a/internal/workload/registry_ecr.go b/internal/workload/registry_ecr.go new file mode 100644 index 0000000..7578e8f --- /dev/null +++ b/internal/workload/registry_ecr.go @@ -0,0 +1,37 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "context" + "encoding/base64" + "fmt" + "strings" + + "github.com/aws/aws-sdk-go-v2/config" + "github.com/aws/aws-sdk-go-v2/service/ecr" +) + +func ecrAuth(ctx context.Context, region string) (string, string, bool, error) { + cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion(region)) + if err != nil { + return "", "", false, fmt.Errorf("load aws config: %w", err) + } + out, err := ecr.NewFromConfig(cfg).GetAuthorizationToken(ctx, &ecr.GetAuthorizationTokenInput{}) + if err != nil { + return "", "", false, fmt.Errorf("ecr authorization: %w", err) + } + if len(out.AuthorizationData) == 0 || out.AuthorizationData[0].AuthorizationToken == nil { + return "", "", false, fmt.Errorf("ecr authorization token is empty") + } + raw, err := base64.StdEncoding.DecodeString(*out.AuthorizationData[0].AuthorizationToken) + if err != nil { + return "", "", false, fmt.Errorf("ecr authorization token is unusable") + } + user, pass, ok := strings.Cut(string(raw), ":") + if !ok || user == "" || pass == "" { + return "", "", false, fmt.Errorf("ecr authorization token is unusable") + } + return user, pass, true, nil +} diff --git a/internal/workload/registry_test.go b/internal/workload/registry_test.go new file mode 100644 index 0000000..4dcae81 --- /dev/null +++ b/internal/workload/registry_test.go @@ -0,0 +1,126 @@ +// Copyright 2026 OpenSourceOM +// SPDX-License-Identifier: Apache-2.0 + +package workload + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "strings" + "testing" +) + +func TestParseImageRef(t *testing.T) { + tests := []struct { + raw string + host string + name string + ref string + }{ + {"nginx", "docker.io", "library/nginx", "latest"}, + {"nginx:1.25", "docker.io", "library/nginx", "1.25"}, + {"ghcr.io/org/app:v1", "ghcr.io", "org/app", "v1"}, + {"localhost:5000/app:v1", "localhost:5000", "app", "v1"}, + {"gcr.io/proj/app@sha256:abc", "gcr.io", "proj/app", "sha256:abc"}, + } + for _, test := range tests { + got, err := ParseImageRef(test.raw) + if err != nil { + t.Fatalf("%s: %v", test.raw, err) + } + if got.Host != test.host || got.Name != test.name || got.Reference != test.ref { + t.Fatalf("%s = %+v", test.raw, got) + } + } +} + +func TestRegistryPackages(t *testing.T) { + layer := gzipBytes(t, tarLayer(t, map[string][]byte{ + "etc/os-release": []byte("ID=alpine\nVERSION_ID=3.19\n"), + "lib/apk/db/installed": []byte("P:openssl\nV:3.1.4-r0\nA:x86_64\n\n"), + })) + var sawToken bool + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if strings.Contains(r.URL.Path, "/token") { + if r.Header.Get("Authorization") != "" { + t.Errorf("anonymous token request sent credentials") + } + _ = json.NewEncoder(w).Encode(map[string]string{"token": "tok"}) + return + } + if r.Header.Get("Authorization") != "Bearer tok" { + w.Header().Set("WWW-Authenticate", `Bearer realm="http://`+r.Host+`/token",service="test",scope="repository:app:pull"`) + http.Error(w, "denied", http.StatusUnauthorized) + return + } + sawToken = true + switch { + case strings.Contains(r.URL.Path, "/manifests/"): + _ = json.NewEncoder(w).Encode(map[string]any{ + "mediaType": "application/vnd.docker.distribution.manifest.v2+json", + "layers": []map[string]any{{ + "mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip", + "digest": "sha256:abc", + "size": len(layer), + }}, + }) + case strings.Contains(r.URL.Path, "/blobs/"): + _, _ = w.Write(layer) + default: + http.NotFound(w, r) + } + })) + defer srv.Close() + + reg := &Registry{Client: srv.Client(), Auth: func(context.Context, string) (string, string, bool, error) { + return "", "", false, nil + }} + ids, err := reg.Packages(context.Background(), strings.TrimPrefix(srv.URL, "http://")+"/app:v1") + if err != nil { + t.Fatal(err) + } + if !sawToken { + t.Fatal("registry did not require a token") + } + joined := strings.Join(ids, "\n") + if !strings.Contains(joined, "pkg:apk/alpine/openssl@3.1.4-r0") { + t.Fatalf("packages =\n%s", joined) + } +} + +func TestDownloadOmitsURL(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "no", http.StatusForbidden) + })) + defer srv.Close() + err := Download(context.Background(), srv.Client(), srv.URL+"/pkg?sig=secret-token", t.TempDir()+"/bundle", maxBundleBytes) + if err == nil || strings.Contains(err.Error(), "secret-token") { + t.Fatalf("err = %v", err) + } +} + +func TestDockerConfigAuth(t *testing.T) { + dir := t.TempDir() + t.Setenv("DOCKER_CONFIG", dir) + body := []byte(`{"auths":{"ghcr.io":{"auth":"YWxpY2U6c2VjcmV0"}}}`) + if err := os.WriteFile(dir+"/config.json", body, 0o600); err != nil { + t.Fatal(err) + } + user, pass, ok, err := dockerConfigAuth("ghcr.io") + if err != nil || !ok || user != "alice" || pass != "secret" { + t.Fatalf("auth = %s %s %v %v", user, pass, ok, err) + } +} + +func TestECRRegion(t *testing.T) { + region, ok := ecrRegion("123456789012.dkr.ecr.us-west-2.amazonaws.com") + if !ok || region != "us-west-2" { + t.Fatalf("region = %s %v", region, ok) + } + if _, ok := ecrRegion("ghcr.io"); ok { + t.Fatal("ghcr.io parsed as ecr") + } +} From 6dd57651a4dbb4ea7a0fa13e8e56d38bb91df69b Mon Sep 17 00:00:00 2001 From: O M Date: Wed, 2 Dec 2026 18:32:57 -0500 Subject: [PATCH 2/2] Keep archive entry names off the filesystem. Package databases are written under a temp directory using a fixed path list, so a zip or tar entry cannot escape that directory. Co-authored-by: Cursor --- internal/workload/archive.go | 41 ++++++++++++++++++++++++++++--- internal/workload/archive_test.go | 26 ++++++++++++++++++++ 2 files changed, 63 insertions(+), 4 deletions(-) diff --git a/internal/workload/archive.go b/internal/workload/archive.go index 8284173..1efb3ab 100644 --- a/internal/workload/archive.go +++ b/internal/workload/archive.go @@ -44,6 +44,9 @@ func WalkZip(path string) ([]string, error) { if file.UncompressedSize64 > maxBundleBytes && !isJar(file.Name) { continue } + if strings.Contains(file.Name, "..") { + continue + } rc, err := file.Open() if err != nil { return nil, fmt.Errorf("read deployment package: %w", err) @@ -80,6 +83,12 @@ func (t *layerTree) addTar(r io.Reader) error { if err != nil { return fmt.Errorf("read layer: %w", err) } + if strings.Contains(hdr.Name, "..") && !strings.HasSuffix(hdr.Name, ".wh..wh..opq") { + continue + } + if strings.Contains(hdr.Linkname, "..") { + continue + } switch hdr.Typeflag { case tar.TypeReg, tar.TypeRegA: if err := t.add(hdr.Name, tr, hdr.Size); err != nil { @@ -218,11 +227,16 @@ func (t *layerTree) packages() ([]string, error) { defer os.RemoveAll(root) for rel, body := range t.files { - if !isPackageDB(rel) && !isOSRelease(rel) { + // safe is a fixed package-database path, never the archive entry name. + safe, ok := localPackageFile(rel) + if !ok || strings.Contains(safe, "..") { + continue + } + if !filepath.IsLocal(safe) { continue } - dest := filepath.Join(root, filepath.FromSlash(rel)) - if !strings.HasPrefix(dest, root+string(os.PathSeparator)) && dest != root { + dest := filepath.Join(root, safe) + if !strings.HasPrefix(dest, root+string(os.PathSeparator)) { continue } if err := os.MkdirAll(filepath.Dir(dest), 0o700); err != nil { @@ -279,7 +293,26 @@ func isPackageDB(rel string) bool { } func isOSRelease(rel string) bool { - return rel == "etc/os-release" || rel == "usr/lib/os-release" + _, ok := localPackageFile(rel) + return ok && !isPackageDB(rel) +} + +// localPackageFile returns a fixed relative path when rel is a package +// database or os-release file. The result is one of those literals. +func localPackageFile(rel string) (string, bool) { + for _, candidate := range packageDBPaths { + if rel == candidate { + return candidate, true + } + } + switch rel { + case "etc/os-release": + return "etc/os-release", true + case "usr/lib/os-release": + return "usr/lib/os-release", true + default: + return "", false + } } func isWhiteout(rel string) bool { diff --git a/internal/workload/archive_test.go b/internal/workload/archive_test.go index 42bf98d..abe6fe9 100644 --- a/internal/workload/archive_test.go +++ b/internal/workload/archive_test.go @@ -71,6 +71,32 @@ func TestWalkZipReadsMavenAndSkipsFileURLs(t *testing.T) { } } +func TestWalkZipSkipsDotDotEntries(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "bundle.zip") + writeZip(t, path, map[string]string{ + "../../var/lib/dpkg/status": "Package: stolen\nStatus: install ok installed\nVersion: 1\n\n", + "../package.json": `{"name":"stolen","version":"1.0.0"}`, + }) + _, err := WalkZip(path) + if err != ErrNoPackages { + t.Fatalf("err = %v", err) + } +} + +func TestWalkLayerTarsOpaqueWhiteout(t *testing.T) { + first := tarLayer(t, map[string][]byte{ + "app/node_modules/lodash/package.json": []byte(`{"name":"lodash","version":"4.17.21"}`), + }) + second := tarLayer(t, map[string][]byte{ + "app/.wh..wh..opq": {}, + }) + _, err := WalkLayerTars([]io.Reader{bytes.NewReader(first), bytes.NewReader(second)}) + if err != ErrNoPackages { + t.Fatalf("err = %v", err) + } +} + func TestWalkLayerTarsEmpty(t *testing.T) { _, err := WalkLayerTars([]io.Reader{bytes.NewReader(tarLayer(t, map[string][]byte{ "readme.txt": []byte("hello"),