Skip to content

Chore/sign backend images#1

Open
utkxrsh26 wants to merge 2 commits into
masterfrom
chore/sign-backend-images
Open

Chore/sign backend images#1
utkxrsh26 wants to merge 2 commits into
masterfrom
chore/sign-backend-images

Conversation

@utkxrsh26
Copy link
Copy Markdown
Owner

Description

This PR fixes #

Notes for Reviewers

Signed commits

  • Yes, I signed my commits.

richiejp added 2 commits May 14, 2026 21:05
Close a trust gap where a registry compromise or MITM could silently
replace a backend image: the gallery YAML tells LocalAI which image to
pull, but until now nothing verified the bytes came from our CI.

Consumer (pkg/oci/cosignverify):
- New package using sigstore-go to verify keyless-cosign signatures.
- OCI 1.1 referrers API + new bundle format (no legacy :tag.sig).
- Policy fields: Issuer / IssuerRegex / Identity / IdentityRegex /
  NotBefore. NotBefore is the revocation lever — keyless Fulcio certs
  are ephemeral so revocation is policy-side; advancing not_before in
  the gallery YAML invalidates every signature predating the cutoff.
- TUF trusted root cached process-wide so N backends from one gallery
  do 1 fetch, not N.

Plumbing:
- pkg/downloader: ImageVerifier interface + WithImageVerifier option
  threaded through DownloadFileWithContext. Verification runs between
  oci.GetImage and oci.ExtractOCIImage, with digest pinning via
  pinnedImageRef to close the TOCTOU window. Skips the verifier's HEAD
  when the ref is already digest-pinned.
- core/config: Gallery.Verification YAML block.
- core/gallery: backendDownloadOptions builds the verifier from the
  policy; applied on initial URI, mirrors, and tag fallbacks.
- core/gallery/upgrade: the upgrade path now routes through the same
  options builder. A regression Ginkgo spec pins this contract —
  without it, UpgradeBackend silently bypassed verification.
- core/cli: --require-backend-integrity (LOCALAI_REQUIRE_BACKEND_INTEGRITY)
  escalates missing policy / empty SHA256 from warn to hard-fail.

Producer (.github/workflows/backend_merge.yml):
- id-token: write at job scope (PR-fork-safe via existing event gate).
- sigstore/cosign-installer@v3 pinned to v2.4.1.
- After each docker buildx imagetools create, resolve the manifest
  list digest and run cosign sign --recursive --new-bundle-format
  --registry-referrers-mode=oci-1-1 against repo@digest. --recursive
  signs the index and every per-arch entry, matching how the consumer
  resolves a tag to a platform-specific manifest before verifying.

Rollout: backend/index.yaml has no `verification:` block yet, so this
PR is backward-compatible — installs proceed with a warning until the
gallery is populated. Strict mode is opt-in.

Assisted-by: claude-code:claude-opus-4-7 [Bash] [Edit] [Read] [Write] [WebSearch] [WebFetch]
Signed-off-by: Richard Palethorpe <io@richiejp.com>
…ad of env

The previous implementation re-exported the --require-backend-integrity
CLI flag into LOCALAI_REQUIRE_BACKEND_INTEGRITY via os.Setenv, then
re-read it in core/gallery via os.Getenv. This leaked process state
into the gallery package and made the flag impossible to override
per-call or test without touching the env.

Add RequireBackendIntegrity to ApplicationConfig (with a matching
WithRequireBackendIntegrity AppOption) and thread the bool through
every install/upgrade path: InstallBackend, InstallBackendFromGallery,
UpgradeBackend, InstallModelFromGallery, InstallExternalBackend,
ApplyGalleryFromString/File, startup.InstallModels. Worker subcommands
gain the same env-bound flag on WorkerFlags so distributed-worker
installs honor it consistently with the worker daemon path.

Add a forbidigo lint rule against os.Getenv / os.LookupEnv / os.Environ
to keep the env-leak pattern from creeping back. Existing offenders
(p2p, config loaders, etc.) are baseline-grandfathered by the existing
new-from-merge-base: origin/master setting; targeted path exclusions
cover the legitimate cases — kong CLI entry points, backend
subprocesses, system capability probes, gRPC AUTH_TOKEN inheritance,
test gating env vars.

Assisted-by: claude-code:claude-opus-4-7
Signed-off-by: Richard Palethorpe <io@richiejp.com>
@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented May 28, 2026

PR Summary

What Changed

  • Added keyless cosign signature verification for OCI backend images using sigstore-go, with verification policies configured via gallery YAML.
  • Introduced --require-backend-integrity flag and LOCALAI_REQUIRE_BACKEND_INTEGRITY env var to enforce strict mode that rejects backends without signatures or SHA256 checksums.
  • Updated CI/CD to sign multi-arch backend images with cosign using OCI 1.1 referrers API.

Key Changes by Area

Security & Verification

  • New pkg/oci/cosignverify/ package implements Sigstore bundle verification with OIDC issuer/identity matching and NotBefore revocation timestamp.
  • Gallery.Verification config in core/config/gallery.go supports issuer regex, identity regex, and optional revocation cutoff.

CLI & Configuration

  • --require-backend-integrity flag added across all entry points: local-ai run, backends, models, and all worker subcommands.
  • forbidigo linter rules in .golangci.yml block direct os.Getenv calls to enforce config plumbing through ApplicationConfig.

Backend Installation

  • InstallBackend, InstallBackendFromGallery, and UpgradeBackend now resolve verification options before writing to disk.
  • OCI downloads verify signatures between manifest fetch and layer extraction; HTTP/tarball downloads enforce SHA256 when strict mode is on.

CI/CD

  • .github/workflows/backend_merge.yml signs images with cosign sign --recursive --new-bundle-format --registry-referrers-mode=oci-1-1.

Files Changed

File Changes Summary
.agents/adding-backends.md Added note on integrity verification requirements
.agents/backend-signing.md Comprehensive trust model and signing documentation
.github/workflows/backend_merge.yml Added cosign signing with OCI 1.1 referrers for multi-arch images
.golangci.yml Added forbidigo rules blocking os.Getenv and testing.T outside CLI/tests
AGENTS.md Updated agent documentation
core/application/startup.go Propagated RequireBackendIntegrity through model installation
core/application/upgrade_checker.go Updated upgrade paths with integrity checks
core/backend/llm.go Backend integration updates
core/cli/backends.go Added --require-backend-integrity flag
core/cli/models.go Added --require-backend-integrity flag
core/cli/run.go Added --require-backend-integrity flag
core/cli/worker/worker.go Added --require-backend-integrity flag
core/cli/worker/worker_backend_common.go Pass requireIntegrity to backend discovery
core/cli/worker/worker_llamacpp.go Pass requireIntegrity to findLLamaCPPBackend
core/cli/worker/worker_mlx_common.go Pass requireIntegrity to backend discovery
core/cli/worker/worker_mlx_distributed.go Worker integration updates
core/cli/worker/worker_p2p.go Worker integration updates
core/cli/worker/worker_p2p_mlx.go Worker integration updates
core/cli/worker/worker_vllm.go Worker integration updates
core/config/application_config.go Added RequireBackendIntegrity config option
core/config/gallery.go Added GalleryVerification schema with issuer/identity/not_before
core/gallery/backends.go Added backendDownloadOptions() with cosign/SHA256 verification
core/gallery/backends_test.go Test updates for verification paths
core/gallery/backends_version_test.go Test updates for version handling
core/gallery/models.go Model installation with integrity checks
core/gallery/models_test.go Test updates for model installation
core/gallery/upgrade.go UpgradeBackend resolves verification before disk write
core/gallery/upgrade_test.go Added strict mode regression test for OCI without verification policy
core/services/galleryop/backends.go InstallExternalBackend accepts requireIntegrity parameter
core/services/galleryop/backends_test.go Test updates for backend operations
core/services/galleryop/managers_local.go LocalModelManager stores requireBackendIntegrity
core/services/galleryop/models.go Model service integration
core/services/worker/config.go Added RequireBackendIntegrity to worker config
core/services/worker/install.go Worker installation with integrity checks
core/startup/model_preload.go Preload with verification options
core/startup/model_preload_test.go Test updates for preloading
go.mod Added sigstore-go, go-containerregistry, TUF, and cloud KMS dependencies
go.sum Updated checksums for new dependencies
pkg/downloader/pinned_ref_internal_test.go Table-driven tests for image reference parsing
pkg/downloader/uri.go Added ImageVerifier interface, WithImageVerifier option, and pinnedImageRef() helper
pkg/oci/cosignverify/bundle.go Sigstore bundle discovery via OCI 1.1 referrers API
pkg/oci/cosignverify/cosignverify_suite_test.go Ginkgo test suite entry point
pkg/oci/cosignverify/notbefore_internal_test.go Internal tests for enforceNotBefore revocation helper
pkg/oci/cosignverify/verify.go Core verification logic with Policy and Verifier types
pkg/oci/cosignverify/verify_test.go Ginkgo tests with 90s timeout for live verification

Review Focus Areas

  • Verification policy matching: Check that issuer/identity regex handling in pkg/oci/cosignverify/verify.go correctly rejects mismatched signatures without false positives.
  • TOCTOU protection: Verify pinnedImageRef() in pkg/downloader/uri.go:76-95 properly resolves tags to digests before verification to prevent race conditions.
  • Strict mode enforcement: Ensure UpgradeBackend in core/gallery/upgrade.go:278-295 fails fast when requireIntegrity=true and no verification policy exists.

Architecture

Design Decisions

  • Uses new Sigstore bundle format (cosign 2.2+) with OCI 1.1 referrers instead of legacy .sig tags. This is a deliberate choice: both producer and consumer are controlled by the same team, so backward compatibility is not required.
  • TUF trusted root is cached process-wide to avoid redundant fetches when installing multiple backends.
  • NotBefore timestamp serves as policy-side revocation for ephemeral Fulcio certificates rather than maintaining a CRL.
  • forbidigo linter enforces Ginkgo/Gomega testing patterns and blocks direct os.Getenv to ensure configuration flows through ApplicationConfig.

Scalability & Extensibility

  • ImageVerifier interface in pkg/downloader/uri.go:42-48 allows pluggable verification backends beyond cosign.
  • Cloud KMS providers (AWS, Azure, GCP) are included in dependencies but not yet wired to verification paths. Out of scope for this PR.

Risks

  • Intentional: Live cosign verification tests require external network and Fulcio/Rekor availability; these are gated by LOCALAI_COSIGN_LIVE env var and 90s timeout to prevent CI hangs.
  • Intentional: Strict mode is opt-in via flag/env; default behavior warns but does not block unverified backends to avoid breaking existing workflows.
  • Unintentional: TUF root caching assumes process lifetime; long-running daemons may need root refresh logic not yet implemented.

@codity-dev-utk
Copy link
Copy Markdown

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. ## Backend OCI Image Signing & Verification Workflow

  • P...

Complex complexity • Components: backend_merge.yml workflow, cosign signing integration, OCI image verification

sequenceDiagram
    title Backend OCI Image Signing and Verification Workflow

    participant CI as GitHub_Actions_CI
    participant Fulcio as Fulcio_CA
    participant Registry as OCI_Registry
    participant LocalAI as LocalAI_Runtime
    participant CosignVerify as Cosign_Verifier
    participant Gallery as Gallery_YAML

    Note over CI,Gallery: Producer Side - Image Build and Sign

    CI->>CI: Build multi-arch manifest list<br/>docker buildx imagetools create

    CI->>Fulcio: Request signing certificate<br/>Exchange OIDC token for ephemeral cert
    Fulcio-->>CI: Return 10-minute validity certificate<br/>bound to workflow identity

    CI->>CI: Resolve digest<br/>docker buildx imagetools inspect

    CI->>Registry: cosign sign --recursive --new-bundle-format<br/>Sign manifest list and per-arch entries
    Note right of CI: OCI 1.1 referrers storagebr/Sigstore bundle format

    Registry-->>CI: Confirm signature stored

    Note over CI,Gallery: Consumer Side - Backend Installation

    LocalAI->>Gallery: Fetch backend gallery index.yaml
    Gallery-->>LocalAI: Return backend entry with verification block<br/>issuer, identity_regex, optional not_before

    LocalAI->>Registry: Pull OCI image by tag
    Registry-->>LocalAI: Return manifest for target architecture

    LocalAI->>CosignVerify: Verify image with Gallery.Verification policy

    CosignVerify->>Registry: Discover signature via OCI referrers API
    Registry-->>CosignVerify: Return Sigstore bundle

    CosignVerify->>CosignVerify: Verify certificate against Fulcio
    CosignVerify->>CosignVerify: Match identity_regex against OIDC subject
    CosignVerify->>CosignVerify: Check not_before timestamp if set

    alt Verification passes
        CosignVerify-->>LocalAI: Verification success
        LocalAI->>LocalAI: Extract and install backend
    else Verification fails or missing
        alt LOCALAI_REQUIRE_BACKEND_INTEGRITY is set
            CosignVerify-->>LocalAI: Verification failure
            LocalAI->>LocalAI: Block installation with error
        else Default warning mode
            CosignVerify-->>LocalAI: Verification warning
            LocalAI->>LocalAI: Log warning and install anyway
        end
    end

    Note over CI,Gallery: Revocation Playbook - Incident Response

    alt Compromise detected
        Gallery->>Gallery: Advance not_before timestamp<br/>to invalidate pre-compromise signatures
        LocalAI->>Gallery: Refresh gallery cache
        Gallery-->>LocalAI: Updated policy with new not_before
        LocalAI->>CosignVerify: Verify subsequent installs
        CosignVerify->>CosignVerify: Reject signatures with IntegratedTime before not_before
    end
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

# 2.2+ is required for --new-bundle-format.
- name: Install cosign
if: github.event_name != 'pull_request'
uses: sigstore/cosign-installer@v3
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security High

The new sigstore/cosign-installer step is pinned to the mutable major-version ref @v3 rather than a commit SHA. This action installs the binary that produces every backend image signature; it is the trust root of the entire supply-chain integrity feature being introduced in this PR. A malicious push to the sigstore/cosign-installer repository at the v3 tag would cause CI to install an attacker-controlled cosign binary, which could (a) silently skip signing so no signature is ever produced, (b) sign with a different OIDC identity that passes a permissive consumer policy, or (c) exfiltrate OIDC tokens and registry credentials. All other actions in the file also use floating refs, but the cosign installer is uniquely load-bearing here. Fix: pin to the full commit SHA (e.g. sigstore/cosign-installer@11086d25041f77fe8fe7470324ad114c4a329dd9).

Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: .github/workflows/backend_merge.yml
Lines: 72-72
Issue Type: security-high
Severity: high

Issue Description:
The new `sigstore/cosign-installer` step is pinned to the mutable major-version ref `@v3` rather than a commit SHA. This action installs the binary that produces every backend image signature; it is the trust root of the entire supply-chain integrity feature being introduced in this PR. A malicious push to the `sigstore/cosign-installer` repository at the `v3` tag would cause CI to install an attacker-controlled cosign binary, which could (a) silently skip signing so no signature is ever produced, (b) sign with a different OIDC identity that passes a permissive consumer policy, or (c) exfiltrate OIDC tokens and registry credentials. All other actions in the file also use floating refs, but the cosign installer is uniquely load-bearing here. Fix: pin to the full commit SHA (e.g. `sigstore/cosign-installer@11086d25041f77fe8fe7470324ad114c4a329dd9`).

Current Code:
        uses: sigstore/cosign-installer@v3

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/gallery/backends.go
Comment on lines +129 to +131
if requireIntegrity {
return nil, fmt.Errorf("strict integrity: gallery %q has no verification policy for OCI backend %q (set verification: in the gallery YAML or disable --require-backend-integrity)",
config.Gallery.Name, config.Name)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness Medium

The strict-integrity error message for OCI backends: 'set verification: in the gallery YAML': is inapplicable and misleading when the install originates from InstallExternalBackend (i.e. local-ai backends install <oci-uri>, --external-backends, or startup ExternalBackends). In that path the GalleryBackend is constructed without any Gallery set (Gallery.Name=="", Gallery.Verification==nil), so strict mode unconditionally returns this error for every external OCI install. The fix hint ('set verification: in the gallery YAML') cannot be followed because there is no gallery entry to edit. Operators who enable LOCALAI_REQUIRE_BACKEND_INTEGRITY=1 and rely on external OCI backends will hit this error with no actionable guidance; the message should distinguish the external-install case and explain that ad-hoc OCI installs must be migrated to a gallery entry with a verification: block.

Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: core/gallery/backends.go
Lines: 129-131
Issue Type: robustness-medium
Severity: medium

Issue Description:
The strict-integrity error message for OCI backends: 'set verification: in the gallery YAML': is inapplicable and misleading when the install originates from `InstallExternalBackend` (i.e. `local-ai backends install <oci-uri>`, `--external-backends`, or startup `ExternalBackends`). In that path the `GalleryBackend` is constructed without any `Gallery` set (Gallery.Name=="", Gallery.Verification==nil), so strict mode unconditionally returns this error for every external OCI install. The fix hint ('set verification: in the gallery YAML') cannot be followed because there is no gallery entry to edit. Operators who enable `LOCALAI_REQUIRE_BACKEND_INTEGRITY=1` and rely on external OCI backends will hit this error with no actionable guidance; the message should distinguish the external-install case and explain that ad-hoc OCI installs must be migrated to a gallery entry with a `verification:` block.

Current Code:
            if requireIntegrity {
                return nil, fmt.Errorf("strict integrity: gallery %q has no verification policy for OCI backend %q (set verification: in the gallery YAML or disable --require-backend-integrity)",
                    config.Gallery.Name, config.Name)

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional Medium

After InstallBackendFromGallery succeeds, the code falls through to line 52 still holding the zero-value backend from the failed backends.Get call (the !ok branch installs but never re-fetches). backend.RunFile is the empty string, so filepath.Dir("") returns ".": not "". The guard if backendPath == "" therefore never fires, and the function returns "./llama-cpp-rpc-server" as the binary path. Depending on the working directory when the syscall.Exec runs, this either silently resolves to a wrong binary or fails with a confusing 'no such file' error. The parallel function findBackendPath in worker_backend_common.go correctly calls gallery.ListSystemBackends again after install; findLLamaCPPBackend should do the same.

Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: core/cli/worker/worker_llamacpp.go
Lines: 52-55
Issue Type: functional-medium
Severity: medium

Issue Description:
After `InstallBackendFromGallery` succeeds, the code falls through to line 52 still holding the zero-value `backend` from the failed `backends.Get` call (the `!ok` branch installs but never re-fetches). `backend.RunFile` is the empty string, so `filepath.Dir("")` returns `"."`: not `""`. The guard `if backendPath == ""` therefore never fires, and the function returns `"./llama-cpp-rpc-server"` as the binary path. Depending on the working directory when the syscall.Exec runs, this either silently resolves to a wrong binary or fails with a confusing 'no such file' error. The parallel function `findBackendPath` in `worker_backend_common.go` correctly calls `gallery.ListSystemBackends` again after install; `findLLamaCPPBackend` should do the same.

Current Code:
    backendPath := filepath.Dir(backend.RunFile)

    if backendPath == "" {
        return "", errors.New("llama-cpp backend not found, install it first")
    }

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@codity-dev-utk
Copy link
Copy Markdown

Security Scan

Security scan in progress...

Analyzing code for:

  • Hardcoded secrets and credentials
  • Injection vulnerabilities (SQL, Command, XSS)
  • Authentication and authorization issues
  • Cryptographic weaknesses

Results will be posted shortly...

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR Summary

What Changed

  • Added keyless cosign signature verification for OCI backend images using sigstore-go, with issuer/identity regex matching and revocation via not_before timestamp.
  • Introduced --require-backend-integrity / LOCALAI_REQUIRE_BACKEND_INTEGRITY flag to hard-fail on unverified backends (OCI without cosign policy, or tarballs without SHA256).
  • Updated CI to sign backend images with cosign sign --recursive --new-bundle-format using OCI 1.1 referrers.

Key Changes by Area

Security/Verification:

  • New pkg/oci/cosignverify/ package with verify.go (core logic), bundle.go (OCI referrers API), and Ginkgo test suite with 90s timeout for live tests.
  • GalleryVerification struct in core/config/gallery.go:78 supports issuer/identity regex and NotBefore revocation.

CLI/Config:

  • RequireBackendIntegrity flag added to ApplicationConfig and all worker subcommands (core/cli/worker/*.go).

Backend Installation:

  • InstallBackend, InstallBackendFromGallery, UpgradeBackend signatures updated to accept requireIntegrity bool parameter; upgrade now validates before atomic swap.

CI/CD:

  • .github/workflows/backend_merge.yml signs multi-arch manifests by digest after push.

Linting:

  • .golangci.yml added forbidigo rules blocking testing.T methods (enforce Ginkgo) and direct os.Getenv calls.

Files Changed

File Changes Summary
.agents/adding-backends.md Note on integrity verification for new backends
.agents/backend-signing.md Complete trust model, producer/consumer setup, strict mode, revocation playbook
.github/workflows/backend_merge.yml Added cosign sign with recursive bundle format for multi-arch manifests
.golangci.yml Added forbidigo linter rules for Ginkgo/Gomega enforcement and config discipline
AGENTS.md Updated agent documentation
core/application/startup.go Propagate integrity flag through startup
core/application/upgrade_checker.go Updated upgrade checking with integrity requirements
core/backend/llm.go Backend integration updates
core/cli/backends.go Added --require-backend-integrity flag support
core/cli/models.go Added --require-backend-integrity flag support
core/cli/run.go Added --require-backend-integrity flag support
core/cli/worker/worker.go Worker integrity flag propagation
core/cli/worker/worker_backend_common.go Worker backend common integrity handling
core/cli/worker/worker_llamacpp.go LLaMA.cpp worker integrity flag
core/cli/worker/worker_mlx_common.go MLX common worker integrity flag
core/cli/worker/worker_mlx_distributed.go MLX distributed worker integrity flag
core/cli/worker/worker_p2p.go P2P worker integrity flag
core/cli/worker/worker_p2p_mlx.go P2P MLX worker integrity flag
core/cli/worker/worker_vllm.go vLLM worker integrity flag
core/config/application_config.go Added RequireBackendIntegrity flag at line 78
core/config/gallery.go Added GalleryVerification struct with issuer/identity/NotBefore
core/gallery/backends.go Added backendDownloadOptions, newGalleryVerifier; updated InstallBackend signatures
core/gallery/backends_test.go Updated test calls with requireIntegrity parameter
core/gallery/backends_version_test.go Updated test calls with requireIntegrity parameter
core/gallery/models.go Model installation integrity updates
core/gallery/models_test.go Updated model test calls
core/gallery/upgrade.go Updated UpgradeBackend with integrity checks before atomic swap
core/gallery/upgrade_test.go Added strict mode rejection test for OCI without verification policy
core/services/galleryop/backends.go InstallExternalBackend propagates requireIntegrity
core/services/galleryop/backends_test.go Updated test calls
core/services/galleryop/managers_local.go LocalModelManager/LocalBackendManager integrity propagation
core/services/galleryop/models.go Model operations integrity updates
core/services/worker/config.go Added RequireBackendIntegrity to worker config at line 29
core/services/worker/install.go Worker install/upgrade paths respect integrity settings at lines 115-178
core/startup/model_preload.go Preload integrity handling
core/startup/model_preload_test.go Updated preload tests
go.mod Added sigstore-go, rekor, timestamp-authority, go-tuf, cloud KMS providers, certificate-transparency-go
go.sum Dependency checksum updates
pkg/downloader/pinned_ref_internal_test.go Digest pinning tests for TOCTOU prevention
pkg/downloader/uri.go Added ImageVerifier interface and WithImageVerifier option
pkg/oci/cosignverify/bundle.go Sigstore bundle discovery via OCI 1.1 referrers API
pkg/oci/cosignverify/cosignverify_suite_test.go Ginkgo test suite entry point
pkg/oci/cosignverify/notbefore_internal_test.go Internal tests for NotBefore revocation check
pkg/oci/cosignverify/verify.go Core cosign verification with policy matching and Fulcio cert validation
pkg/oci/cosignverify/verify_test.go Ginkgo tests with 90s timeout for live integration tests

Review Focus Areas

  • Policy matching logic in pkg/oci/cosignverify/verify.go: Verify issuer/identity regex handling correctly pins to expected GitHub Actions workflow paths.
  • Strict mode enforcement in core/gallery/backends.go:backendDownloadOptions(): Confirm OCI without verification policy hard-fails when requireIntegrity=true.
  • Upgrade atomicity: Ensure core/gallery/upgrade.go validates integrity before swap, preventing partial upgrades on verification failure.

Architecture

Design Decisions:

  • Uses OCI 1.1 referrers API with new Sigstore bundle format instead of legacy :sha256-<hex>.sig tags. This is deliberate for forward compatibility.
  • TUF trusted root cached per-URL to avoid redundant fetches across verifiers.
  • NotBefore timestamp acts as revocation lever since keyless Fulcio certificates are ephemeral (10-minute validity). No CRL or explicit revocation list is used by design.
  • Strict mode is opt-in via flag/env to avoid breaking existing deployments. This is intentional: security-conscious users enable it, others get warnings.

Scalability & Extensibility:

  • ImageVerifier interface in pkg/downloader/uri.go allows pluggable verification beyond cosign.
  • Cloud KMS provider dependencies (AWS, Azure, GCP) added to go.mod for future producer-side signing support. Currently out of scope for consumer verification.

Risks:

  • Intentional: No fallback to legacy cosign tag-based signatures. Images signed with old format will fail verification. Acceptable per migration plan in documentation.
  • Intentional: 90s timeout on live tests may flake on slow networks. Test is opt-in via LOCALAI_COSIGN_LIVE=1.
  • Unintentional: TUF root cache has no expiration. Could stale-pin if root rotates. Should review cache invalidation strategy.

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Backend OCI Image Signing & Verification Pipeline

Complex complexity • Components: backend_merge.yml workflow, cosign signing integration, sigstore-go verification

sequenceDiagram
    title Backend OCI Image Signing and Verification Workflow

    participant GitHubActions as GitHub Actions CI
    participant Fulcio as Fulcio CA
    participant OCIRegistry as OCI Registry
    participant LocalAI as LocalAI Runtime
    participant GalleryYAML as Gallery YAML
    participant SigstoreGo as sigstore-go

    Note over GitHubActions: Workflow backend_merge.yml triggers on merge to master

    GitHubActions->>GitHubActions: Build per-arch images with docker buildx
    GitHubActions->>GitHubActions: Create multi-arch manifest list with imagetools create
    GitHubActions->>GitHubActions: Resolve digest with imagetools inspect

    GitHubActions->>Fulcio: Exchange OIDC token for ephemeral signing certificate
    Fulcio-->>GitHubActions: Return 10-minute validity certificate bound to workflow identity

    GitHubActions->>OCIRegistry: cosign sign --recursive --new-bundle-format --registry-referrers-mode=oci-1-1
    Note right of GitHubActions: Signs both manifest list and each per-arch manifest by digest
    OCIRegistry-->>GitHubActions: Store signature as OCI 1.1 referrer with Sigstore bundle

    LocalAI->>GalleryYAML: Fetch backend gallery index on startup or refresh
    GalleryYAML-->>LocalAI: Return backend entries with verification policy block

    LocalAI->>LocalAI: Check LOCALAI_REQUIRE_BACKEND_INTEGRITY flag

    alt Strict mode enabled
        LocalAI->>LocalAI: Fail if verification block missing or verification fails
    else Default mode
        LocalAI->>LocalAI: Warn if verification block missing but allow install
    end

    LocalAI->>OCIRegistry: Request backend image by tag
    OCIRegistry-->>LocalAI: Return per-arch manifest for current platform

    LocalAI->>OCIRegistry: Query OCI referrers API for signature bundle
    OCIRegistry-->>LocalAI: Return Sigstore bundle attached to manifest digest

    LocalAI->>SigstoreGo: Verify bundle with policy from Gallery YAML
    Note right of LocalAI: Policy includes issuer, identity regex, optional not_before timestamp

    SigstoreGo-->>LocalAI: Return verification result

    alt Verification succeeds
        LocalAI->>LocalAI: Extract and install backend image
    else Verification fails
        alt Strict mode
            LocalAI->>LocalAI: Abort installation with error
        else Default mode
            LocalAI->>LocalAI: Log warning and abort installation
        end
    end

    Note over GalleryYAML: Incident response: advance not_before timestamp to revoke compromised signatures
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Security Scan

Security scan in progress...

Analyzing code for:

  • Hardcoded secrets and credentials
  • Injection vulnerabilities (SQL, Command, XSS)
  • Authentication and authorization issues
  • Cryptographic weaknesses

Results will be posted shortly...

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Backend OCI Image Signing & Verification Workflow

Complex complexity • Components: backend_merge.yml workflow, cosign signing integration, OCI image verification

sequenceDiagram
    title Backend OCI Image Signing and Verification Workflow

    participant GitHubActions as GitHub Actions CI
    participant Fulcio as Fulcio CA
    participant OCIRegistry as OCI Registry
    participant LocalAI as LocalAI Runtime
    participant CosignVerifier as Cosign Verifier
    participant SigstoreGo as Sigstore Go

    Note over GitHubActions,OCIRegistry: Producer Side - Image Signing

    GitHubActions->>Fulcio: Request signing certificate via OIDC token exchange
    Fulcio-->>GitHubActions: Return ephemeral certificate bound to workflow identity

    GitHubActions->>OCIRegistry: Push multi-arch manifest list
    GitHubActions->>OCIRegistry: Sign manifest list and per-arch entries recursively with cosign

    Note right of GitHubActions: Uses digest not tag to prevent signature orphaning

    OCIRegistry-->>GitHubActions: Store signatures as OCI 1.1 referrers in Sigstore bundle format

    Note over LocalAI,SigstoreGo: Consumer Side - Image Verification

    LocalAI->>LocalAI: Parse gallery YAML with verification block
    Note right of LocalAI: Contains issuer, identity regex, optional not_before timestamp

    LocalAI->>OCIRegistry: Request backend image by tag
    OCIRegistry-->>LocalAI: Return per-arch manifest digest

    LocalAI->>CosignVerifier: Verify image with gallery policy
    CosignVerifier->>OCIRegistry: Fetch signature bundle via OCI 1.1 referrers API
    OCIRegistry-->>CosignVerifier: Return Sigstore bundle

    CosignVerifier->>SigstoreGo: Verify signature against policy
    SigstoreGo-->>CosignVerifier: Validation result with integrated timestamp

    alt Signature valid and within not_before window
        CosignVerifier-->>LocalAI: Verification success
        LocalAI->>LocalAI: Extract and install backend
    else Signature invalid or before not_before cutoff
        CosignVerifier-->>LocalAI: Verification failure
        alt Strict mode enabled
            LocalAI->>LocalAI: Hard error - refuse installation
        else Strict mode disabled
            LocalAI->>LocalAI: Warning log - install anyway
        end
    end

    Note over LocalAI: Revocation Playbook
    Note right of LocalAI: Advance not_before in gallery YAML to invalidate compromised signatures
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Backend OCI Image Signing & Verification Flow

Complex complexity • Components: backend_merge.yml workflow, cosign signing integration, sigstore-go verification

sequenceDiagram
    title Backend Image Signing and Verification Workflow

    participant GHA as GitHub Actions
    participant Fulcio as Fulcio CA
    participant OCI as OCI Registry
    participant LocalAI as LocalAI Instance
    participant Gallery as Gallery YAML
    participant Sigstore as Sigstore Go

    Note over GHA,Fulcio: Producer Side - Image Signing

    GHA->>Fulcio: Exchange OIDC token for ephemeral signing certificate
    Fulcio-->>GHA: Return 10-minute validity certificate bound to workflow identity

    GHA->>OCI: Build and push multi-arch manifest list
    GHA->>OCI: cosign sign --recursive --new-bundle-format --registry-referrers-mode=oci-1-1 digest

    Note over OCI: Signatures stored as OCI 1.1 referrers in Sigstore bundle format

    Note over LocalAI,Sigstore: Consumer Side - Image Verification

    LocalAI->>Gallery: Fetch backend gallery with verification policy
    Gallery-->>LocalAI: Return verification block with issuer, identity_regex, optional not_before

    LocalAI->>OCI: Request backend image by tag
    OCI-->>LocalAI: Return per-arch manifest digest

    LocalAI->>OCI: Query referrers API for Sigstore bundle
    OCI-->>LocalAI: Return signature bundle

    LocalAI->>Sigstore: Verify bundle against gallery policy
    Sigstore->>Sigstore: Check issuer matches token.actions.githubusercontent.com
    Sigstore->>Sigstore: Check identity matches workflow regex pattern
    Sigstore->>Sigstore: Check signature timestamp against not_before if set

    alt Verification passes
        Sigstore-->>LocalAI: Verification success
        LocalAI->>LocalAI: Extract and install backend
    else Verification fails or missing
        alt LOCALAI_REQUIRE_BACKEND_INTEGRITY enabled
            LocalAI->>LocalAI: Block installation with error
        else Default mode
            LocalAI->>LocalAI: Install with warning logged
        end
    end

    Note over GHA,LocalAI: Revocation Playbook - Compromise Response

    alt Workflow compromise detected
        Gallery->>Gallery: Advance not_before timestamp to after compromise window
        LocalAI->>Gallery: Refresh gallery on next poll
        LocalAI->>LocalAI: Reject signatures with IntegratedTime before not_before
    end
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR Summary

What Changed

  • Added keyless cosign signature verification for OCI backend images using Sigstore, with a new requireBackendIntegrity flag to enforce strict verification policies.
  • Introduced a pkg/oci/cosignverify/ package that verifies images against gallery verification: policies using Fulcio OIDC identity matching.
  • Updated CI/CD to sign multi-arch manifests with cosign and propagate integrity checks through all backend install/upgrade paths.

Key Changes by Area

Security & Verification

  • New pkg/oci/cosignverify/ package with OIDC policy matching and revocation timestamp support.
  • Gallery YAML verification: block configures issuer, identity regex, and optional not_before revocation.

Configuration

  • RequireBackendIntegrity flag added to ApplicationConfig with CLI flag --require-backend-integrity and env var LOCALAI_REQUIRE_BACKEND_INTEGRITY.

CI/CD

  • .github/workflows/backend_merge.yml signs manifests with cosign using digest-based references and OCI 1.1 referrers.

CLI & Workers

  • All backend commands (run, backends, models, worker) and worker subcommands updated to pass integrity requirements through discovery functions.

Files Changed

File Changes Summary
.agents/adding-backends.md Added note on integrity verification for new backends
.agents/backend-signing.md Trust model, producer/consumer setup, revocation playbook
.github/workflows/backend_merge.yml Cosign signing with digest-based references and OCI 1.1 referrers
.golangci.yml Forbidigo rules blocking os.Getenv outside CLI, testing.T methods
AGENTS.md Documentation updates
core/application/startup.go Propagate requireIntegrity through startup paths
core/application/upgrade_checker.go Pass integrity flag to upgrade checks
core/backend/llm.go Updated backend discovery with integrity parameter
core/cli/backends.go Added --require-backend-integrity flag
core/cli/models.go Added integrity flag to model commands
core/cli/run.go Added integrity flag to run command
core/cli/worker/worker.go Worker integrity flag propagation
core/cli/worker/worker_backend_common.go Common worker backend integrity handling
core/cli/worker/worker_llamacpp.go LLaMA.cpp worker integrity support
core/cli/worker/worker_mlx_common.go MLX common worker integrity support
core/cli/worker/worker_mlx_distributed.go MLX distributed worker integrity support
core/cli/worker/worker_p2p.go P2P worker integrity support
core/cli/worker/worker_p2p_mlx.go P2P MLX worker integrity support
core/cli/worker/worker_vllm.go vLLM worker integrity support
core/config/application_config.go Added RequireBackendIntegrity field
core/config/gallery.go Added GalleryVerification struct with issuer/identity/NotBefore
core/gallery/backends.go backendDownloadOptions() with cosign verification; newGalleryVerifier() constructor
core/gallery/backends_test.go Updated tests for new integrity parameter
core/gallery/backends_version_test.go Updated version tests
core/gallery/models.go Propagate integrity through model operations
core/gallery/models_test.go Updated model tests
core/gallery/upgrade.go UpgradeBackend now enforces integrity before download
core/gallery/upgrade_test.go Regression test for strict mode rejecting unverified OCI backends
core/services/galleryop/backends.go InstallExternalBackend with integrity parameter
core/services/galleryop/backends_test.go Updated service tests
core/services/galleryop/managers_local.go Local managers with integrity propagation
core/services/galleryop/models.go Model service integrity handling
core/services/worker/config.go Worker config with integrity field
core/services/worker/install.go Worker install with integrity enforcement
core/startup/model_preload.go Preload with integrity checks
core/startup/model_preload_test.go Updated preload tests
go.mod Added sigstore-go, rekor, sigstore, TUF dependencies
go.sum Updated checksums for new dependencies
pkg/downloader/pinned_ref_internal_test.go Tests for digest-pinned image references
pkg/downloader/uri.go ImageVerifier interface, WithImageVerifier(), pinnedImageRef() helper
pkg/oci/cosignverify/bundle.go Sigstore bundle discovery via OCI 1.1 referrers
pkg/oci/cosignverify/cosignverify_suite_test.go Ginkgo test suite entry
pkg/oci/cosignverify/notbefore_internal_test.go enforceNotBefore revocation tests
pkg/oci/cosignverify/verify.go Core verifier with Policy, Verifier, VerifyImage
pkg/oci/cosignverify/verify_test.go Policy validation and live verification tests

Review Focus Areas

  • Upgrade path integrity: core/gallery/upgrade.go:268-278 now resolves integrity options before any filesystem mutation. Verify this prevents the previous bypass where unverified backends could be swapped in.
  • OIDC policy matching: pkg/oci/cosignverify/verify.go issuer/identity regex validation. Check that the regex anchoring prevents prefix attacks.
  • Worker propagation: Ensure all worker subcommands (worker_llamacpp.go, worker_mlx_distributed.go, etc.) correctly thread the integrity flag through to findBackendPath() calls.

Architecture

Design Decisions

  • Digest-pinned references (pinnedImageRef()) prevent TOCTOU attacks between manifest fetch and layer extraction. This trades flexibility (no tag updates mid-pull) for security.
  • TUF root caching and Rekor verification are delegated to sigstore-go with default production roots. No custom TUF infrastructure.
  • NotBefore revocation uses simple timestamp comparison rather than full CRL/OCSP. This is intentional: gallery files are versioned, so revocation is coarse-grained.

Scalability & Extensibility

  • ImageVerifier interface in pkg/downloader/uri.go allows alternative verifiers beyond cosign. Out of scope: pluggable policy engines, keyful signing, or alternative transparency logs.

Risks

  • Intentional: Live tests in verify_test.go require LOCALAI_COSIGN_LIVE_IMAGE env var and network access to Rekor/Fulcio. These are skipped in standard CI to avoid flakes and rate limits.
  • Intentional: Default requireIntegrity=false allows unverified installs with warnings only. This preserves backward compatibility but means supply-chain protection is opt-in.
  • Unintentional: Worker config plumbing through core/services/worker/config.go may have missed edge cases in P2P/MLX distributed paths. Verify all find*BackendPath() call sites pass the flag.

Merge Status

NOT MERGEABLE — PR Score 43/100, below threshold (50)

  • [H4] PR quality score (43) is below merge floor (50)
  • [H6] Code quality raw score (21) is below merge floor (40)

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Backend OCI Image Signing & Verification Workflow

Complex complexity • Components: backend_merge.yml workflow, cosign signing integration, OCI image verification

sequenceDiagram
    title: Backend OCI Image Signing and Verification Flow

    participant GitHubActions as GitHub Actions CI
    participant Fulcio as Fulcio CA
    participant OCIRegistry as OCI Registry
    participant LocalAI as LocalAI Runtime
    participant GalleryYAML as Gallery YAML Policy
    participant SigstoreGo as sigstore-go Verifier

    Note over GitHubActions: Workflow backend_merge.yml triggers on merge to master

    GitHubActions->>GitHubActions: Build per-arch images and create multi-arch manifest list
    GitHubActions->>GitHubActions: Resolve manifest list digest with docker buildx imagetools inspect

    GitHubActions->>Fulcio: Exchange OIDC token for ephemeral signing certificate
    Fulcio-->>GitHubActions: Return Fulcio certificate bound to workflow identity

    GitHubActions->>OCIRegistry: cosign sign --recursive --new-bundle-format --registry-referrers-mode=oci-1-1 registry/repo@digest
    Note over GitHubActions: Signs both manifest list and each per-arch entry

    OCIRegistry-->>GitHubActions: Store Sigstore bundle as OCI 1.1 referrer

    Note over LocalAI: User runs local-ai backends install or local-ai run

    LocalAI->>GalleryYAML: Load backend gallery with verification block
    GalleryYAML-->>LocalAI: Return policy: issuer, identity_regex, optional not_before

    LocalAI->>OCIRegistry: Pull backend image by tag
    OCIRegistry-->>LocalAI: Return per-arch manifest

    LocalAI->>OCIRegistry: Discover signature via OCI 1.1 referrers API
    OCIRegistry-->>LocalAI: Return Sigstore bundle

    LocalAI->>SigstoreGo: Verify bundle against policy
    SigstoreGo->>SigstoreGo: Check certificate issuer matches policy
    SigstoreGo->>SigstoreGo: Check OIDC identity matches identity_regex
    SigstoreGo->>SigstoreGo: Check signature timestamp against not_before if set
    SigstoreGo-->>LocalAI: Verification result

    alt Verification succeeds
        LocalAI->>LocalAI: Extract and install backend image
    else Verification fails or missing
        alt LOCALAI_REQUIRE_BACKEND_INTEGRITY is set
            LocalAI->>LocalAI: Hard error, refuse installation
        else Default mode
            LocalAI->>LocalAI: Log warning, proceed with installation
        end
    end

    Note over GitHubActions,LocalAI: Revocation scenario: compromise detected

    GitHubActions->>GalleryYAML: Advance not_before timestamp to invalidate old signatures
    LocalAI->>GalleryYAML: Refresh gallery on next poll
    GalleryYAML-->>LocalAI: Updated policy with new not_before
    LocalAI->>SigstoreGo: Re-verify existing signatures against new policy
    SigstoreGo->>SigstoreGo: Old signatures now fail timestamp check
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Clean
Files Scanned 45

No critical security issues detected

Scan completed in 36.6s

Security scan powered by Codity.ai

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

License Compliance Scan

Metric Value
Packages Scanned 980
High Risk (Strong Copyleft) 0
Medium Risk (Weak Copyleft) 6
Low Risk (Permissive) 857
Unknown License 117

Weak copyleft licenses found - verify compatibility

Some packages have unknown licenses - manual review required

Medium Risk Licenses - 6 packages

(MPL-2.0 OR Apache-2.0) (1 packages):

  • dompurify 3.4.0

MPL-2.0 (5 packages):

  • github.com/philippgille/chromem-go 0.7.0
  • github.com/libp2p/go-yamux/v5 5.1.0
  • github.com/hashicorp/golang-lru/v2 2.0.7
  • github.com/hashicorp/golang-lru 1.0.2
  • github.com/shoenig/go-m1cpu 0.1.6
Unknown Licenses - 117 packages
  • jackspeak 3.4.3 (BlueOak-1.0.0)
  • minipass 7.1.3 (BlueOak-1.0.0)
  • package-json-from-dist 1.0.1 (BlueOak-1.0.0)
  • path-scurry 1.11.1 (BlueOak-1.0.0)
  • string-width-cjs 4.2.3
  • strip-ansi-cjs 6.0.1
  • wrap-ansi-cjs 7.0.0
  • github.com/standard-webhooks/standard-webhooks/libraries 0.0.0-20260508151727-1282bb917829
  • github.com/sigstore/rekor 1.4.3
  • github.com/sigstore/sigstore 1.10.0
  • github.com/sigstore/rekor-tiles/v2 2.0.1
  • github.com/swaggo/swag/v2 2.0.0-rc4
  • github.com/sigstore/timestamp-authority/v2 2.0.3
  • github.com/tetratelabs/wazero 1.11.0
  • github.com/theupdateframework/go-tuf/v2 2.3.0
  • github.com/transparency-dev/merkle 0.0.2
  • github.com/wk8/go-ordered-map/v2 2.1.8
  • github.com/transparency-dev/formats 0.0.0-20251017110053-404c0d5b696c
  • go.mongodb.org/mongo-driver 1.17.6
  • github.com/ProtonMail/go-crypto 1.1.6

...and 97 more

Powered by Codity.ai · Docs

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Code Quality Report — utkxrsh26/LocalAI · PR #1

Scanned: 2026-06-02 19:08 UTC | Score: 21/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 1
Medium 3
Low 125
Top Findings

[CQ-LLM-003] .github/workflows/backend_merge.yml:64 (Error_Handling · HIGH)

Issue: Swallowed exceptions when no tags are found, leading to potential silent failures.
Suggestion: Log an error message and handle the case where no tags are found more explicitly.

if [ -z "$tags" ]; then
  echo "No quay.io tags from docker/metadata-action; skipping quay merge"
  exit 0
fi

[CQ-LLM-002] .github/workflows/backend_merge.yml:64 (Complexity · MEDIUM)

Issue: The function for creating the Docker image manifest list is complex and has deep nesting.
Suggestion: Consider breaking down the logic into smaller functions or steps to improve readability and maintainability.

if [ -z "$tags" ]; then
  echo "No quay.io tags from docker/metadata-action; skipping quay merge"
  exit 0
fi
# shellcheck disable=SC2086
docker buildx imagetools create $tags \

[CQ-LLM-004] .github/workflows/backend_merge.yml:64 (Performance · MEDIUM)

Issue: Potential N+1 query issue when resolving the manifest list digest for each tag.
Suggestion: Batch the operations or optimize the way tags are processed to reduce the number of queries.

first_tag=$(jq -cr '
  .tags | map(select(startswith("quay.io/"))) | .[0]
' <<< "$DOCKER_METADATA_OUTPUT_JSON")

[CQ-LLM-005] .github/workflows/backend_merge.yml:64 (Testability · MEDIUM)

Issue: Hard-coded dependencies in the workflow make it difficult to test in isolation.
Suggestion: Introduce dependency injection or configuration options to allow for easier testing.

docker buildx imagetools create $tags \

[CQ-009] .agents/adding-backends.md:115 (Style · LOW)

Issue: Line exceeds 120 characters (401 chars)
Suggestion: Break long lines into multiple lines for readability

**Note on integrity:** OCI backends installed from a gallery whose `verification:` block is set are verified against a k...

[CQ-LLM-001] .agents/backend-signing.md:1 (Documentation · LOW)

Issue: Missing docstring for the new file that describes its purpose.
Suggestion: Add a brief overview at the top of the file explaining its purpose and usage.

# Backend image signing & verification

[CQ-008] .agents/backend-signing.md:23 (Maintainability · LOW)

Issue: Magic number 10 in code
Suggestion: Extract to a named constant

- **Revocation:** Keyless cosign certs are ephemeral (10-minute Fulcio

[CQ-009] .agents/backend-signing.md:111 (Style · LOW)

Issue: Line exceeds 120 characters (123 chars)
Suggestion: Break long lines into multiple lines for readability

- `.github/workflows/backend_merge.yml` — producer-side `cosign sign --recursive` after each multi-arch manifest list pu...

[CQ-009] .golangci.yml:58 (Style · LOW)

Issue: Line exceeds 120 characters (263 chars)
Suggestion: Break long lines into multiple lines for readability

          msg: 'Plumb config through ApplicationConfig (or the relevant CLI struct) instead of reading env directly. CLI...

[CQ-009] AGENTS.md:34 (Style · LOW)

Issue: Line exceeds 120 characters (269 chars)
Suggestion: Break long lines into multiple lines for readability

| [.agents/backend-signing.md](.agents/backend-signing.md) | Backend OCI image signing (keyless cosign + sigstore-go) — ...

Per-File Breakdown

File Critical High Medium Low Total
.agents/adding-backends.md 0 0 0 1 1
.agents/backend-signing.md 0 0 0 3 3
.github/workflows/backend_merge.yml 0 1 3 0 4
.golangci.yml 0 0 0 1 1
AGENTS.md 0 0 0 1 1
core/application/startup.go 0 0 0 4 4
core/backend/llm.go 0 0 0 1 1
core/cli/backends.go 0 0 0 6 6
core/cli/models.go 0 0 0 2 2
core/cli/run.go 0 0 0 1 1
core/cli/worker/worker.go 0 0 0 5 5
core/cli/worker/worker_backend_common.go 0 0 0 1 1
core/cli/worker/worker_llamacpp.go 0 0 0 1 1
core/cli/worker/worker_mlx_common.go 0 0 0 1 1
core/config/gallery.go 0 0 0 1 1
core/gallery/backends.go 0 0 0 7 7
core/gallery/backends_test.go 0 0 0 3 3
core/gallery/models.go 0 0 0 2 2
core/gallery/models_test.go 0 0 0 1 1
core/gallery/upgrade.go 0 0 0 3 3
core/services/galleryop/backends.go 0 0 0 2 2
core/services/galleryop/managers_local.go 0 0 0 1 1
core/services/galleryop/models.go 0 0 0 9 9
core/services/worker/config.go 0 0 0 5 5
core/services/worker/install.go 0 0 0 2 2
core/startup/model_preload.go 0 0 0 4 4
core/startup/model_preload_test.go 0 0 0 2 2
go.mod 0 0 0 6 6
go.sum 0 0 0 41 41
pkg/downloader/pinned_ref_internal_test.go 0 0 0 2 2
pkg/downloader/uri.go 0 0 0 2 2
pkg/oci/cosignverify/bundle.go 0 0 0 1 1
pkg/oci/cosignverify/notbefore_internal_test.go 0 0 0 1 1
pkg/oci/cosignverify/verify_test.go 0 0 0 2 2

Recommendations

  1. Resolve High severity issues, especially error handling gaps and performance bottlenecks.
  • Run automated tests after applying fixes to verify no regressions.

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Backend Image Signing & Verification Workflow

Complex complexity • Components: backend_merge.yml workflow, cosign signing integration, OCI image verification

sequenceDiagram
    title Backend OCI Image Signing and Verification Workflow

    participant CI as GitHub_Actions_CI
    participant Fulcio as Fulcio_CA
    participant Registry as OCI_Registry
    participant LocalAI as LocalAI_Instance
    participant Verifier as Cosign_Verifier
    participant Gallery as Gallery_YAML

    CI->>CI: Build per-arch images
    CI->>CI: Create multi-arch manifest list
    CI->>CI: Resolve digest from tag
    
    CI->>Fulcio: Exchange OIDC token for signing cert
    Fulcio-->>CI: Return ephemeral certificate
    
    CI->>Registry: Push image manifest
    CI->>Registry: cosign sign --recursive --new-bundle-format --registry-referrers-mode=oci-1-1 digest
    
    Registry-->>CI: Store signature as OCI 1.1 referrer
    
    LocalAI->>Gallery: Fetch backend/index.yaml
    Gallery-->>LocalAI: Return verification policy with issuer, identity_regex, not_before
    
    LocalAI->>Registry: Request backend image by tag
    Registry-->>LocalAI: Return per-arch manifest
    
    LocalAI->>Verifier: Verify image with policy
    
    Verifier->>Registry: Discover signature via referrers API
    Registry-->>Verifier: Return Sigstore bundle
    
    Verifier->>Verifier: Validate signature with sigstore-go
    
    alt Signature valid and matches policy
        Verifier-->>LocalAI: Verification success
        LocalAI->>Registry: Pull and extract image
        Registry-->>LocalAI: Image layers
    else Signature invalid or policy mismatch
        Verifier-->>LocalAI: Verification failed
        
        alt LOCALAI_REQUIRE_BACKEND_INTEGRITY enabled
            LocalAI->>LocalAI: Hard error, refuse installation
        else Default mode
            LocalAI->>LocalAI: Log warning, allow installation
        end
    end
    
    note over CI,Registry: Producer side: Keyless signing with cosign in backend_merge.yml
    
    note over LocalAI,Gallery: Consumer side: Policy-driven verification with optional strict mode
    
    note over Gallery: Revocation via not_before timestamp advances to invalidate compromised signatures
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR Summary

What Changed

  • Added keyless cosign signature verification for OCI backend images using Sigstore's Fulcio certificates and OCI 1.1 referrers API.
  • Introduced requireIntegrity parameter throughout the backend installation pipeline to enforce strict verification when enabled.
  • Added new backends (opus, silero-vad, local-store, kitten-tts, voxcpm, pocket-tts, nemo) with expanded platform coverage for Metal and NVIDIA L4T.

Key Changes by Area

Security & Verification: New pkg/oci/cosignverify/ package implements Sigstore bundle verification with issuer/identity policy matching and not_before revocation. CI workflow signs images with --new-bundle-format --registry-referrers-mode=oci-1-1.

Configuration: ApplicationConfig.RequireBackendIntegrity flag enables strict mode via --require-backend-integrity CLI flag or LOCALAI_REQUIRE_BACKEND_INTEGRITY env var. Gallery.Verification schema defines policy in YAML.

Backend Installation: All install/upgrade paths now pass requireIntegrity through InstallBackendFromGallery, InstallExternalBackend, and worker commands. OCI URIs without verification policy hard-fail in strict mode before any network call.

Build & Registry: Makefile adds new Golang backends. backend/index.yaml expands with Metal variants and NVIDIA L4T CUDA 12/13 support.

Code Quality: .golangci.yml adds forbidigo rule banning os.Getenv outside CLI entry points to enforce configuration through typed structs.

Files Changed

File Changes Summary
.agents/backend-signing.md Documentation for producer/consumer setup and revocation playbook
.github/workflows/backend_merge.yml Cosign signing with recursive OCI 1.1 referrers for multi-arch manifests
.golangci.yml forbidigo linter rules for Ginkgo/Gomega and os.Getenv restrictions
core/cli/run.go New --require-backend-integrity flag and env var binding
core/cli/backends.go Pass requireIntegrity to gallery install functions
core/cli/models.go Propagate integrity requirement through model install paths
core/cli/worker/worker.go Worker config receives RequireBackendIntegrity
core/cli/worker/worker_backend_common.go Pass integrity flag to backend installation
core/cli/worker/worker_llamacpp.go Integrity propagation for llama.cpp worker
core/cli/worker/worker_mlx_common.go Integrity propagation for MLX workers
core/cli/worker/worker_mlx_distributed.go Integrity propagation for distributed MLX
core/cli/worker/worker_p2p.go Integrity propagation for P2P worker
core/cli/worker/worker_p2p_mlx.go Integrity propagation for P2P MLX worker
core/cli/worker/worker_vllm.go Integrity propagation for vLLM worker
core/config/application_config.go RequireBackendIntegrity bool field added
core/config/gallery.go GalleryVerification struct with issuer/identity_regex/not_before
core/gallery/backends.go backendDownloadOptions() translates policy to downloader options; strict integrity enforcement
core/gallery/backends_test.go Updated test calls with requireIntegrity=false
core/gallery/backends_version_test.go Updated test calls with requireIntegrity=false
core/gallery/models.go Propagate integrity through model installation
core/gallery/models_test.go Updated test calls with requireIntegrity=false
core/gallery/upgrade.go UpgradeBackend() signature updated with requireIntegrity
core/gallery/upgrade_test.go Regression test for OCI backends without policy in strict mode
core/services/galleryop/backends.go InstallExternalBackend() signature with requireIntegrity
core/services/galleryop/backends_test.go Updated test calls with requireIntegrity=false
core/services/galleryop/managers_local.go LocalModelManager and LocalBackendManager propagate integrity requirement
core/services/galleryop/models.go Model operations pass integrity flag
core/services/worker/config.go Config.RequireBackendIntegrity field
core/services/worker/install.go Worker installation uses integrity flag
core/startup/model_preload.go Preload operations pass integrity requirement
core/startup/model_preload_test.go Updated test calls with requireIntegrity=false
go.mod Added sigstore-go, rekor, sigstore, TUF, cloud KMS dependencies
go.sum Updated with Sigstore and related crypto dependencies
pkg/downloader/pinned_ref_internal_test.go Tests for digest-pinned ref rewriting
pkg/downloader/uri.go ImageVerifier interface and WithImageVerifier() option; verification before layer extraction
pkg/oci/cosignverify/bundle.go OCI 1.1 referrers API integration for Sigstore bundle discovery
pkg/oci/cosignverify/cosignverify_suite_test.go Ginkgo test suite bootstrap
pkg/oci/cosignverify/notbefore_internal_test.go Unit tests for enforceNotBefore revocation check
pkg/oci/cosignverify/verify.go Core verification logic with Policy struct and Verifier type
pkg/oci/cosignverify/verify_test.go Policy validation tests with 90s timeout for live integration tests

Review Focus Areas

  • Policy enforcement in backendDownloadOptions: Verify that strict mode correctly rejects OCI URIs before any network activity when verification policy is missing.
  • OCI referrer fetching in bundle.go: Check error handling when registry lacks OCI 1.1 referrers support or cosign bundle is absent.
  • Worker propagation: Ensure all worker subcommands (P2P, MLX, vLLM) correctly thread RequireBackendIntegrity through to installation calls without bypass paths.

Architecture

Design Decisions: Keyless signing chosen over static keys to eliminate key management burden. OCI 1.1 referrers API used instead of tag-based discovery to avoid race conditions and enable multi-arch verification. not_before timestamp preferred over CRL/OCSP for revocation simplicity in air-gapped environments. The forbidigo linter enforces configuration discipline: all os.Getenv calls must route through ApplicationConfig to ensure integrity flags are testable and auditable.

Scalability & Extensibility: Verification is pluggable via ImageVerifier interface. Cloud KMS providers (AWS, Azure, GCP, Vault) added to dependencies for future producer-side key management, but consumer verification remains OIDC-based. Out of scope: tarball/HTTP signature verification (SHA256 only), non-OCI artifact signing.

Risks:

  • Intentional: Strict mode is opt-in to avoid breaking existing deployments. Unverified backends log warnings only by default.
  • Intentional: Live integration tests require LOCALAI_COSIGN_LIVE=1 and network access to Sigstore infrastructure; these are not run in standard CI.
  • Unintentional: Worker commands have many call sites for backend installation. Verify no path bypasses the integrity parameter through indirect invocation or reflection-based configuration loading.

Merge Status

NOT MERGEABLE — PR Score 41/100, below threshold (50)

  • [H4] PR quality score (41) is below merge floor (50)
  • [H6] Code quality raw score (21) is below merge floor (40)

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Workflow Diagrams

Automatically generated sequence diagrams showing the workflows in this PR

1. Backend OCI Image Signing & Verification Workflow

Complex complexity • Components: backend_merge.yml workflow, cosign keyless signing, OCI image verification

sequenceDiagram
    title Backend OCI Image Signing and Verification Workflow

    participant GitHubActions as GitHub Actions CI
    participant Fulcio as Fulcio CA
    participant OCIRegistry as OCI Registry
    participant LocalAI as LocalAI Runtime
    participant SigstoreGo as Sigstore Go Verifier
    participant GalleryYAML as Gallery YAML Policy

    Note over GitHubActions,OCIRegistry: Producer Side - Image Signing

    GitHubActions->>Fulcio: Request signing certificate with OIDC token
    Fulcio-->>GitHubActions: Return ephemeral certificate bound to workflow identity

    GitHubActions->>OCIRegistry: Push multi-arch manifest list
    GitHubActions->>OCIRegistry: cosign sign --recursive --new-bundle-format --registry-referrers-mode=oci-1-1

    Note right of GitHubActions: Signs both manifest list and per-arch entries by digest
    OCIRegistry-->>GitHubActions: Store signatures as OCI 1.1 referrers

    Note over LocalAI,GalleryYAML: Consumer Side - Image Verification

    LocalAI->>GalleryYAML: Load backend gallery with verification block
    GalleryYAML-->>LocalAI: Return policy issuer identity_regex not_before

    LocalAI->>OCIRegistry: Request backend image by tag
    OCIRegistry-->>LocalAI: Return per-arch manifest digest

    LocalAI->>OCIRegistry: Query OCI referrers API for signature bundle
    OCIRegistry-->>LocalAI: Return Sigstore bundle

    LocalAI->>SigstoreGo: Verify signature with gallery policy
    SigstoreGo->>SigstoreGo: Check certificate issuer matches policy issuer
    SigstoreGo->>SigstoreGo: Check identity matches identity_regex
    SigstoreGo->>SigstoreGo: Check signature timestamp against not_before

    alt Verification succeeds
        SigstoreGo-->>LocalAI: Verification passed
        LocalAI->>LocalAI: Extract and install backend
    else Verification fails or missing
        alt Strict mode enabled LOCALAI_REQUIRE_BACKEND_INTEGRITY equals 1
            SigstoreGo-->>LocalAI: Verification failed
            LocalAI->>LocalAI: Hard error refuse installation
        else Strict mode disabled
            SigstoreGo-->>LocalAI: Verification warning
            LocalAI->>LocalAI: Log warning install anyway
        end
    end

    Note over GitHubActions,GalleryYAML: Revocation Playbook

    alt Compromise detected
        GalleryYAML->>GalleryYAML: Advance not_before timestamp
        LocalAI->>GalleryYAML: Refresh gallery policy
        GalleryYAML-->>LocalAI: Updated not_before
        LocalAI->>SigstoreGo: Verify old signature
        SigstoreGo->>SigstoreGo: Signature timestamp before not_before
        SigstoreGo-->>LocalAI: Verification failed signature revoked
    end
Loading

Note: Diagrams show detected patterns only. Complex workflows may require manual review.

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

PR Summary

What Changed

  • Added keyless cosign signature verification for OCI backend images using Sigstore/cosign, with a new RequireBackendIntegrity flag that enforces verification before installation.
  • Fixed a security issue where UpgradeBackend wrote downloaded bytes to disk before applying verification policies. Verification now happens before any filesystem changes.
  • Added new pkg/oci/cosignverify package with OCI 1.1 referrers API support for discovering Sigstore bundles.

Key Changes by Area

Security & Verification:

  • New pkg/oci/cosignverify/ package implements keyless cosign verification with configurable OIDC identity policies (issuer, identity_regex) and revocation via NotBefore timestamp.
  • RequireBackendIntegrity flag (--require-backend-integrity / LOCALAI_REQUIRE_BACKEND_INTEGRITY) rejects backend installs without valid signatures (OCI) or SHA256 checksums (tarball/HTTP).

Configuration:

  • core/config/gallery.go: Added Gallery.Verification schema with issuer/identity regex matching.
  • core/config/application_config.go: Added RequireBackendIntegrity flag with CLI/env support.

CLI:

  • Updated all backend/model install commands to pass integrity requirements through the call stack.

CI/CD:

  • .github/workflows/backend_merge.yml: Added cosign sign --recursive with --new-bundle-format and --registry-referrers-mode=oci-1-1 for multi-arch manifest lists.

Code Quality:

  • .golangci.yml: Added forbidigo rule preventing direct os.Getenv calls outside CLI entry points.

Files Changed

File Changes Summary
.agents/adding-backends.md Updated with integrity verification note
.agents/backend-signing.md New documentation for producer/consumer setup, trust model, and revocation
.github/workflows/backend_merge.yml Added cosign signing with OCI 1.1 referrers mode
.golangci.yml Added forbidigo linter rules
AGENTS.md Updated
core/application/startup.go Updated
core/application/upgrade_checker.go Updated
core/backend/llm.go Updated
core/cli/backends.go Added integrity flag support
core/cli/models.go Added integrity flag support
core/cli/run.go Added integrity flag support
core/cli/worker/worker.go Added integrity flag support
core/cli/worker/worker_backend_common.go Added integrity flag support
core/cli/worker/worker_llamacpp.go Added integrity flag support
core/cli/worker/worker_mlx_common.go Added integrity flag support
core/cli/worker/worker_mlx_distributed.go Added integrity flag support
core/cli/worker/worker_p2p.go Added integrity flag support
core/cli/worker/worker_p2p_mlx.go Added integrity flag support
core/cli/worker/worker_vllm.go Added integrity flag support
core/config/application_config.go Added RequireBackendIntegrity flag
core/config/gallery.go Added GalleryVerification struct
core/gallery/backends.go Added backendDownloadOptions() and newGalleryVerifier(); fixed verification timing
core/gallery/backends_test.go Updated tests
core/gallery/backends_version_test.go Updated tests
core/gallery/models.go Updated
core/gallery/models_test.go Updated tests
core/gallery/upgrade.go Updated UpgradeBackend() to verify before disk writes
core/gallery/upgrade_test.go Updated tests
core/services/galleryop/backends.go Threaded requireBackendIntegrity through install paths
core/services/galleryop/backends_test.go Updated tests
core/services/galleryop/managers_local.go Threaded requireBackendIntegrity through install paths
core/services/galleryop/models.go Updated
core/services/worker/config.go Added RequireBackendIntegrity worker configuration
core/services/worker/install.go Added integrity flag support
core/startup/model_preload.go Updated
core/startup/model_preload_test.go Updated tests
go.mod Added sigstore-go and related dependencies
go.sum Updated
pkg/downloader/pinned_ref_internal_test.go Added tests for pinnedImageRef() helper
pkg/downloader/uri.go Added ImageVerifier interface and WithImageVerifier() option
pkg/oci/cosignverify/bundle.go Sigstore bundle discovery via OCI 1.1 referrers API
pkg/oci/cosignverify/cosignverify_suite_test.go Ginkgo test suite entry point
pkg/oci/cosignverify/notbefore_internal_test.go Tests for enforceNotBefore() revocation helper
pkg/oci/cosignverify/verify.go Core verification logic with Policy struct and Verifier type
pkg/oci/cosignverify/verify_test.go Ginkgo tests with 90s timeout for live integration tests

Review Focus Areas

  • Verification timing in core/gallery/upgrade.go: Confirm the fix prevents TOCTOU attacks by verifying before any disk writes.
  • Policy matching in pkg/oci/cosignverify/verify.go: Review OIDC identity regex matching and NotBefore revocation logic.
  • CLI flag propagation: Check that RequireBackendIntegrity is correctly threaded through all worker and backend install paths.

Architecture

Design Decisions:

  • Opt-in by default: Missing verification policy logs a warning. RequireBackendIntegrity=true upgrades this to a hard failure. This allows gradual adoption without breaking existing workflows.
  • OCI 1.1 referrers API: Uses --new-bundle-format from cosign 2.2+ for multi-arch manifest lists. This is newer than standard cosign attachment and requires registry support.
  • Verification before extraction: The downloader runs verification after manifest fetch but before layer extraction to prevent TOCTOU attacks.

Scalability & Extensibility:

  • The ImageVerifier interface in pkg/downloader/uri.go allows pluggable verification backends beyond cosign.
  • TUF trusted material is cached in the Verifier type to avoid repeated root updates.

Risks:

  • Intentional: Keyless signing requires live Fulcio/Rekor access. Air-gapped environments cannot verify signatures. This is acceptable for the target use case (cloud-native CI/CD).
  • Intentional: OCI 1.1 referrers API is not universally supported. Older registries may fail to discover signatures. The error message should guide users to upgrade or disable strict mode.
  • Unintentional: The 90-second timeout in live tests (verify_test.go:46) may be insufficient on slow networks. Consider making this configurable.

Merge Status

NOT MERGEABLE — PR Score 23/100, below threshold (50)

  • [H4] PR quality score (23) is below merge floor (50)
  • [H5] 4 HIGH-severity inline review findings need resolution (threshold: 3)
  • [H6] Code quality raw score (22) is below merge floor (40)

return "", err
}
err := gallery.InstallBackendFromGallery(context.Background(), gals, systemState, ml, llamaCPPGalleryName, nil, true)
err := gallery.InstallBackendFromGallery(context.Background(), gals, systemState, ml, llamaCPPGalleryName, nil, true, requireIntegrity)
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Functional High

After InstallBackendFromGallery succeeds, findLLamaCPPBackend continues to use the stale backend variable that was captured before installation: at the point where backends.Get(llamaCPPGalleryName) returned ok == false. The zero-value struct has RunFile == "", so filepath.Dir("") returns "." and the gRPC server binary is looked up in the current working directory, causing the worker to fail to start.

The sibling helper findBackendPath in worker_backend_common.go handles this correctly by calling gallery.ListSystemBackends again and re-calling backends.Get after a successful install. findLLamaCPPBackend must do the same: after the error-free return from InstallBackendFromGallery, re-list the system backends and re-fetch the entry before reading backend.RunFile.

Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: core/cli/worker/worker_llamacpp.go
Lines: 46-46
Issue Type: functional-high
Severity: high

Issue Description:
After `InstallBackendFromGallery` succeeds, `findLLamaCPPBackend` continues to use the stale `backend` variable that was captured *before* installation: at the point where `backends.Get(llamaCPPGalleryName)` returned `ok == false`. The zero-value struct has `RunFile == ""`, so `filepath.Dir("")` returns `"."` and the gRPC server binary is looked up in the current working directory, causing the worker to fail to start.

The sibling helper `findBackendPath` in `worker_backend_common.go` handles this correctly by calling `gallery.ListSystemBackends` again and re-calling `backends.Get` after a successful install. `findLLamaCPPBackend` must do the same: after the error-free return from `InstallBackendFromGallery`, re-list the system backends and re-fetch the entry before reading `backend.RunFile`.

Current Code:
		err := gallery.InstallBackendFromGallery(context.Background(), gals, systemState, ml, llamaCPPGalleryName, nil, true, requireIntegrity)

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Clean
Files Scanned 45

No critical security issues detected

Scan completed in 30.9s

Security scan powered by Codity.ai

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

License Compliance Scan

Metric Value
Packages Scanned 980
High Risk (Strong Copyleft) 0
Medium Risk (Weak Copyleft) 6
Low Risk (Permissive) 835
Unknown License 139

Weak copyleft licenses found - verify compatibility

Some packages have unknown licenses - manual review required

Medium Risk Licenses - 6 packages

(MPL-2.0 OR Apache-2.0) (1 packages):

  • dompurify 3.4.0

MPL-2.0 (5 packages):

  • github.com/philippgille/chromem-go 0.7.0
  • github.com/libp2p/go-yamux/v5 5.1.0
  • github.com/hashicorp/golang-lru 1.0.2
  • github.com/hashicorp/golang-lru/v2 2.0.7
  • github.com/shoenig/go-m1cpu 0.1.6
Unknown Licenses - 139 packages
  • jackspeak 3.4.3 (BlueOak-1.0.0)
  • minipass 7.1.3 (BlueOak-1.0.0)
  • package-json-from-dist 1.0.1 (BlueOak-1.0.0)
  • path-scurry 1.11.1 (BlueOak-1.0.0)
  • string-width-cjs 4.2.3
  • strip-ansi-cjs 6.0.1
  • wrap-ansi-cjs 7.0.0
  • github.com/sigstore/rekor 1.4.3
  • github.com/sigstore/rekor-tiles/v2 2.0.1
  • github.com/sigstore/sigstore 1.10.0
  • github.com/sigstore/timestamp-authority/v2 2.0.3
  • github.com/standard-webhooks/standard-webhooks/libraries 0.0.0-20260508151727-1282bb917829
  • github.com/swaggo/swag/v2 2.0.0-rc4
  • github.com/tetratelabs/wazero 1.11.0
  • github.com/theupdateframework/go-tuf/v2 2.3.0
  • github.com/transparency-dev/formats 0.0.0-20251017110053-404c0d5b696c
  • github.com/transparency-dev/merkle 0.0.2
  • github.com/wk8/go-ordered-map/v2 2.1.8
  • go.mongodb.org/mongo-driver 1.17.6
  • github.com/PuerkitoBio/goquery 1.10.3

...and 119 more

Powered by Codity.ai · Docs

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 2, 2026

Code Quality Report — utkxrsh26/LocalAI · PR #1

Scanned: 2026-06-02 23:50 UTC | Score: 22/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 0
Medium 3
Low 126
Top Findings

[CQ-LLM-003] .github/workflows/backend_merge.yml:32 (Complexity · MEDIUM)

Issue: The job definition has multiple responsibilities, which increases complexity.
Suggestion: Consider breaking down the job into smaller, more focused jobs to reduce complexity.

jobs:
  merge:
    runs-on: ubuntu-latest

[CQ-LLM-004] .github/workflows/backend_merge.yml:121 (Error_Handling · MEDIUM)

Issue: Swallowed exception when no tags are found.
Suggestion: Log an error message or take appropriate action instead of just exiting silently.

if [ -z "$tags" ]; then
  echo "No quay.io tags from docker/metadata-action; skipping quay merge"
  exit 0
fi

[CQ-LLM-005] .github/workflows/backend_merge.yml:140 (Error_Handling · MEDIUM)

Issue: Swallowed exception when no tags are found for dockerhub.
Suggestion: Log an error message or take appropriate action instead of just exiting silently.

if [ -z "$tags" ]; then
  echo "No dockerhub tags from docker/metadata-action; skipping dockerhub merge"
  exit 0
fi

[CQ-LLM-001] .agents/adding-backends.md:113 (Documentation · LOW)

Issue: Missing docstring for the new note on integrity.
Suggestion: Add a brief description of the integrity note to clarify its purpose.

**Note on integrity:** OCI backends installed from a gallery whose `verification:` block is set are verified against a keyless-cosign policy before extraction; tarball/HTTP backends use the optional `sha256:` field.

[CQ-009] .agents/adding-backends.md:115 (Style · LOW)

Issue: Line exceeds 120 characters (401 chars)
Suggestion: Break long lines into multiple lines for readability

**Note on integrity:** OCI backends installed from a gallery whose `verification:` block is set are verified against a k...

[CQ-008] .agents/backend-signing.md:23 (Maintainability · LOW)

Issue: Magic number 10 in code
Suggestion: Extract to a named constant

- **Revocation:** Keyless cosign certs are ephemeral (10-minute Fulcio

[CQ-009] .agents/backend-signing.md:111 (Style · LOW)

Issue: Line exceeds 120 characters (123 chars)
Suggestion: Break long lines into multiple lines for readability

- `.github/workflows/backend_merge.yml` — producer-side `cosign sign --recursive` after each multi-arch manifest list pu...

[CQ-009] .golangci.yml:58 (Style · LOW)

Issue: Line exceeds 120 characters (263 chars)
Suggestion: Break long lines into multiple lines for readability

          msg: 'Plumb config through ApplicationConfig (or the relevant CLI struct) instead of reading env directly. CLI...

[CQ-009] AGENTS.md:34 (Style · LOW)

Issue: Line exceeds 120 characters (269 chars)
Suggestion: Break long lines into multiple lines for readability

| [.agents/backend-signing.md](.agents/backend-signing.md) | Backend OCI image signing (keyless cosign + sigstore-go) — ...

[CQ-009] core/application/startup.go:215 (Style · LOW)

Issue: Line exceeds 120 characters (317 chars)
Suggestion: Break long lines into multiple lines for readability

	if err := coreStartup.InstallModels(options.Context, application.GalleryService(), options.Galleries, options.BackendGa...

Per-File Breakdown

File Critical High Medium Low Total
.agents/adding-backends.md 0 0 0 2 2
.agents/backend-signing.md 0 0 0 2 3
.github/workflows/backend_merge.yml 0 0 3 0 3
.golangci.yml 0 0 0 1 1
AGENTS.md 0 0 0 1 1
core/application/startup.go 0 0 0 4 4
core/backend/llm.go 0 0 0 1 1
core/cli/backends.go 0 0 0 6 6
core/cli/models.go 0 0 0 2 2
core/cli/run.go 0 0 0 1 1
core/cli/worker/worker.go 0 0 0 5 5
core/cli/worker/worker_backend_common.go 0 0 0 1 1
core/cli/worker/worker_llamacpp.go 0 0 0 1 1
core/cli/worker/worker_mlx_common.go 0 0 0 1 1
core/config/gallery.go 0 0 0 1 1
core/gallery/backends.go 0 0 0 7 7
core/gallery/backends_test.go 0 0 0 3 3
core/gallery/models.go 0 0 0 2 2
core/gallery/models_test.go 0 0 0 1 1
core/gallery/upgrade.go 0 0 0 3 3
core/services/galleryop/backends.go 0 0 0 2 2
core/services/galleryop/managers_local.go 0 0 0 1 1
core/services/galleryop/models.go 0 0 0 9 9
core/services/worker/config.go 0 0 0 5 5
core/services/worker/install.go 0 0 0 2 2
core/startup/model_preload.go 0 0 0 4 4
core/startup/model_preload_test.go 0 0 0 2 2
go.mod 0 0 0 6 6
go.sum 0 0 0 41 41
pkg/downloader/pinned_ref_internal_test.go 0 0 0 2 2
pkg/downloader/uri.go 0 0 0 2 2
pkg/oci/cosignverify/bundle.go 0 0 0 1 1
pkg/oci/cosignverify/notbefore_internal_test.go 0 0 0 1 1
pkg/oci/cosignverify/verify_test.go 0 0 0 2 2

Recommendations

  • Run automated tests after applying fixes to verify no regressions.

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 3, 2026

PR review started! Estimated time: 5-10 minutes.

Custom Review Instructions Detected
source: context file (CLAUDE.md / .cursorrules)

# LocalAI Agent Instructions

This file is the entry point for AI coding assistants (Claude Code, Cursor, Copilot, Codex, Aider, etc.) working on LocalAI. It is an index to detailed topic guides in the `.agents/` directory. Read the relevant file(s) for the task at hand — you don't need to load all of them.

Human contributors: see [CONTRIBUTING.md](CONTRIBUTING.md) for the development workflow.

## Policy for AI-Assisted Contributions

LocalAI follows the Linux kernel project's [guidelines for 
...
Learn More

View Analytics Dashboard

Ask Codity questions: Mention @codity {your question} in a comment to get answers about the code.

Trigger a manual review: Comment @codity review on a PR or MR.

Generate unit tests: Comment /generate-tests to auto-generate tests for Go, Python, Ruby, JavaScript, TypeScript, and Java files.

Run security scan again: Comment /security-scan to run SAST and dependency vulnerability scans for all major languages in your repo.

View Full Docs

Comment on lines +149 to +156
' <<< "$DOCKER_METADATA_OUTPUT_JSON")
digest=$(docker buildx imagetools inspect "$first_tag" --format '{{.Manifest.Digest}}')
# --recursive walks the list and signs every per-arch entry
# too — clients that resolve a tag to a platform-specific
# manifest before checking signatures need the per-arch
# signatures, not just the list-level one.
cosign sign --yes --recursive \
--new-bundle-format \
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Robustness High

The quay.io signing block assigns digest from docker buildx imagetools inspect but never validates that the result is non-empty before handing it to cosign sign. If the inspect call fails silently (e.g., a transient registry error, an empty format template result, or a race where the pushed tag is momentarily unresolvable), the shell assignment succeeds with an empty string and the subsequent command becomes cosign sign ... "quay.io/go-skynet/local-ai-backends@". Cosign will reject the malformed reference with an opaque error rather than a clear 'digest is empty' message, making the failure hard to diagnose in CI. Worse, if cosign were to interpret an empty digest as 'sign whatever the tag currently resolves to', the wrong manifest could be signed. A one-line guard makes the intent explicit and surfaces the root cause immediately.

Also reported at: .github/workflows/backend_merge.yml L179–L188

Suggested fix
          digest=$(docker buildx imagetools inspect "$first_tag" --format '{{.Manifest.Digest}}')
          if [ -z "$digest" ]; then
            echo "ERROR: failed to resolve manifest-list digest for ${first_tag}; cannot sign" >&2
            exit 1
          fi
          # --recursive walks the list and signs every per-arch entry
          # too — clients that resolve a tag to a per-arch manifest before
          # checking signatures need the per-arch signatures, not just the list-level one.
          cosign sign --yes --recursive \
            --new-bundle-format \
            --registry-referrers-mode=oci-1-1 \
            "quay.io/go-skynet/local-ai-backends@${digest}"
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: .github/workflows/backend_merge.yml
Lines: 149-156
Issue Type: robustness-high
Severity: high

Issue Description:
The quay.io signing block assigns `digest` from `docker buildx imagetools inspect` but never validates that the result is non-empty before handing it to `cosign sign`. If the inspect call fails silently (e.g., a transient registry error, an empty format template result, or a race where the pushed tag is momentarily unresolvable), the shell assignment succeeds with an empty string and the subsequent command becomes `cosign sign ... "quay.io/go-skynet/local-ai-backends@"`. Cosign will reject the malformed reference with an opaque error rather than a clear 'digest is empty' message, making the failure hard to diagnose in CI. Worse, if cosign were to interpret an empty digest as 'sign whatever the tag currently resolves to', the wrong manifest could be signed. A one-line guard makes the intent explicit and surfaces the root cause immediately.

_Also reported at: `.github/workflows/backend_merge.yml` L179–L188_

Current Code:
          digest=$(docker buildx imagetools inspect "$first_tag" --format '{{.Manifest.Digest}}')
          # --recursive walks the list and signs every per-arch entry
          # too — clients that resolve a tag to a per-arch manifest before
          # checking signatures need the per-arch signatures, not just the list-level one.
          cosign sign --yes --recursive \
            --new-bundle-format \
            --registry-referrers-mode=oci-1-1 \
            "quay.io/go-skynet/local-ai-backends@${digest}"

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

Comment thread core/gallery/backends.go
Comment on lines +157 to +176
// newGalleryVerifier constructs a cosignverify.Verifier from the gallery
// policy. Parses NotBefore (RFC3339) here so YAML errors surface at install
// time rather than during signature verification.
func newGalleryVerifier(p *config.GalleryVerification) (*cosignverify.Verifier, error) {
pol := cosignverify.Policy{
Issuer: p.Issuer,
IssuerRegex: p.IssuerRegex,
Identity: p.Identity,
IdentityRegex: p.IdentityRegex,
}
if p.NotBefore != "" {
t, err := time.Parse(time.RFC3339, p.NotBefore)
if err != nil {
return nil, fmt.Errorf("not_before %q: %w", p.NotBefore, err)
}
pol.NotBefore = t
}
return cosignverify.NewVerifier(pol, nil, nil)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Security High

newGalleryVerifier constructs a cosignverify.Policy from the gallery YAML fields without validating that the policy contains at least one non-empty identity constraint. The backend-signing.md documentation explicitly warns: "Without this, any image signed by anyone with a Fulcio cert would pass: the regex is what makes a signature mean 'produced by our CI'." A gallery operator who writes verification: {} (empty block, e.g. to enable the non-nil check that gates verification) or verification:\n not_before: "2026-01-01T00:00:00Z" (only a revocation cutoff, no identity pin) will get a verifier that accepts any valid Fulcio-signed OCI image as a legitimate LocalAI backend. The nil-pointer guard in backendDownloadOptions (config.Gallery.Verification != nil) considers such a block as "has a policy" and proceeds to build the verifier, giving a false sense of security. Validate that at least one of Issuer/IssuerRegex AND at least one of Identity/IdentityRegex are non-empty before calling cosignverify.NewVerifier.

Suggested fix
func newGalleryVerifier(p *config.GalleryVerification) (*cosignverify.Verifier, error) {
	if p.Issuer == "" && p.IssuerRegex == "" {
		return nil, fmt.Errorf("gallery verification policy must specify at least one of issuer or issuer_regex")
	}
	if p.Identity == "" && p.IdentityRegex == "" {
		return nil, fmt.Errorf("gallery verification policy must specify at least one of identity or identity_regex")
	}
	pol := cosignverify.Policy{
		Issuer:        p.Issuer,
		IssuerRegex:   p.IssuerRegex,
		Identity:      p.Identity,
		IdentityRegex: p.IdentityRegex,
	}
Prompt for AI assistance

Copy the prompt below and paste it into ChatGPT, Claude, or any LLM:

You are an expert bash developer with deep knowledge of security, performance, and best practices.

### Context

File: core/gallery/backends.go
Lines: 157-176
Issue Type: security-high
Severity: high

Issue Description:
newGalleryVerifier constructs a cosignverify.Policy from the gallery YAML fields without validating that the policy contains at least one non-empty identity constraint. The backend-signing.md documentation explicitly warns: "Without this, any image signed by *anyone* with a Fulcio cert would pass: the regex is what makes a signature mean 'produced by our CI'." A gallery operator who writes `verification: {}` (empty block, e.g. to enable the non-nil check that gates verification) or `verification:\n  not_before: "2026-01-01T00:00:00Z"` (only a revocation cutoff, no identity pin) will get a verifier that accepts any valid Fulcio-signed OCI image as a legitimate LocalAI backend. The nil-pointer guard in backendDownloadOptions (`config.Gallery.Verification != nil`) considers such a block as "has a policy" and proceeds to build the verifier, giving a false sense of security. Validate that at least one of Issuer/IssuerRegex AND at least one of Identity/IdentityRegex are non-empty before calling cosignverify.NewVerifier.

Current Code:
func newGalleryVerifier(p *config.GalleryVerification) (*cosignverify.Verifier, error) {
	pol := cosignverify.Policy{
		Issuer:        p.Issuer,
		IssuerRegex:   p.IssuerRegex,
		Identity:      p.Identity,
		IdentityRegex: p.IdentityRegex,
	}

---

### Instructions

1. Fix the issue described above
2. Maintain the exact indentation and code style from the original
3. Follow bash best practices and language-specific idioms
4. Ensure the fix addresses the root cause, not just the symptoms
5. Add brief inline comments explaining the fix if needed

### Constraints

- Do not change functionality beyond fixing the identified issue
- Preserve existing variable names and function signatures unless they are part of the problem
- Ensure the fix is production-ready

---


Like Dislike Create Issue Jira

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 3, 2026

PR Summary

What Changed

  • Added keyless cosign signature verification for backend OCI images using Sigstore, with a new requireBackendIntegrity flag to enforce signed installations.
  • Introduced gallery-level verification policies (issuer, identity regex, revocation timestamps) and integrated verification into all backend download paths before any disk writes.
  • Added CI signing to backend builds and blocked direct os.Getenv calls outside CLI entry points via linter rules.

Key Changes by Area

Security/Verification: New pkg/oci/cosignverify/ package discovers Sigstore bundles via OCI 1.1 referrers API and validates against Fulcio-issued certificates with TUF root caching.

CLI/Config: New --require-backend-integrity flag and LOCALAI_REQUIRE_BACKEND_INTEGRITY env var added to all backend-related commands (run, backends, models, worker subcommands).

Gallery/Installation: Verification struct added to gallery schema; backendDownloadOptions() enforces cosign for OCI URIs and SHA256 for non-OCI URIs in strict mode; atomic upgrades verify before swapping.

CI/CD: Backend merge workflow now signs multi-arch manifests with cosign sign --recursive --new-bundle-format using GitHub OIDC.

Files Changed

File Changes Summary
.agents/adding-backends.md Note on integrity verification for new backends
.agents/backend-signing.md Trust model, setup guide, and incident response playbook
.github/workflows/backend_merge.yml Added cosign sign step after manifest push
.golangci.yml Added forbidigo rule banning os.Getenv outside CLI/test paths
AGENTS.md Updated agent documentation
core/application/startup.go Propagated requireIntegrity flag
core/application/upgrade_checker.go Propagated requireIntegrity flag
core/backend/llm.go Propagated requireIntegrity flag
core/cli/backends.go Added --require-backend-integrity flag
core/cli/models.go Added --require-backend-integrity flag
core/cli/run.go Added --require-backend-integrity flag
core/cli/worker/worker.go Added --require-backend-integrity flag
core/cli/worker/worker_backend_common.go Propagated requireIntegrity to backend discovery
core/cli/worker/worker_llamacpp.go Propagated requireIntegrity flag
core/cli/worker/worker_mlx_common.go Propagated requireIntegrity flag
core/cli/worker/worker_mlx_distributed.go Propagated requireIntegrity flag
core/cli/worker/worker_p2p.go Propagated requireIntegrity flag
core/cli/worker/worker_p2p_mlx.go Propagated requireIntegrity flag
core/cli/worker/worker_vllm.go Propagated requireIntegrity flag
core/config/application_config.go Added RequireBackendIntegrity field
core/config/gallery.go Added Verification struct with issuer/identity/not_before
core/gallery/backends.go Added backendDownloadOptions() with cosign/SHA256 enforcement
core/gallery/backends_test.go Updated tests with requireIntegrity parameter
core/gallery/backends_version_test.go Updated tests with requireIntegrity parameter
core/gallery/models.go Propagated requireIntegrity through model installation
core/gallery/models_test.go Updated tests with requireIntegrity parameter
core/gallery/upgrade.go Atomic upgrade with pre-write verification
core/gallery/upgrade_test.go Added strict mode rejection test; updated call sites
core/services/galleryop/backends.go Updated signatures to accept requireIntegrity
core/services/galleryop/backends_test.go Updated tests with requireIntegrity parameter
core/services/galleryop/managers_local.go Propagated requireIntegrity through local manager
core/services/galleryop/models.go Propagated requireIntegrity through model operations
core/services/worker/config.go Added env var binding for LOCALAI_REQUIRE_BACKEND_INTEGRITY
core/services/worker/install.go Propagated requireIntegrity to worker installs
core/startup/model_preload.go Propagated requireIntegrity through preload path
core/startup/model_preload_test.go Updated tests with requireIntegrity parameter
go.mod Added sigstore-go and related dependencies
go.sum Updated with Sigstore dependency checksums
pkg/downloader/pinned_ref_internal_test.go Tests for tag-to-digest pinning helper
pkg/downloader/uri.go Added ImageVerifier interface, WithImageVerifier(), pinnedImageRef()
pkg/oci/cosignverify/bundle.go OCI 1.1 referrers API bundle discovery
pkg/oci/cosignverify/cosignverify_suite_test.go Ginkgo test suite setup
pkg/oci/cosignverify/notbefore_internal_test.go Revocation timestamp validation tests
pkg/oci/cosignverify/verify.go Core cosign verification with TUF caching
pkg/oci/cosignverify/verify_test.go Policy validation and live integration tests (90s timeout)

Review Focus Areas

  • Verification policy matching: Check that issuer/identity regex handling in pkg/oci/cosignverify/verify.go correctly rejects mismatched certificates without false positives.
  • TOCTOU in download path: Confirm pinnedImageRef() in pkg/downloader/uri.go:76-93 resolves tags to digests before verification runs, preventing race conditions between verify and extract.
  • Flag propagation completeness: Ensure all worker backend discovery paths (worker_*.go files) thread requireIntegrity through to InstallExternalBackend calls.

Architecture

Design Decisions: Verification runs before any disk writes to prevent tampered bytes from reaching storage. The forbidigo linter rule forces env var access into CLI layer for testability. TUF roots are cached per-process to avoid Sigstore rate limits.

Scalability & Extensibility: Out of scope for this PR. The verification policy struct can extend to support additional signature schemes beyond cosign.

Risks:

  • Intentional: Live cosign tests require network and are gated behind LOCALAI_COSIGN_LIVE=1; these may flake in CI and are not run by default.
  • Intentional: Strict mode breaks backward compatibility. Galleries without verification: blocks will reject OCI backends when requireBackendIntegrity=true.
  • Unintentional: The 90s test timeout in verify_test.go:90 may still be insufficient for slow networks.

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 3, 2026

Security Scan

Security scan in progress...

Analyzing code for:

  • Hardcoded secrets and credentials
  • Injection vulnerabilities (SQL, Command, XSS)
  • Authentication and authorization issues
  • Cryptographic weaknesses

Results will be posted shortly...

@utkxrsh26
Copy link
Copy Markdown
Owner Author

@codity review

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 4, 2026

PR Summary

What Changed

  • Added keyless cosign signature verification for OCI backend images using sigstore-go, with signatures stored as OCI 1.1 referrers.
  • Introduced --require-backend-integrity flag to enforce strict verification (reject unverifiable backends) instead of warning-only mode.
  • CI now signs multi-arch backend images automatically after each push.

Key Changes by Area

Security/Verification: New pkg/oci/cosignverify/ package implements policy-based verification with issuer/identity regex matching, TUF root pinning, and not_before revocation timestamps.

CLI/Config: RequireBackendIntegrity option added to ApplicationConfig and threaded through all backend install, upgrade, and model install paths.

CI/CD: .github/workflows/backend_merge.yml signs images with cosign sign --recursive --new-bundle-format and stores signatures as OCI referrers.

Gallery: New GalleryVerification config defines verification policies; backendDownloadOptions() gates downloads on policy compliance.

Files Changed

File Changes Summary
.agents/backend-signing.md Documentation for trust model, CI setup, gallery config, and incident response
.github/workflows/backend_merge.yml Added cosign signing step for multi-arch manifests
.golangci.yml Added forbidigo linter; disabled staticcheck
core/config/application_config.go Added RequireBackendIntegrity field
core/config/gallery.go Added GalleryVerification struct with issuer/identity/not_before fields
core/cli/run.go Added --require-backend-integrity flag
core/cli/backends.go Threaded requireIntegrity through backend commands
core/cli/models.go Threaded requireIntegrity through model install
core/cli/worker/worker.go Added integrity flag to worker subcommands
core/gallery/backends.go Added backendDownloadOptions() with verification gating
core/gallery/backends_test.go Added strict mode rejection tests
core/gallery/upgrade.go Updated UpgradeBackend() to use verification flow
core/gallery/upgrade_test.go Added upgrade rollback behavior tests
core/services/galleryop/backends.go Updated signatures to accept requireIntegrity
core/services/galleryop/managers_local.go Propagated integrity requirement through managers
pkg/oci/cosignverify/verify.go Core sigstore-go verification logic with Policy struct
pkg/oci/cosignverify/bundle.go OCI 1.1 referrers API for Sigstore bundle discovery
pkg/oci/cosignverify/verify_test.go Ginkgo tests with 90s timeout for live verification
pkg/downloader/uri.go Added ImageVerifier interface and digest pinning
go.mod Added sigstore-go, go-containerregistry, cloud KMS dependencies

Review Focus Areas

  • Verification policy matching in pkg/oci/cosignverify/verify.go:Policy.Validate() - ensure regex patterns behave as expected.
  • TOCTOU protection in pkg/downloader/uri.go:pinnedImageRef() - confirm digest pinning happens before any layer extraction.
  • Strict mode enforcement in core/gallery/backends.go:backendDownloadOptions() - verify fail-closed behavior when requireIntegrity=true and policy is missing.

Architecture

Design Decisions: Keyless signing chosen over key-based to eliminate key management burden; OCI 1.1 referrers avoid tag clutter. Digest pinning prevents race conditions between manifest verification and layer download. forbidigo linter enforces configuration flow through ApplicationConfig rather than scattered os.Getenv calls.

Scalability & Extensibility: Cloud KMS providers (AWS, Azure, GCP, Vault) added to dependencies but not yet wired to verification logic. Out of scope for this PR.

Risks:

  • Intentional: Live cosign tests require LOCALAI_COSIGN_LIVE=1 and network access; 90s timeout added to prevent CI hangs.
  • Unintentional: Large dependency footprint from sigstore-go and cloud KMS libraries increases binary size and supply chain surface area.

Merge Status

NOT MERGEABLE — PR Score 14/100, below threshold (50)

  • [H4] PR quality score (14) is below merge floor (50)
  • [H5] 6 HIGH-severity inline review findings need resolution (threshold: 3)
  • [H6] Code quality raw score (23) is below merge floor (40)

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 4, 2026

Security Scan Summary

Metric Value
Vulnerabilities Critical: 0
Overall Risk Clean
Files Scanned 45

No critical security issues detected

Scan completed in 34.3s

Security scan powered by Codity.ai

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 4, 2026

License Compliance Scan

Metric Value
Packages Scanned 980
High Risk (Strong Copyleft) 0
Medium Risk (Weak Copyleft) 6
Low Risk (Permissive) 870
Unknown License 104

Weak copyleft licenses found - verify compatibility

Some packages have unknown licenses - manual review required

Medium Risk Licenses - 6 packages

(MPL-2.0 OR Apache-2.0) (1 packages):

  • dompurify 3.4.0

MPL-2.0 (5 packages):

  • github.com/philippgille/chromem-go 0.7.0
  • github.com/libp2p/go-yamux/v5 5.1.0
  • github.com/hashicorp/golang-lru/v2 2.0.7
  • github.com/hashicorp/golang-lru 1.0.2
  • github.com/shoenig/go-m1cpu 0.1.6
Unknown Licenses - 104 packages
  • jackspeak 3.4.3 (BlueOak-1.0.0)
  • minipass 7.1.3 (BlueOak-1.0.0)
  • package-json-from-dist 1.0.1 (BlueOak-1.0.0)
  • path-scurry 1.11.1 (BlueOak-1.0.0)
  • string-width-cjs 4.2.3
  • strip-ansi-cjs 6.0.1
  • wrap-ansi-cjs 7.0.0
  • github.com/sigstore/protobuf-specs 0.5.1
  • github.com/sigstore/rekor-tiles/v2 2.0.1
  • github.com/sigstore/rekor 1.4.3
  • github.com/sigstore/sigstore 1.10.0
  • github.com/sigstore/timestamp-authority/v2 2.0.3
  • github.com/standard-webhooks/standard-webhooks/libraries 0.0.0-20260508151727-1282bb917829
  • github.com/swaggo/swag/v2 2.0.0-rc4
  • github.com/tetratelabs/wazero 1.11.0
  • github.com/theupdateframework/go-tuf/v2 2.3.0
  • github.com/transparency-dev/formats 0.0.0-20251017110053-404c0d5b696c
  • github.com/transparency-dev/merkle 0.0.2
  • github.com/wk8/go-ordered-map/v2 2.1.8
  • go.mongodb.org/mongo-driver 1.17.6

...and 84 more

Powered by Codity.ai · Docs

@codity-dev-utk
Copy link
Copy Markdown

codity-dev-utk Bot commented Jun 4, 2026

Code Quality Report — utkxrsh26/LocalAI · PR #1

Scanned: 2026-06-04 12:44 UTC | Score: 23/100 | Provider: github

Executive Summary

Severity Count
Critical 0
High 0
Medium 3
Low 125
Top Findings

[CQ-LLM-002] .agents/backend-signing.md:1 (Documentation · MEDIUM)

Issue: Missing docstring for the new file.
Suggestion: Add a summary docstring at the top of the file to describe its purpose and contents.

# Backend image signing & verification

[CQ-LLM-003] .github/workflows/backend_merge.yml:32 (Documentation · MEDIUM)

Issue: Missing docstring for the permissions section.
Suggestion: Add a comment explaining the purpose of the permissions required for the workflow.

permissions:
  contents: read
  id-token: write

[CQ-LLM-004] .github/workflows/backend_merge.yml:58 (Documentation · MEDIUM)

Issue: Missing docstring for the cosign installation step.
Suggestion: Add a comment explaining the purpose of installing cosign and its version requirement.

- name: Install cosign
  if: github.event_name != 'pull_request'
  uses: sigstore/cosign-installer@v3

[CQ-LLM-001] .agents/adding-backends.md:113 (Documentation · LOW)

Issue: Missing docstring for the new note on integrity.
Suggestion: Add a brief description of the integrity note to clarify its purpose.

**Note on integrity:** OCI backends installed from a gallery whose `verification:` block is set are verified against a keyless-cosign policy before extraction; tarball/HTTP backends use the optional `sha256:` field.

[CQ-009] .agents/adding-backends.md:115 (Style · LOW)

Issue: Line exceeds 120 characters (401 chars)
Suggestion: Break long lines into multiple lines for readability

**Note on integrity:** OCI backends installed from a gallery whose `verification:` block is set are verified against a k...

[CQ-008] .agents/backend-signing.md:23 (Maintainability · LOW)

Issue: Magic number 10 in code
Suggestion: Extract to a named constant

- **Revocation:** Keyless cosign certs are ephemeral (10-minute Fulcio

[CQ-009] .agents/backend-signing.md:111 (Style · LOW)

Issue: Line exceeds 120 characters (123 chars)
Suggestion: Break long lines into multiple lines for readability

- `.github/workflows/backend_merge.yml` — producer-side `cosign sign --recursive` after each multi-arch manifest list pu...

[CQ-009] .golangci.yml:58 (Style · LOW)

Issue: Line exceeds 120 characters (263 chars)
Suggestion: Break long lines into multiple lines for readability

          msg: 'Plumb config through ApplicationConfig (or the relevant CLI struct) instead of reading env directly. CLI...

[CQ-009] AGENTS.md:34 (Style · LOW)

Issue: Line exceeds 120 characters (269 chars)
Suggestion: Break long lines into multiple lines for readability

| [.agents/backend-signing.md](.agents/backend-signing.md) | Backend OCI image signing (keyless cosign + sigstore-go) — ...

[CQ-009] core/application/startup.go:215 (Style · LOW)

Issue: Line exceeds 120 characters (317 chars)
Suggestion: Break long lines into multiple lines for readability

	if err := coreStartup.InstallModels(options.Context, application.GalleryService(), options.Galleries, options.BackendGa...

Per-File Breakdown

File Critical High Medium Low Total
.agents/adding-backends.md 0 0 0 2 2
.agents/backend-signing.md 0 0 1 2 3
.github/workflows/backend_merge.yml 0 0 2 0 2
.golangci.yml 0 0 0 1 1
AGENTS.md 0 0 0 1 1
core/application/startup.go 0 0 0 4 4
core/backend/llm.go 0 0 0 1 1
core/cli/backends.go 0 0 0 6 6
core/cli/models.go 0 0 0 2 2
core/cli/run.go 0 0 0 1 1
core/cli/worker/worker.go 0 0 0 5 5
core/cli/worker/worker_backend_common.go 0 0 0 1 1
core/cli/worker/worker_llamacpp.go 0 0 0 1 1
core/cli/worker/worker_mlx_common.go 0 0 0 1 1
core/config/gallery.go 0 0 0 1 1
core/gallery/backends.go 0 0 0 7 7
core/gallery/backends_test.go 0 0 0 3 3
core/gallery/models.go 0 0 0 2 2
core/gallery/models_test.go 0 0 0 1 1
core/gallery/upgrade.go 0 0 0 3 3
core/services/galleryop/backends.go 0 0 0 2 2
core/services/galleryop/managers_local.go 0 0 0 1 1
core/services/galleryop/models.go 0 0 0 9 9
core/services/worker/config.go 0 0 0 5 5
core/services/worker/install.go 0 0 0 2 2
core/startup/model_preload.go 0 0 0 4 4
core/startup/model_preload_test.go 0 0 0 2 2
go.mod 0 0 0 6 6
go.sum 0 0 0 41 41
pkg/downloader/pinned_ref_internal_test.go 0 0 0 2 2
pkg/downloader/uri.go 0 0 0 2 2
pkg/oci/cosignverify/bundle.go 0 0 0 1 1
pkg/oci/cosignverify/notbefore_internal_test.go 0 0 0 1 1
pkg/oci/cosignverify/verify_test.go 0 0 0 2 2

Recommendations

  • Run automated tests after applying fixes to verify no regressions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants