Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions .github/workflows/reusable-security-source.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,17 @@ on:
description: Allow package metadata queries to the OSV vulnerability service
type: boolean
default: false
extended:
description: Enable local-rule Semgrep and npm component SBOM
type: boolean
default: false
permissions:
contents: read
jobs:
source:
if: inputs.confirmed && github.event_name == 'workflow_dispatch' && github.ref_name == github.event.repository.default_branch
runs-on: ubuntu-24.04
timeout-minutes: 20
timeout-minutes: 25
steps:
- name: Validate engine pin
env:
Expand Down Expand Up @@ -51,9 +55,10 @@ jobs:
- name: Scan immutable product revision
env:
ONLINE_SCA: ${{ inputs.allow_online_sca }}
EXTENDED: ${{ inputs.extended }}
run: |
test "$(git -C product rev-parse HEAD)" = "$GITHUB_SHA"
node engine/security-assurance/scan-source.mjs product "$RUNNER_TEMP/appfactory-scanners" "$RUNNER_TEMP/security-source-summary.json" "$ONLINE_SCA"
node engine/security-assurance/scan-source.mjs product "$RUNNER_TEMP/appfactory-scanners" "$RUNNER_TEMP/security-source-summary.json" "$ONLINE_SCA" "$EXTENDED"
- name: Upload redacted aggregate summary only
if: always()
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
Expand Down
4 changes: 3 additions & 1 deletion .github/workflows/security-source-canary.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ on:
branches: [main]
paths:
- 'security-assurance/scanner-lock.json'
- 'security-assurance/sast-sbom.mjs'
- 'security-assurance/semgrep-rules.yml'
- 'security-assurance/install-scanners.sh'
- 'security-assurance/scan-source.mjs'
- 'security-assurance/scanner-results.mjs'
Expand All @@ -19,7 +21,7 @@ jobs:
canary:
if: github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-24.04
timeout-minutes: 10
timeout-minutes: 25
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
Expand Down
6 changes: 6 additions & 0 deletions docs/security-source-scanning.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,9 @@ The engine scans HEAD reachable Git history (not all remote refs) with default G

Raw reports remain in private temp directory, removed in finally; stdout/CI summary contains fixed statuses and aggregate counts only. No filenames, source snippets, secret values or package identifiers published in artifacts. Real findings require remediation and rotation when applicable; run the approved scanners locally in a restricted environment for detailed diagnosis. Report is metadata, not cryptographically verified scanner provenance. It is not a reviewed findings inventory for the ASVS gate. Trusted policy, independent evidence provenance, selected L3 requirements and normalized review remain separate work. No silent downgrade or skip treated as clean.
Local canary tests and actual binary execution must be verified before activating a product. See [engine](security-assurance.md) and [issue #199](https://github.com/Trigenys/appfactory/issues/199).

## Phase 2 — opt-in local-rule SAST and CycloneDX component inventory

Semgrep CE 1.187.0 Linux amd64 image pinned to the official nonroot manifest digest in scanner-lock.json (Docker Hub 2026-12-01). Image ~426 MB compressed; only pull on explicit extended runs or the source canary; never on VPS by default. Run with network disabled, no consumer code execution, read-only source snapshot and root filesystem, no privileges, bounded resources, local rules only, metrics/version checks disabled. Copies only tracked regular JS/TS sources (2000 files / 50 MiB total / 1 MB per file bound), not consumer configuration. Path coverage and errors checked; nosemgrep disabled. Three initial risk patterns (eval, new Function, document.write), NOT general SAST coverage. Other languages and vulnerabilities require reviewed rules. No scanner output or finding snippets uploaded.

Extended mode defaults false for compatibility. The driver reports structured SAST and SBOM statuses; extended exit 0 requires scoped SAST CLEAN and SBOM GENERATED. The CycloneDX 1.5 component inventory uses existing OSV all-packages results, deduplicated by npm name/version; no extra SCA queries. It does not assert full deployed inventory, dependency graph, component hashes, licenses or suppliers. A BOM can be generated even with vulnerabilities. Missing or partial SCA coverage blocks generation. No lockfile = no SBOM. Optional final driver argument writes the BOM to a new private local file (refuses overwrite); CI emits counts and SHA-256, not component details. Example: node security-assurance/scan-source.mjs /checkout /private/bin /private/summary.json true true /private/product.cdx.json . Keep BOM private. Full schema validation and artifact provenance remain necessary before formal release gate. Container scanning, DAST, broad SAST rules and verified evidence enforcement remain #199 work.
77 changes: 77 additions & 0 deletions security-assurance/sast-sbom.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { spawnSync } from 'node:child_process';
import { readFileSync, writeFileSync, mkdirSync, lstatSync, realpathSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { resolve, relative, isAbsolute, dirname, join, extname } from 'node:path';
import { fileURLToPath } from 'node:url';
const lock=JSON.parse(readFileSync(new URL('./scanner-lock.json',import.meta.url),'utf8'));
const rules=fileURLToPath(new URL('./semgrep-rules.yml',import.meta.url));
const extensions=new Set(['.js','.jsx','.mjs','.cjs','.ts','.tsx','.mts','.cts']);
const outcome=(status,findings=0,files=0)=>({status,findings,files});
const normalizedPath=p=>typeof p==='string'?p.replace(/^\/src\//,'').replace(/^\.\//,''):null;
export function sastResult(exit,data,expected) {
if(![0,1].includes(exit)||!Array.isArray(data?.results)||!Array.isArray(data.errors)||
data.errors.length||!Array.isArray(data.paths?.scanned)||!Array.isArray(expected))return outcome('ERROR');
if(!expected.length)return outcome('NO_COVERAGE');
const scanned=new Set(data.paths.scanned.map(normalizedPath));
if(scanned.size!==expected.length||expected.some(p=>!scanned.has(p)))return outcome('NO_COVERAGE',data.results.length,scanned.size);
if(!data.results.every(r=>typeof r?.check_id==='string'&&r.check_id.length&&scanned.has(normalizedPath(r.path))))return outcome('ERROR');
if((exit===0)!==(data.results.length===0))return outcome('ERROR');
return outcome(data.results.length?'FINDINGS':'CLEAN',data.results.length,scanned.size);
}
export function runSast(root,tracked,tmp,env) {
const expected=tracked.filter(p=>extensions.has(extname(p)));
if(!expected.length||expected.length>2000)return outcome('NO_COVERAGE');
const snapshot=join(tmp,'sast-source');mkdirSync(snapshot,{mode:0o700});
let total=0;
try {
for(const p of expected){
const src=resolve(root,p), rel=relative(root,realpathSync(src)), info=lstatSync(src);
if(rel!==p||rel.startsWith('..')||isAbsolute(rel)||!info.isFile()||info.size>1000000)return outcome('NO_COVERAGE');
total+=info.size;if(total>50*1024*1024)return outcome('NO_COVERAGE');
const dst=join(snapshot,p);mkdirSync(dirname(dst),{recursive:true,mode:0o700});writeFileSync(dst,readFileSync(src),{mode:0o600});
}
const image=lock.tools.semgrep.image;
const pull=spawnSync('docker',['pull','--platform','linux/amd64',image],{stdio:'ignore',timeout:240000,env});
if(pull.status!==0||pull.error)return outcome('ERROR');
const r=spawnSync('docker',['run','--rm','--pull=never','--platform','linux/amd64','--network','none','--read-only',
'--cap-drop','ALL','--security-opt','no-new-privileges','--pids-limit','256','--memory','2g','--cpus','2',
'--user',process.getuid()+':'+process.getgid(),'--tmpfs','/tmp:rw,nosuid,nodev,size=256m','-e','HOME=/tmp','-e','SEMGREP_LOG_FILE=/tmp/semgrep.log',
'--mount','type=bind,src='+snapshot+',dst=/src,readonly','--mount','type=bind,src='+rules+',dst=/appfactory-rules.yml,readonly',
'--workdir','/src','--entrypoint','semgrep',image,'scan','--oss-only','--config','/appfactory-rules.yml','--metrics=off',
'--disable-version-check','--disable-nosem','--no-git-ignore','--strict','--error','--json','--jobs=2','--max-target-bytes=1000000','/src'],
{encoding:'utf8',maxBuffer:32*1024*1024,timeout:240000,env,stdio:['ignore','pipe','ignore']});
if(r.error||r.signal)return outcome('ERROR');
return sastResult(r.status,JSON.parse(r.stdout),expected);
}catch{return outcome('ERROR')}
}
// Inventory-only CycloneDX 1.5 from existing OSV all-packages output. No invented graph.
export function componentBom(revision,reports) {
if(!/^[a-f0-9]{40}$/.test(revision)||!Array.isArray(reports)||!reports.length)throw Error('missing inventory');
const components=new Map();
for(const report of reports){
if(!Array.isArray(report?.results)||!report.results.length)throw Error('missing results');
let packages=0;
for(const s of report.results){
if(!Array.isArray(s?.packages))throw Error('missing packages');
for(const item of s.packages){
const p=item?.package;
if(!p||p.ecosystem!=='npm'||typeof p.name!=='string'||!p.name||typeof p.version!=='string'||!p.version)throw Error('unsupported package');
const key=JSON.stringify([p.ecosystem,p.name,p.version]);const id=createHash('sha256').update(key).digest('hex');
components.set(key,{type:'library',name:p.name,version:p.version,'bom-ref':'urn:appfactory:component:'+id});
packages++;
}
}
if(!packages)throw Error('empty lockfile inventory');
}
return {bomFormat:'CycloneDX',specVersion:'1.5',version:1,metadata:{component:{type:'application',name:'source-candidate',version:revision},
properties:[{name:'appfactory:scope',value:'OSV npm lockfile component inventory; dependency graph and deployment completeness not verified'}]},
components:[...components.entries()].sort(([a],[b])=>a<b?-1:a>b?1:0).map(([,v])=>v)};
}
export function bomSummary(revision,reports,dependencyStatus,destination) {
if(!['CLEAN','FINDINGS'].includes(dependencyStatus))return {status:'NO_COVERAGE',components:0};
try{
const bom=componentBom(revision,reports),bytes=JSON.stringify(bom,null,2)+'\n';
if(destination)writeFileSync(destination,bytes,{flag:'wx',mode:0o600});
return {status:'GENERATED',components:bom.components.length,sha256:createHash('sha256').update(bytes).digest('hex'),specVersion:bom.specVersion};
}catch{return {status:'ERROR',components:0}}
}
17 changes: 11 additions & 6 deletions security-assurance/scan-source.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import { readFileSync, writeFileSync, mkdtempSync, rmSync, statSync, lstatSync,
import { tmpdir } from 'node:os';
import { resolve, relative, isAbsolute, join, basename } from 'node:path';
import { secretResult, dependencyResult, summarizeDependencies, sourceGate } from './scanner-results.mjs';
import { runSast, bomSummary } from './sast-sbom.mjs';
const lock=JSON.parse(readFileSync(new URL('./scanner-lock.json',import.meta.url),'utf8'));
const [rootArg,binArg,outArg,onlineArg]=process.argv.slice(2);
const [rootArg,binArg,outArg,onlineArg,extendedArg='false',bomArg]=process.argv.slice(2);
const safeEnv={...process.env,HOME:process.env.HOME};
delete safeEnv.GITHUB_TOKEN; delete safeEnv.GH_TOKEN; delete safeEnv.ACTIONS_RUNTIME_TOKEN; delete safeEnv.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
delete safeEnv.GITLEAKS_CONFIG; delete safeEnv.GITLEAKS_CONFIG_TOML;
Expand All @@ -24,7 +25,7 @@ function parse(path) {
function within(root,file) {const p=relative(root,realpathSync(file));return p!==''&&!p.startsWith('..')&&!isAbsolute(p)}
let tmp;
try {
if(!rootArg||!binArg||!outArg||!['true','false'].includes(onlineArg))throw Error('arguments required');
if(!rootArg||!binArg||!outArg||!['true','false'].includes(onlineArg)||!['true','false'].includes(extendedArg)||(bomArg&&extendedArg!=='true'))throw Error('arguments required');
const root=realpathSync(rootArg), bin=realpathSync(binArg), out=resolve(outArg);
if(resolve(git(root,['rev-parse','--show-toplevel']).trim())!==root||
git(root,['rev-parse','--is-shallow-repository']).trim()!=='false'||
Expand All @@ -41,6 +42,7 @@ try {
// Phase 1 intentionally covers Node lockfiles only; do not infer other ecosystems are clean.
const files=tracked.filter(x=>['package-lock.json','npm-shrinkwrap.json','pnpm-lock.yaml','yarn.lock'].includes(basename(x)));
const unsupported=tracked.filter(x=>['Cargo.lock','go.mod','go.sum','poetry.lock','uv.lock','composer.lock','Gemfile.lock','Pipfile.lock','requirements.txt','gradle.lockfile','packages.lock.json'].includes(basename(x))).length;
const reports=[];
let dependencies={status:'NOT_RUN',findings:0,packages:0,lockfiles:files.length};
if(onlineArg==='true') {
if(files.length>20) dependencies={status:'ERROR',findings:0,packages:0,lockfiles:files.length};
Expand All @@ -51,16 +53,19 @@ try {
if(!within(root,absolute)||!lstatSync(absolute).isFile()) {scans.push({status:'ERROR',findings:0,packages:0});continue;}
const raw=join(tmp,'osv-'+i+'.json');
const exit=run(join(bin,'osv'),['scan','source','--config',osvConfig,'--all-packages','--format','json','--output-file',raw,'-L',absolute],root);
scans.push(dependencyResult(exit,parse(raw)));
const parsed=parse(raw);scans.push(dependencyResult(exit,parsed));reports.push(parsed);
}
dependencies=summarizeDependencies(scans);
if(unsupported>0&&dependencies.status==='CLEAN')dependencies.status='NO_COVERAGE';
}
}
const report={schemaVersion:1,revision:rev,generatedAt:new Date().toISOString(),scope:'HEAD reachable history and tracked Node lockfiles; not a full product assessment',tools:lock.tools,secrets,dependencies:{...dependencies,unsupportedKnownFiles:unsupported},sast:'NOT_RUN',sbom:'NOT_RUN',container:'NOT_RUN',dast:'NOT_RUN',certification:false,releaseEligible:false};
const extended=extendedArg==='true';
const sast=extended?runSast(root,tracked,tmp,safeEnv):{status:'NOT_RUN',findings:0,files:0};
const sbom=extended?bomSummary(rev,reports,dependencies.status,bomArg?resolve(bomArg):undefined):{status:'NOT_RUN',components:0};
const report={schemaVersion:1,revision:rev,generatedAt:new Date().toISOString(),scope:'HEAD reachable history and tracked Node lockfiles; not a full product assessment',tools:lock.tools,secrets,dependencies:{...dependencies,unsupportedKnownFiles:unsupported},sast,sbom,container:'NOT_RUN',dast:'NOT_RUN',certification:false,releaseEligible:false};
writeFileSync(out,JSON.stringify(report,null,2)+'\n',{flag:'wx',mode:0o600});
console.log(JSON.stringify({revision:rev,secrets:secrets.status,dependencies:dependencies.status,sourceChecksClean:sourceGate(report),releaseEligible:false}));
if(!sourceGate(report))process.exitCode=2;
console.log(JSON.stringify({revision:rev,secrets:secrets.status,dependencies:dependencies.status,sourceChecksClean:sourceGate(report),sast:sast.status,sbom:sbom.status,releaseEligible:false}));
if(!sourceGate(report)||(extended&&(sast.status!=='CLEAN'||sbom.status!=='GENERATED')))process.exitCode=2;
} catch {
console.error('Source scanner execution or precondition failed. No security conclusion.');
process.exitCode=1;
Expand Down
6 changes: 6 additions & 0 deletions security-assurance/scanner-lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,12 @@
"version": "2.7.1",
"url": "https://github.com/google/osv-scanner/releases/download/v2.7.1/osv-scanner_linux_amd64",
"sha256": "fb7dab19a8bd9bbe5c3189f09d4b7ee1820c9553a23bac202648a56efd2f6ee8"
},
"semgrep": {
"version": "1.187.0",
"image": "semgrep/semgrep@sha256:c4f4812643a1e6879b4148710805b88e84446cb7416eb0b0e515bb642c914341",
"platform": "linux/amd64",
"source": "https://hub.docker.com/layers/semgrep/semgrep/1.187.0-nonroot/images/sha256-c4f4812643a1e6879b4148710805b88e84446cb7416eb0b0e515bb642c914341"
}
}
}
16 changes: 16 additions & 0 deletions security-assurance/semgrep-rules.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
rules:
- id: appfactory-js-dynamic-eval
languages: [javascript, typescript]
severity: ERROR
message: Review dynamic code evaluation.
pattern: eval(...)
- id: appfactory-js-dynamic-function
languages: [javascript, typescript]
severity: ERROR
message: Review dynamic Function construction.
pattern: new Function(...)
- id: appfactory-js-document-write
languages: [javascript, typescript]
severity: WARNING
message: Review dynamic HTML output and contextual escaping.
pattern: document.write(...)
20 changes: 20 additions & 0 deletions test/security-assurance.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,23 @@ test('every scoped lockfile must have coverage; never infer release eligibility'
assert.equal(sourceGate({secrets:{status:'CLEAN'},dependencies:{status:'NOT_RUN'}}),false);
assert.equal(sourceGate({secrets:{status:'CLEAN'},dependencies:clean}),true);
});

import { sastResult, componentBom, bomSummary } from '../security-assurance/sast-sbom.mjs';
test('SAST rejects parse errors, missing paths and suppressed coverage',()=>{
const clean={results:[],errors:[],paths:{scanned:['/src/a.js']}};
assert.equal(sastResult(0,clean,['a.js']).status,'CLEAN');
assert.equal(sastResult(0,clean,['a.js','b.js']).status,'NO_COVERAGE');
assert.equal(sastResult(0,{...clean,errors:[{}]},['a.js']).status,'ERROR');
assert.equal(sastResult(1,{...clean,results:[{check_id:'rule',path:'a.js'}]},['a.js']).status,'FINDINGS');
assert.equal(sastResult(0,{...clean,results:[{check_id:'rule',path:'a.js'}]},['a.js']).status,'ERROR');
});
test('CycloneDX inventory includes clean and vulnerable npm components without fabricating a graph',()=>{
const fixture={results:[{packages:[{package:{ecosystem:'npm',name:'a',version:'1.0.0'}},{package:{ecosystem:'npm',name:'b',version:'2.0.0'},vulnerabilities:[{id:'fixture'}]}]}]};
const b=componentBom(rev,[fixture,fixture]);assert.equal(b.bomFormat,'CycloneDX');assert.equal(b.specVersion,'1.5');
assert.equal(b.components.length,2);assert.equal(b.dependencies,undefined);
assert.deepEqual(componentBom(rev,[fixture]),b);
assert.equal(bomSummary(rev,[fixture],'FINDINGS').status,'GENERATED');
assert.equal(bomSummary(rev,[fixture],'ERROR').status,'NO_COVERAGE');
assert.throws(()=>componentBom(rev,[{results:[{packages:[]}]}]));
assert.equal(bomSummary(rev,[{results:[{packages:[{package:{name:'x',version:'1',ecosystem:'Go'}}]}]}],'CLEAN').status,'ERROR');
});
Loading
Loading